text
stringlengths
5
22M
id
stringlengths
12
177
metadata
dict
__index_level_0__
int64
0
1.37k
# model settings input_size = 300 model = dict( type='SingleStageDetector', pretrained='open-mmlab://vgg16_caffe', backbone=dict( type='SSDVGG', input_size=input_size, depth=16, with_last_pool=False, ceil_mode=True, out_indices=(3, 4), out_feature_indices=(22, 34), l2_norm_scale=20), neck=None, bbox_head=dict( type='SSDHead', in_channels=(512, 1024, 512, 256, 256, 256), num_classes=80, anchor_generator=dict( type='SSDAnchorGenerator', scale_major=False, input_size=input_size, basesize_ratio_range=(0.15, 0.9), strides=[8, 16, 32, 64, 100, 300], ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2])), train_cfg=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0., ignore_iof_thr=-1, gt_max_assign_all=False), smoothl1_beta=1., allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.45), min_bbox_size=0, score_thr=0.02, max_per_img=200)) cudnn_benchmark = True
Cream/EfficientViT/downstream/configs/_base_/models/ssd300.py/0
{ "file_path": "Cream/EfficientViT/downstream/configs/_base_/models/ssd300.py", "repo_id": "Cream", "token_count": 866 }
294
import random import warnings import numpy as np import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, Fp16OptimizerHook, OptimizerHook, build_optimizer, build_runner) from mmcv.utils import build_from_cfg from mmdet.core import DistEvalHook, EvalHook from mmdet.datasets import (build_dataloader, build_dataset, replace_ImageToTensor) from mmdet.utils import get_root_logger try: import apex except: print('apex is not installed') def set_random_seed(seed, deterministic=False): """Set random seed. Args: seed (int): Seed to be used. deterministic (bool): Whether to set the deterministic option for CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` to True and `torch.backends.cudnn.benchmark` to False. Default: False. """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) if deterministic: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def train_detector(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None): logger = get_root_logger(cfg.log_level) # prepare data loaders dataset = dataset if isinstance(dataset, (list, tuple)) else [dataset] if 'imgs_per_gpu' in cfg.data: logger.warning('"imgs_per_gpu" is deprecated in MMDet V2.0. ' 'Please use "samples_per_gpu" instead') if 'samples_per_gpu' in cfg.data: logger.warning( f'Got "imgs_per_gpu"={cfg.data.imgs_per_gpu} and ' f'"samples_per_gpu"={cfg.data.samples_per_gpu}, "imgs_per_gpu"' f'={cfg.data.imgs_per_gpu} is used in this experiments') else: logger.warning( 'Automatically set "samples_per_gpu"="imgs_per_gpu"=' f'{cfg.data.imgs_per_gpu} in this experiments') cfg.data.samples_per_gpu = cfg.data.imgs_per_gpu data_loaders = [ build_dataloader( ds, cfg.data.samples_per_gpu, cfg.data.workers_per_gpu, # cfg.gpus will be ignored if distributed len(cfg.gpu_ids), dist=distributed, seed=cfg.seed) for ds in dataset ] # build optimizer optimizer = build_optimizer(model, cfg.optimizer) # use apex fp16 optimizer if cfg.optimizer_config.get("type", None) and cfg.optimizer_config["type"] == "DistOptimizerHook": if cfg.optimizer_config.get("use_fp16", False): model, optimizer = apex.amp.initialize( model.cuda(), optimizer, opt_level="O1") for m in model.modules(): if hasattr(m, "fp16_enabled"): m.fp16_enabled = True # put model on gpus if distributed: find_unused_parameters = cfg.get('find_unused_parameters', False) # Sets the `find_unused_parameters` parameter in # torch.nn.parallel.DistributedDataParallel model = MMDistributedDataParallel( model.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False, find_unused_parameters=find_unused_parameters) else: model = MMDataParallel( model.cuda(cfg.gpu_ids[0]), device_ids=cfg.gpu_ids) if 'runner' not in cfg: cfg.runner = { 'type': 'EpochBasedRunner', 'max_epochs': cfg.total_epochs } warnings.warn( 'config is now expected to have a `runner` section, ' 'please set `runner` in your config.', UserWarning) else: if 'total_epochs' in cfg: assert cfg.total_epochs == cfg.runner.max_epochs # build runner runner = build_runner( cfg.runner, default_args=dict( model=model, optimizer=optimizer, work_dir=cfg.work_dir, logger=logger, meta=meta)) # an ugly workaround to make .log and .log.json filenames the same runner.timestamp = timestamp # fp16 setting fp16_cfg = cfg.get('fp16', None) if fp16_cfg is not None: optimizer_config = Fp16OptimizerHook( **cfg.optimizer_config, **fp16_cfg, distributed=distributed) elif distributed and 'type' not in cfg.optimizer_config: optimizer_config = OptimizerHook(**cfg.optimizer_config) else: optimizer_config = cfg.optimizer_config # register hooks runner.register_training_hooks(cfg.lr_config, optimizer_config, cfg.checkpoint_config, cfg.log_config, cfg.get('momentum_config', None)) if distributed: if isinstance(runner, EpochBasedRunner): runner.register_hook(DistSamplerSeedHook()) # register eval hooks if validate: # Support batch_size > 1 in validation val_samples_per_gpu = cfg.data.val.pop('samples_per_gpu', 1) if val_samples_per_gpu > 1: # Replace 'ImageToTensor' to 'DefaultFormatBundle' cfg.data.val.pipeline = replace_ImageToTensor( cfg.data.val.pipeline) val_dataset = build_dataset(cfg.data.val, dict(test_mode=True)) val_dataloader = build_dataloader( val_dataset, samples_per_gpu=val_samples_per_gpu, workers_per_gpu=cfg.data.workers_per_gpu, dist=distributed, shuffle=False) eval_cfg = cfg.get('evaluation', {}) eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner' eval_hook = DistEvalHook if distributed else EvalHook runner.register_hook(eval_hook(val_dataloader, **eval_cfg)) # user-defined hooks if cfg.get('custom_hooks', None): custom_hooks = cfg.custom_hooks assert isinstance(custom_hooks, list), \ f'custom_hooks expect list type, but got {type(custom_hooks)}' for hook_cfg in cfg.custom_hooks: assert isinstance(hook_cfg, dict), \ 'Each item in custom_hooks expects dict type, but got ' \ f'{type(hook_cfg)}' hook_cfg = hook_cfg.copy() priority = hook_cfg.pop('priority', 'NORMAL') hook = build_from_cfg(hook_cfg, HOOKS) runner.register_hook(hook, priority=priority) if cfg.resume_from: runner.resume(cfg.resume_from) elif cfg.load_from: runner.load_checkpoint(cfg.load_from) runner.run(data_loaders, cfg.workflow)
Cream/EfficientViT/downstream/mmdet_custom/apis/train.py/0
{ "file_path": "Cream/EfficientViT/downstream/mmdet_custom/apis/train.py", "repo_id": "Cream", "token_count": 3309 }
295
# only for evaluation MODEL: TYPE: swin NAME: swin_large_patch4_window7_224 SWIN: EMBED_DIM: 192 DEPTHS: [ 2, 2, 18, 2 ] NUM_HEADS: [ 6, 12, 24, 48 ] WINDOW_SIZE: 7
Cream/MiniViT/Mini-Swin/configs/swin_large_patch4_window7_224.yaml/0
{ "file_path": "Cream/MiniViT/Mini-Swin/configs/swin_large_patch4_window7_224.yaml", "repo_id": "Cream", "token_count": 94 }
296
# TinyCLIP-ViT Inference ## Download checkpoints Download a checkpoint from [Model Zoo](../README.md#model-zoo). ## Zero-shot inference on ImageNet-1k Please change the paths to `imagenet-val` and `resume`. ### For manual weight inference checkpoint: <details> <summary>Evaluate TinyCLIP ViT-39M/16 + Text-19M (YFCC-15M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model TinyCLIP-ViT-39M-16-Text-19M \ --eval \ --resume ./checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-8M/16 + Text-3M (YFCC-15M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model TinyCLIP-ViT-8M-16-Text-3M \ --eval \ --resume ./checkpoints/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ResNet-30M + Text-29M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model TinyCLIP-ResNet-30M-Text-29M \ --eval \ --resume ./checkpoints/TinyCLIP-ResNet-30M-Text-29M-LAION400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ResNet-19M + Text-19M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model TinyCLIP-ResNet-19M-Text-19M \ --eval \ --resume ./checkpoints/TinyCLIP-ResNet-19M-Text-19M-LAION400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-61M/32 + Text-29M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model TinyCLIP-ViT-61M-32-Text-29M \ --eval \ --resume ./checkpoints/TinyCLIP-ViT-61M-32-Text-29M-LAION400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-40M/32 + Text-19M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model TinyCLIP-ViT-40M-32-Text-19M \ --eval \ --resume ./checkpoints/TinyCLIP-ViT-40M-32-Text-19M-LAION400M.pt </code></pre> </details> ### For auto weight inference checkpoint: <details> <summary>Evaluate TinyCLIP ViT-63M/32 + Text-31M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model ViT-B-32 \ --prune-image \ --prune-text \ --eval \ --resume ./checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAION400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-45M/32 + Text-18M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model ViT-B-32 \ --prune-image \ --prune-text \ --eval \ --resume ./checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAION400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-22M/32 + Text-10M (LAION-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model ViT-B-32 \ --prune-image \ --prune-text \ --eval \ --resume ./checkpoints/TinyCLIP-auto-ViT-22M-32-Text-10M-LAION400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-63M/32 + Text-31M (LAION+YFCC-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model ViT-B-32 \ --prune-image \ --prune-text \ --eval \ --resume ./checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAIONYFCC400M.pt </code></pre> </details> <details> <summary>Evaluate TinyCLIP ViT-45M/32 + Text-18M (LAION+YFCC-400M) </summary> <pre><code>python -m torch.distributed.launch --use_env --nproc_per_node 8 src/training/main_for_test.py \ --imagenet-val ./ImageNet \ --model ViT-B-32 \ --prune-image \ --prune-text \ --eval \ --resume ./checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAIONYFCC400M.pt </code></pre> </details>
Cream/TinyCLIP/docs/EVALUATION.md/0
{ "file_path": "Cream/TinyCLIP/docs/EVALUATION.md", "repo_id": "Cream", "token_count": 1806 }
297
from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD from .factory import list_models, create_model, create_model_and_transforms, get_tokenizer, add_model_config, \ load_model, load_exp from .loss import ClipLoss from .model import CLIP, CLIPTextCfg, CLIPVisionCfg, convert_weights_to_fp16, trace_model from .openai import load_openai_model, list_openai_models from .pretrained import list_pretrained, list_pretrained_tag_models, list_pretrained_model_tags,\ get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained from .tokenizer import SimpleTokenizer, tokenize from .transform import image_transform from .l0module import L0Module
Cream/TinyCLIP/src/open_clip/__init__.py/0
{ "file_path": "Cream/TinyCLIP/src/open_clip/__init__.py", "repo_id": "Cream", "token_count": 229 }
298
import torch import numpy as np def ampscaler_get_grad_norm(parameters, norm_type: float = 2.0) -> torch.Tensor: if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = [p for p in parameters if p.grad is not None] norm_type = float(norm_type) if len(parameters) == 0: return torch.tensor(0.) device = parameters[0].grad.device if norm_type == np.inf: total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters) else: total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type) return total_norm class NativeScalerWithGradNormCount: state_dict_key = "amp_scaler" def __init__(self, *args, **kwargs): self._scaler = torch.cuda.amp.GradScaler(*args, **kwargs) def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): self._scaler.scale(loss).backward(create_graph=create_graph) if update_grad: if clip_grad is not None: assert parameters is not None # unscale the gradients of optimizer's assigned params in-place self._scaler.unscale_(optimizer) norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad) else: self._scaler.unscale_(optimizer) norm = ampscaler_get_grad_norm(parameters) self._scaler.step(optimizer) self._scaler.update() else: norm = None return norm def state_dict(self): return self._scaler.state_dict() def load_state_dict(self, state_dict): self._scaler.load_state_dict(state_dict)
Cream/TinyCLIP/src/training/loss_scaler.py/0
{ "file_path": "Cream/TinyCLIP/src/training/loss_scaler.py", "repo_id": "Cream", "token_count": 846 }
299
# TinyViT: Fast Pretraining Distillation for Small Vision Transformers [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Tiny%20vision%20transformer%20models,%20SOTA%20performance!!&url=https://github.com/microsoft/Cream/tree/main/TinyViT&via=houwen_peng&hashtags=ViT,tiny,efficient) :pushpin: This is an official PyTorch implementation of **[ECCV 2022]** - [TinyViT: Fast Pretraining Distillation for Small Vision Transformers](https://arxiv.org/pdf/2207.10666.pdf). TinyViT is a new family of **tiny and efficient** vision transformers pretrained on **large-scale** datasets with our proposed **fast distillation framework**. The central idea is to **transfer knowledge** from **large pretrained models** to small ones. The logits of large teacher models are sparsified and stored in disk in advance to **save the memory cost and computation overheads**. :rocket: TinyViT with **only 21M parameters** achieves **84.8%** top-1 accuracy on ImageNet-1k, and **86.5%** accuracy under 512x512 resolutions. <div align="center"> <img width="80%" alt="TinyViT overview" src=".figure/framework.png"/> </div> :sunny: Hiring research interns for neural architecture search, tiny transformer design, model compression projects: [email protected]. ## Highlights <div align="center"> <img width="80%" src=".figure/performance.png"/> </div> * TinyViT-21M ![](./.figure/distill.png) on IN-22k achieves **84.8%** top-1 accuracy on IN-1k, and **86.5%** accuracy under 512x512 resolutions. * TinyViT-21M **trained from scratch on IN-1k** without distillation achieves **83.1** top-1 accuracy, under **4.3 GFLOPs** and **1,571 images/s** throughput on V100 GPU. * TinyViT-5M ![](./.figure/distill.png) reaches **80.7%** top-1 accuracy on IN-1k under 3,060 images/s throughput. * Save teacher logits **once**, and **reuse** the saved sparse logits to distill **arbitrary students without overhead** of teacher model. It takes **16 GB / 481 GB** storage space for IN-1k (300 epochs) and IN-22k (90 epochs), respectively. ## Features 1. **Efficient Distillation**. The teacher logits can be saved in parallel and reused for arbitrary student models, to avoid re-forwarding cost of the large teacher model. 2. **Reproducibility**. We provide the hyper-parameters of [IN-1k training](./configs/1k), [IN-22k pre-training with distillation](./configs/22k_distill), [IN-22kto1k fine-tuning](./configs/22kto1k), and [higher resolution fine-tuning](./configs/higher_resolution). In addition, all training logs are public (in Model Zoo). 3. **Ease of Use**. One file to build a TinyViT model. The file [`models/tiny_vit.py`](./models/tiny_vit.py) defines TinyViT model family. ```python from tiny_vit import tiny_vit_21m_224 model = tiny_vit_21m_224(pretrained=True) output = model(image) ``` An inference script: [`inference.py`](./inference.py). 4. **Extensibility**. Add custom dataset, student and teacher models with no need to modify your code. The class [`DatasetWrapper`](./data/build.py#L74) wraps the general dataset to support saving and loading sparse logits. It only need the logits of models for knowledge distillation. 5. **Public teacher model**. We provide CLIP-ViT-Large/16-22k, a powerful teacher model on pretraining distillation (Acc@1 85.894 Acc@5 97.566 on IN-1k). We finetuned CLIP-ViT-Large/16 released by OpenAI on IN-22k. 6. **Online Logging**. Support [wandb](https://wandb.ai) for checking the results anytime anywhere. ## Model Zoo Model | Pretrain | Input | Acc@1 | Acc@5 | #Params | MACs | FPS | 22k Model | 1k Model :-----------------------------------------:|:---------|:-----:|:-----:|:-----:|:-------:|:----:|:----:|:---------:|:--------: TinyViT-5M ![](./.figure/distill.png) | IN-22k |224x224| 80.7 | 95.6 | 5.4M | 1.3G | 3,060|[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth)/[config](./configs/22k_distill/tiny_vit_5m_22k_distill.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.log)|[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.pth)/[config](./configs/22kto1k/tiny_vit_5m_22kto1k.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.log) TinyViT-11M ![](./.figure/distill.png) | IN-22k |224x224| 83.2 | 96.5 | 11M | 2.0G | 2,468|[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth)/[config](./configs/22k_distill/tiny_vit_11m_22k_distill.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.log)|[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.pth)/[config](./configs/22kto1k/tiny_vit_11m_22kto1k.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.log) TinyViT-21M ![](./.figure/distill.png) | IN-22k |224x224| 84.8 | 97.3 | 21M | 4.3G | 1,571|[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth)/[config](./configs/22k_distill/tiny_vit_21m_22k_distill.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.log)|[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.pth)/[config](./configs/22kto1k/tiny_vit_21m_22kto1k.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.log) TinyViT-21M-384 ![](./.figure/distill.png) | IN-22k |384x384| 86.2 | 97.8 | 21M | 13.8G| 394 | - |[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.pth)/[config](./configs/higher_resolution/tiny_vit_21m_224to384.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.log) TinyViT-21M-512 ![](./.figure/distill.png) | IN-22k |512x512| 86.5 | 97.9 | 21M | 27.0G| 167 | - |[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.pth)/[config](./configs/higher_resolution/tiny_vit_21m_384to512.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.log) TinyViT-5M | IN-1k |224x224| 79.1 | 94.8 | 5.4M | 1.3G | 3,060| - |[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_1k.pth)/[config](./configs/1k/tiny_vit_5m.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_1k.log) TinyViT-11M | IN-1k |224x224| 81.5 | 95.8 | 11M | 2.0G | 2,468| - |[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_1k.pth)/[config](./configs/1k/tiny_vit_11m.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_1k.log) TinyViT-21M | IN-1k |224x224| 83.1 | 96.5 | 21M | 4.3G | 1,571| - |[link](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_1k.pth)/[config](./configs/1k/tiny_vit_21m.yaml)/[log](https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_1k.log) ImageNet-22k (IN-22k) is the same as ImageNet-21k (IN-21k), where the number of classes is 21,841. The models with ![](./.figure/distill.png) are pretrained on ImageNet-22k with the distillation of CLIP-ViT-L/14-22k, then finetuned on ImageNet-1k. We finetune the 1k models on IN-1k to higher resolution progressively (224 -> 384 -> 512) [[detail]](./docs/TRAINING.md), without any IN-1k knowledge distillation. ## Getting Started :beginner: Here is the setup tutorial and evaluation scripts. ### Install dependencies and prepare datasets - [Preparation](./docs/PREPARATION.md) ### Evaluate it ! - [Evaluation](./docs/EVALUATION.md) ## Pretrain a TinyViT model on ImageNet :beginner: For the proposed fast pretraining distillation, we need to **save teacher sparse logits** firstly, then **pretrain a model**. - [How to save teacher sparse logits?](./docs/SAVE_TEACHER_LOGITS.md) - [Let's train a TinyViT model](./docs/TRAINING.md) ## Citation If this repo is helpful for you, please consider to cite it. :mega: Thank you! :) ```bibtex @InProceedings{tiny_vit, title={TinyViT: Fast Pretraining Distillation for Small Vision Transformers}, author={Wu, Kan and Zhang, Jinnian and Peng, Houwen and Liu, Mengchen and Xiao, Bin and Fu, Jianlong and Yuan, Lu}, booktitle={European conference on computer vision (ECCV)}, year={2022} } ``` ## Research Citing Our Work :tada: We would like to acknowledge the following research work that cites and utilizes our method: <details> <summary> <a href="https://github.com/ChaoningZhang/MobileSAM">MobileSAM</a> (Faster Segment Anything: Towards Lightweight SAM for Mobile Applications) [<b>bib</b>] </summary> ```bibtex @article{zhang2023faster, title={Faster Segment Anything: Towards Lightweight SAM for Mobile Applications}, author={Zhang, Chaoning and Han, Dongshen and Qiao, Yu and Kim, Jung Uk and Bae, Sung Ho and Lee, Seungkyu and Hong, Choong Seon}, journal={arXiv preprint arXiv:2306.14289}, year={2023} } ``` </details> ## Acknowledge Our code is based on [Swin Transformer](https://github.com/microsoft/swin-transformer), [LeViT](https://github.com/facebookresearch/LeViT), [pytorch-image-models](https://github.com/rwightman/pytorch-image-models), [CLIP](https://github.com/openai/CLIP) and [PyTorch](https://github.com/pytorch/pytorch). Thank contributors for their awesome contribution! ## License - [License](./LICENSE)
Cream/TinyViT/README.md/0
{ "file_path": "Cream/TinyViT/README.md", "repo_id": "Cream", "token_count": 3919 }
300
from .auto_augment import RandAugment, AutoAugment, rand_augment_ops, auto_augment_policy,\ rand_augment_transform, auto_augment_transform from .config import resolve_data_config from .constants import * from .dataset import ImageDataset, IterableImageDataset, AugMixDataset from .dataset_factory import create_dataset from .loader import create_loader from .mixup import Mixup, FastCollateMixup from .parsers import create_parser from .real_labels import RealLabelsImagenet from .transforms import * from .transforms_factory import create_transform
Cream/TinyViT/data/augmentation/__init__.py/0
{ "file_path": "Cream/TinyViT/data/augmentation/__init__.py", "repo_id": "Cream", "token_count": 168 }
301
from abc import abstractmethod class Parser: def __init__(self): pass @abstractmethod def _filename(self, index, basename=False, absolute=False): pass def filename(self, index, basename=False, absolute=False): return self._filename(index, basename=basename, absolute=absolute) def filenames(self, basename=False, absolute=False): return [self._filename(index, basename=basename, absolute=absolute) for index in range(len(self))]
Cream/TinyViT/data/augmentation/parsers/parser.py/0
{ "file_path": "Cream/TinyViT/data/augmentation/parsers/parser.py", "repo_id": "Cream", "token_count": 172 }
302
# Preparation ### Install the requirements Run the following command to install the dependences: ```bash pip install -r requirements.txt ``` ### Data Preparation We need to prepare ImageNet-1k and ImageNet-22k datasets from [`http://www.image-net.org/`](http://www.image-net.org/). - ImageNet-1k ImageNet-1k contains 1.28 M images for training and 50 K images for validation. The train set and validation set should be saved as the `*.tar` archives: ``` ImageNet/ β”œβ”€β”€ train.tar └── val.tar ``` Our code also supports storing images as individual files as follow: ``` ImageNet/ β”œβ”€β”€ train β”‚ β”œβ”€β”€ n01440764 β”‚ β”‚ β”œβ”€β”€ n01440764_10026.JPEG β”‚ β”‚ β”œβ”€β”€ n01440764_10027.JPEG ... β”œβ”€β”€ val β”‚ β”œβ”€β”€ n01440764 β”‚ β”‚ β”œβ”€β”€ ILSVRC2012_val_00000293.JPEG ``` - ImageNet-22k ImageNet-22k contains 14 M images with 21,841 classes, without overlapping part with ImageNet-1k validation set. The filelist (`in22k_image_names.txt`) can be download at [here](https://github.com/wkcn/TinyViT-model-zoo/releases/download/datasets/in22k_image_names.txt). Each class is stored as an archive file. ``` ImageNet-22k/ β”œβ”€β”€ in22k_image_names.txt β”œβ”€β”€ n00004475.zip β”œβ”€β”€ n00005787.zip β”œβ”€β”€ n00006024.zip ... β”œβ”€β”€ n15102455.zip └── n15102894.zip ``` The config `DATA.FNAME_FORMAT` defines the image filename format in the archive file, default: `{}.jpeg`. We need IN-1k to evaluate the model, so the folders should be placed like the following (`a soft link is available`): ``` datasets/ β”œβ”€β”€ ImageNet-22k/ # the folder of IN-22k └── ImageNet/ # the folder of IN-1k ```
Cream/TinyViT/docs/PREPARATION.md/0
{ "file_path": "Cream/TinyViT/docs/PREPARATION.md", "repo_id": "Cream", "token_count": 581 }
303
# -------------------------------------------------------- # TinyViT Save Teacher Logits # Copyright (c) 2022 Microsoft # Based on the code: Swin Transformer # (https://github.com/microsoft/swin-transformer) # Save teacher logits # -------------------------------------------------------- import os import time import random import argparse import datetime from collections import defaultdict import numpy as np import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from timm.utils import accuracy from my_meter import AverageMeter from config import get_config from models import build_model from data import build_loader from logger import create_logger from utils import load_checkpoint, NativeScalerWithGradNormCount, add_common_args from models.remap_layer import RemapLayer remap_layer_22kto1k = RemapLayer('./imagenet_1kto22k.txt') def parse_option(): parser = argparse.ArgumentParser( 'TinyViT saving sparse logits script', add_help=False) add_common_args(parser) parser.add_argument('--check-saved-logits', action='store_true', help='Check saved logits') parser.add_argument('--skip-eval', action='store_true', help='Skip evaluation') args = parser.parse_args() config = get_config(args) return args, config def main(config): dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader( config) logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") model = build_model(config) model.cuda() logger.info(str(model)) model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") optimizer = None lr_scheduler = None assert config.MODEL.RESUME loss_scaler = NativeScalerWithGradNormCount() load_checkpoint(config, model_without_ddp, optimizer, lr_scheduler, loss_scaler, logger) if not args.skip_eval and not args.check_saved_logits: acc1, acc5, loss = validate(config, data_loader_val, model) logger.info( f"Accuracy of the network on the {len(dataset_val)} test images: top-1 acc: {acc1:.1f}%, top-5 acc: {acc5:.1f}%") if args.check_saved_logits: logger.info("Start checking logits") else: logger.info("Start saving logits") start_time = time.time() for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): dataset_train.set_epoch(epoch) data_loader_train.sampler.set_epoch(epoch) if args.check_saved_logits: check_logits_one_epoch( config, model, data_loader_train, epoch, mixup_fn=mixup_fn) else: save_logits_one_epoch( config, model, data_loader_train, epoch, mixup_fn=mixup_fn) total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) logger.info('Saving logits time {}'.format(total_time_str)) @torch.no_grad() def save_logits_one_epoch(config, model, data_loader, epoch, mixup_fn): model.eval() num_steps = len(data_loader) batch_time = AverageMeter() meters = defaultdict(AverageMeter) start = time.time() end = time.time() topk = config.DISTILL.LOGITS_TOPK logits_manager = data_loader.dataset.get_manager() for idx, ((samples, targets), (keys, seeds)) in enumerate(data_loader): samples = samples.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if mixup_fn is not None: samples, targets = mixup_fn(samples, targets, seeds) original_targets = targets.argmax(dim=1) else: original_targets = targets with torch.cuda.amp.autocast(enabled=config.AMP_ENABLE): outputs = model(samples) acc1, acc5 = accuracy(outputs, original_targets, topk=(1, 5)) real_batch_size = len(samples) meters['teacher_acc1'].update(acc1.item(), real_batch_size) meters['teacher_acc5'].update(acc5.item(), real_batch_size) # save teacher logits softmax_prob = torch.softmax(outputs, -1) torch.cuda.synchronize() write_tic = time.time() values, indices = softmax_prob.topk( k=topk, dim=-1, largest=True, sorted=True) cpu_device = torch.device('cpu') values = values.detach().to(device=cpu_device, dtype=torch.float16) indices = indices.detach().to(device=cpu_device, dtype=torch.int16) seeds = seeds.numpy() values = values.numpy() indices = indices.numpy() # check data type assert seeds.dtype == np.int32, seeds.dtype assert indices.dtype == np.int16, indices.dtype assert values.dtype == np.float16, values.dtype for key, seed, indice, value in zip(keys, seeds, indices, values): bstr = seed.tobytes() + indice.tobytes() + value.tobytes() logits_manager.write(key, bstr) meters['write_time'].update(time.time() - write_tic) batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) etas = batch_time.avg * (num_steps - idx) extra_meters_str = '' for k, v in meters.items(): extra_meters_str += f'{k} {v.val:.4f} ({v.avg:.4f})\t' logger.info( f'Save: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t' f'eta {datetime.timedelta(seconds=int(etas))}\t' f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' f'{extra_meters_str}' f'mem {memory_used:.0f}MB') epoch_time = time.time() - start logger.info( f"EPOCH {epoch} save logits takes {datetime.timedelta(seconds=int(epoch_time))}") @torch.no_grad() def check_logits_one_epoch(config, model, data_loader, epoch, mixup_fn): model.eval() num_steps = len(data_loader) batch_time = AverageMeter() meters = defaultdict(AverageMeter) start = time.time() end = time.time() topk = config.DISTILL.LOGITS_TOPK for idx, ((samples, targets), (saved_logits_index, saved_logits_value, seeds)) in enumerate(data_loader): samples = samples.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if mixup_fn is not None: samples, targets = mixup_fn(samples, targets, seeds) with torch.cuda.amp.autocast(enabled=config.AMP_ENABLE): outputs = model(samples) softmax_prob = torch.softmax(outputs, -1) torch.cuda.synchronize() values, indices = softmax_prob.topk( k=topk, dim=-1, largest=True, sorted=True) meters['error'].update( (values - saved_logits_value.cuda()).abs().mean().item()) meters['diff_rate'].update(torch.count_nonzero( (indices != saved_logits_index.cuda())).item() / indices.numel()) batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) etas = batch_time.avg * (num_steps - idx) extra_meters_str = '' for k, v in meters.items(): extra_meters_str += f'{k} {v.val:.4f} ({v.avg:.4f})\t' logger.info( f'Check: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t' f'eta {datetime.timedelta(seconds=int(etas))}\t' f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' f'{extra_meters_str}' f'mem {memory_used:.0f}MB') epoch_time = time.time() - start logger.info( f"EPOCH {epoch} check logits takes {datetime.timedelta(seconds=int(epoch_time))}") @torch.no_grad() def validate(config, data_loader, model, num_classes=1000): criterion = torch.nn.CrossEntropyLoss() model.eval() batch_time = AverageMeter() loss_meter = AverageMeter() acc1_meter = AverageMeter() acc5_meter = AverageMeter() end = time.time() for idx, (images, target) in enumerate(data_loader): images = images.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # compute output with torch.cuda.amp.autocast(enabled=config.AMP_ENABLE): output = model(images) if num_classes == 1000: output_num_classes = output.size(-1) if output_num_classes == 21841: output = remap_layer_22kto1k(output) # measure accuracy and record loss loss = criterion(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) loss_meter.update(loss.item(), target.size(0)) acc1_meter.update(acc1.item(), target.size(0)) acc5_meter.update(acc5.item(), target.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) logger.info( f'Test: [{idx}/{len(data_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' f'Mem {memory_used:.0f}MB') acc1_meter.sync() acc5_meter.sync() logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') return acc1_meter.avg, acc5_meter.avg, loss_meter.avg if __name__ == '__main__': args, config = parse_option() config.defrost() assert len( config.DISTILL.TEACHER_LOGITS_PATH) > 0, "Please fill in the config DISTILL.TEACHER_LOGITS_PATH" config.DISTILL.ENABLED = True if not args.check_saved_logits: config.DISTILL.SAVE_TEACHER_LOGITS = True config.freeze() if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: rank = int(os.environ["RANK"]) world_size = int(os.environ['WORLD_SIZE']) print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}") else: rank = -1 world_size = -1 torch.cuda.set_device(config.LOCAL_RANK) torch.distributed.init_process_group( backend='nccl', init_method='env://', world_size=world_size, rank=rank) torch.distributed.barrier() # The seed changes with config, rank, world_size and epoch seed = config.SEED + dist.get_rank() + config.TRAIN.START_EPOCH * \ dist.get_world_size() torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True os.makedirs(config.OUTPUT, exist_ok=True) logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") if dist.get_rank() == 0: path = os.path.join(config.OUTPUT, "config.json") with open(path, "w") as f: f.write(config.dump()) logger.info(f"Full config saved to {path}") # print config logger.info(config.dump()) main(config)
Cream/TinyViT/save_logits.py/0
{ "file_path": "Cream/TinyViT/save_logits.py", "repo_id": "Cream", "token_count": 5300 }
304
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Backbone modules. """ from collections import OrderedDict import torch import torch.nn.functional as F import torchvision from torch import nn from torchvision.models._utils import IntermediateLayerGetter from typing import Dict, List from util.misc import NestedTensor, is_main_process from .position_encoding import build_position_encoding class FrozenBatchNorm2d(torch.nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed. Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than torchvision.models.resnet[18,34,50,101] produce nans. """ def __init__(self, n): super(FrozenBatchNorm2d, self).__init__() self.register_buffer("weight", torch.ones(n)) self.register_buffer("bias", torch.zeros(n)) self.register_buffer("running_mean", torch.zeros(n)) self.register_buffer("running_var", torch.ones(n)) def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): num_batches_tracked_key = prefix + 'num_batches_tracked' if num_batches_tracked_key in state_dict: del state_dict[num_batches_tracked_key] super(FrozenBatchNorm2d, self)._load_from_state_dict( state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) def forward(self, x): # move reshapes to the beginning # to make it fuser-friendly w = self.weight.reshape(1, -1, 1, 1) b = self.bias.reshape(1, -1, 1, 1) rv = self.running_var.reshape(1, -1, 1, 1) rm = self.running_mean.reshape(1, -1, 1, 1) eps = 1e-5 scale = w * (rv + eps).rsqrt() bias = b - rm * scale return x * scale + bias class BackboneBase(nn.Module): def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool): super().__init__() for name, parameter in backbone.named_parameters(): if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name: parameter.requires_grad_(False) if return_interm_layers: return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"} else: return_layers = {'layer4': "0"} self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) self.num_channels = num_channels def forward(self, tensor_list: NestedTensor): xs = self.body(tensor_list.tensors) out: Dict[str, NestedTensor] = {} for name, x in xs.items(): m = tensor_list.mask assert m is not None mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0] out[name] = NestedTensor(x, mask) return out class Backbone(BackboneBase): """ResNet backbone with frozen BatchNorm.""" def __init__(self, name: str, train_backbone: bool, return_interm_layers: bool, dilation: bool): backbone = getattr(torchvision.models, name)( replace_stride_with_dilation=[False, False, dilation], pretrained=is_main_process(), norm_layer=FrozenBatchNorm2d) num_channels = 512 if name in ('resnet18', 'resnet34') else 2048 super().__init__(backbone, train_backbone, num_channels, return_interm_layers) class Joiner(nn.Sequential): def __init__(self, backbone, position_embedding): super().__init__(backbone, position_embedding) def forward(self, tensor_list: NestedTensor): xs = self[0](tensor_list) out: List[NestedTensor] = [] pos = [] for name, x in xs.items(): out.append(x) # position encoding pos.append(self[1](x).to(x.tensors.dtype)) return out, pos def build_backbone(args): position_embedding = build_position_encoding(args) train_backbone = args.lr_backbone > 0 return_interm_layers = args.masks backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation) model = Joiner(backbone, position_embedding) model.num_channels = backbone.num_channels return model
Cream/iRPE/DETR-with-iRPE/models/backbone.py/0
{ "file_path": "Cream/iRPE/DETR-with-iRPE/models/backbone.py", "repo_id": "Cream", "token_count": 1904 }
305
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ A script to run multinode training with submitit. """ import argparse import os import uuid from pathlib import Path import main as detection import submitit def parse_args(): detection_parser = detection.get_args_parser() parser = argparse.ArgumentParser("Submitit for detection", parents=[detection_parser]) parser.add_argument("--ngpus", default=8, type=int, help="Number of gpus to request on each node") parser.add_argument("--nodes", default=4, type=int, help="Number of nodes to request") parser.add_argument("--timeout", default=60, type=int, help="Duration of the job") parser.add_argument("--job_dir", default="", type=str, help="Job dir. Leave empty for automatic.") return parser.parse_args() def get_shared_folder() -> Path: user = os.getenv("USER") if Path("/checkpoint/").is_dir(): p = Path(f"/checkpoint/{user}/experiments") p.mkdir(exist_ok=True) return p raise RuntimeError("No shared folder available") def get_init_file(): # Init file must not exist, but it's parent dir must exist. os.makedirs(str(get_shared_folder()), exist_ok=True) init_file = get_shared_folder() / f"{uuid.uuid4().hex}_init" if init_file.exists(): os.remove(str(init_file)) return init_file class Trainer(object): def __init__(self, args): self.args = args def __call__(self): import main as detection self._setup_gpu_args() detection.main(self.args) def checkpoint(self): import os import submitit from pathlib import Path self.args.dist_url = get_init_file().as_uri() checkpoint_file = os.path.join(self.args.output_dir, "checkpoint.pth") if os.path.exists(checkpoint_file): self.args.resume = checkpoint_file print("Requeuing ", self.args) empty_trainer = type(self)(self.args) return submitit.helpers.DelayedSubmission(empty_trainer) def _setup_gpu_args(self): import submitit from pathlib import Path job_env = submitit.JobEnvironment() self.args.output_dir = Path(str(self.args.output_dir).replace("%j", str(job_env.job_id))) self.args.gpu = job_env.local_rank self.args.rank = job_env.global_rank self.args.world_size = job_env.num_tasks print(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}") def main(): args = parse_args() if args.job_dir == "": args.job_dir = get_shared_folder() / "%j" # Note that the folder will depend on the job_id, to easily track experiments executor = submitit.AutoExecutor(folder=args.job_dir, slurm_max_num_timeout=30) # cluster setup is defined by environment variables num_gpus_per_node = args.ngpus nodes = args.nodes timeout_min = args.timeout executor.update_parameters( mem_gb=40 * num_gpus_per_node, gpus_per_node=num_gpus_per_node, tasks_per_node=num_gpus_per_node, # one task per GPU cpus_per_task=10, nodes=nodes, timeout_min=timeout_min, # max is 60 * 72 ) executor.update_parameters(name="detr") args.dist_url = get_init_file().as_uri() args.output_dir = args.job_dir trainer = Trainer(args) job = executor.submit(trainer) print("Submitted job_id:", job.job_id) if __name__ == "__main__": main()
Cream/iRPE/DETR-with-iRPE/run_with_submitit.py/0
{ "file_path": "Cream/iRPE/DETR-with-iRPE/run_with_submitit.py", "repo_id": "Cream", "token_count": 1391 }
306
"""The implementation of models with image RPE""" import torch from timm.models.registry import register_model from irpe import get_rpe_config from models import deit_tiny_patch16_224,\ deit_small_patch16_224,\ deit_base_patch16_224 _checkpoint_url_prefix = \ 'https://github.com/wkcn/iRPE-model-zoo/releases/download/1.0/' _provided_checkpoints = set([ 'deit_tiny_patch16_224_ctx_product_50_shared_k', 'deit_small_patch16_224_ctx_product_50_shared_k', 'deit_small_patch16_224_ctx_product_50_shared_qk', 'deit_small_patch16_224_ctx_product_50_shared_qkv', 'deit_base_patch16_224_ctx_product_50_shared_k', 'deit_base_patch16_224_ctx_product_50_shared_qkv', ]) def register_rpe_model(fn): '''Register a model with iRPE It is a wrapper of `register_model` with loading the pretrained checkpoint. ''' def fn_wrapper(pretrained=False, **kwargs): model = fn(pretrained=False, **kwargs) if pretrained: model_name = fn.__name__ assert model_name in _provided_checkpoints, \ f'Sorry that the checkpoint `{model_name}` is not provided yet.' url = _checkpoint_url_prefix + model_name + '.pth' checkpoint = torch.hub.load_state_dict_from_url( url=url, map_location='cpu', check_hash=False, ) model.load_state_dict(checkpoint['model']) return model # rename the name of fn_wrapper fn_wrapper.__name__ = fn.__name__ return register_model(fn_wrapper) ##### DeiT-Tiny with image relative position encoding @register_rpe_model def deit_tiny_patch16_224_ctx_product_50_shared_k(pretrained=False, **kwargs): # DeiT-Tiny with relative position encoding on keys (Contextual Product method) rpe_config = get_rpe_config( ratio=1.9, method="product", mode='ctx', shared_head=True, skip=1, rpe_on='k', ) return deit_tiny_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) ##### DeiT-Small with image relative position encoding @register_rpe_model def deit_small_patch16_224_ctx_euc_20_shared_k(pretrained=False, **kwargs): # DeiT-Small with relative position encoding on keys (Contextual Euclidean method) rpe_config = get_rpe_config( ratio=20, method="euc", mode='ctx', shared_head=True, skip=1, rpe_on='k', ) return deit_small_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) @register_rpe_model def deit_small_patch16_224_ctx_quant_51_shared_k(pretrained=False, **kwargs): # DeiT-Small with relative position encoding on keys (Contextual Quantization method) rpe_config = get_rpe_config( ratio=33, method="quant", mode='ctx', shared_head=True, skip=1, rpe_on='k', ) return deit_small_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) @register_rpe_model def deit_small_patch16_224_ctx_cross_56_shared_k(pretrained=False, **kwargs): # DeiT-Small with relative position encoding on keys (Contextual Cross method) rpe_config = get_rpe_config( ratio=20, method="cross", mode='ctx', shared_head=True, skip=1, rpe_on='k', ) return deit_small_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) @register_rpe_model def deit_small_patch16_224_ctx_product_50_shared_k(pretrained=False, **kwargs): # DeiT-Small with relative position encoding on keys (Contextual Product method) rpe_config = get_rpe_config( ratio=1.9, method="product", mode='ctx', shared_head=True, skip=1, rpe_on='k', ) return deit_small_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) @register_rpe_model def deit_small_patch16_224_ctx_product_50_shared_qk(pretrained=False, **kwargs): # DeiT-Small with relative position encoding on queries and keys (Contextual Product method) rpe_config = get_rpe_config( ratio=1.9, method="product", mode='ctx', shared_head=True, skip=1, rpe_on='qk', ) return deit_small_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) @register_rpe_model def deit_small_patch16_224_ctx_product_50_shared_qkv(pretrained=False, **kwargs): # DeiT-Small with relative position encoding on queries, keys and values (Contextual Product method) rpe_config = get_rpe_config( ratio=1.9, method="product", mode='ctx', shared_head=True, skip=1, rpe_on='qkv', ) return deit_small_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) ##### DeiT-Base with image relative position encoding @register_rpe_model def deit_base_patch16_224_ctx_product_50_shared_k(pretrained=False, **kwargs): # DeiT-Base with relative position encoding on keys (Contextual Product method) rpe_config = get_rpe_config( ratio=1.9, method="product", mode='ctx', shared_head=True, skip=1, rpe_on='k', ) return deit_base_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) @register_rpe_model def deit_base_patch16_224_ctx_product_50_shared_qkv(pretrained=False, **kwargs): # DeiT-Base with relative position encoding on queries, keys and values (Contextual Product method) rpe_config = get_rpe_config( ratio=1.9, method="product", mode='ctx', shared_head=True, skip=1, rpe_on='qkv', ) return deit_base_patch16_224(pretrained=pretrained, rpe_config=rpe_config, **kwargs) if __name__ == '__main__': import torch x = torch.randn(1, 3, 224, 224) model = deit_small_patch16_224_ctx_cross_50_shared_k() print(model) y = model(x) print(y.shape)
Cream/iRPE/DeiT-with-iRPE/rpe_models.py/0
{ "file_path": "Cream/iRPE/DeiT-with-iRPE/rpe_models.py", "repo_id": "Cream", "token_count": 3203 }
307
from .registry import model_entrypoints from .registry import is_model def build_model(config, **kwargs): model_name = config.MODEL.NAME if not is_model(model_name): raise ValueError(f'Unkown model: {model_name}') return model_entrypoints(model_name)(config, **kwargs)
CvT/lib/models/build.py/0
{ "file_path": "CvT/lib/models/build.py", "repo_id": "CvT", "token_count": 105 }
308
$schema: http://azureml/sdk-2-0/CommandComponent.json name: microsoft.com.office.spectral.residual.anomaly.detection version: 1.1.1 display_name: Spectral Residual Anomaly Detection is_deterministic: True type: CommandComponent description: This module implements the spectral residual anomaly detection algorithm for time-series. tags: time series: '' anomaly detection: '' inputs: dataset: type: DataFrameDirectory optional: False detect_mode: type: Enum optional: False default: AnomalyOnly description: Specify the detection mode. enum: - AnomalyOnly - AnomalyAndMargin timestamp_column: type: String optional: False description: Choose the column that contains timestamps. value_column: type: String optional: False description: Choose the column that contains values. batch_size: type: Integer optional: False default: 2000 description: This parameter specifies the size of each batch that the detection is perfomed, 0 indicates to run all data in a single batch. min: 0 threshold: type: Float optional: False default: 0.3 description: This parameter specifies the threshold anomaly score that a point is judged as anomaly. min: 0.0 max: 1.0 sensitivity: type: Float optional: False default: 99 description: This parameter is used in AnomalyAndMargin mode to control the width of margin. min: 0.0 max: 100.0 append_result_columns_to_output: type: Boolean optional: False default: True description: Append result columns to the original columns as output compute_stats_in_visualization: type: Boolean optional: False default: True description: Compute stats in visualization outputs: output_port: type: DataFrameDirectory environment: conda: conda_dependencies: name: project_environment channels: - defaults dependencies: - python=3.6.8 - cython=0.29.2 - numpy=1.18.1 - pip=20.0 - pip: - azureml-sdk==0.1.0.* - azureml-designer-core==0.0.31 - --index-url https://azuremlsdktestpypi.azureedge.net/dev/aml/office/134157926D8F - --extra-index-url https://pypi.org/simple - pandas==0.25.3 - pyarrow==0.16.0 - matplotlib==3.1.0 - git+https://github.com/microsoft/[email protected] docker: image: mcr.microsoft.com/azureml/base:intelmpi2018.3-ubuntu16.04 os: Linux command: python invoker.py --input {inputs.dataset} --detect-mode {inputs.detect_mode} --timestamp-column {inputs.timestamp_column} --value-column {inputs.value_column} --batch-size {inputs.batch_size} --threshold {inputs.threshold} --sensitivity {inputs.sensitivity} --append-mode {inputs.append_result_columns_to_output} --compute_stats_in_visualization {inputs.compute_stats_in_visualization} --output {outputs.output_port} ...
anomalydetector/aml_component/ad_component.yaml/0
{ "file_path": "anomalydetector/aml_component/ad_component.yaml", "repo_id": "anomalydetector", "token_count": 1075 }
309
""" Copyright (C) Microsoft Corporation. All rights reserved.​ ​ Microsoft Corporation (β€œMicrosoft”) grants you a nonexclusive, perpetual, royalty-free right to use, copy, and modify the software code provided by us ("Software Code"). You may not sublicense the Software Code or any use of it (except to your affiliates and to vendors to perform work on your behalf) through distribution, network access, service agreement, lease, rental, or otherwise. This license does not purport to express any claim of ownership over data you may have shared with Microsoft in the creation of the Software Code. Unless applicable law gives you more rights, Microsoft reserves all other rights not expressly granted herein, whether by implication, estoppel or otherwise. ​ ​ THE SOFTWARE CODE IS PROVIDED β€œAS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL MICROSOFT OR ITS LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from enum import Enum import numpy as np IsAnomaly = "isAnomaly" AnomalyId = "id" AnomalyScore = "score" Value = "value" Timestamp = "timestamp" Mag = "mag" ExpectedValue = "expectedValue" UpperBoundary = "upperBoundary" LowerBoundary = "lowerBoundary" MAX_RATIO = 0.25 EPS = 1e-8 THRESHOLD = 0.3 MAG_WINDOW = 3 SCORE_WINDOW = 40 class DetectMode(Enum): anomaly_only = 'AnomalyOnly' anomaly_and_margin = 'AnomalyAndMargin' def average_filter(values, n=3): """ Calculate the sliding window average for the give time series. Mathematically, res[i] = sum_{j=i-t+1}^{i} values[j] / t, where t = min(n, i+1) :param values: list. a list of float numbers :param n: int, default 3. window size. :return res: list. a list of value after the average_filter process. """ if n >= len(values): n = len(values) res = np.cumsum(values, dtype=float) res[n:] = res[n:] - res[:-n] res[n:] = res[n:] / n for i in range(1, n): res[i] /= (i + 1) return res def leastsq(x, y): n = len(x) sum_x = np.sum(x) sum_y = np.sum(y) sum_xx = np.sum(np.multiply(x, x)) sum_xy = np.sum(np.multiply(x, y)) a = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x) b = (sum_xx * sum_y - sum_x * sum_xy) / (n * sum_xx - sum_x * sum_x) return a, b def deanomaly_entire(values, entire_anomalies): deanomaly_data = np.copy(values) min_points_to_fit = 4 for idx in entire_anomalies: step = 1 start = max(idx - step, 0) end = min(len(values) - 1, idx + step) fit_values = [(i, values[i]) for i in range(start, end+1) if i not in entire_anomalies] while len(fit_values) < min_points_to_fit and (start > 0 or end < len(values)-1): step = step + 2 start = max(idx - step, 0) end = min(len(values) - 1, idx + step) fit_values = [(i, values[i]) for i in range(start, end+1) if i not in entire_anomalies] if len(fit_values) > 1: x, y = tuple(zip(*fit_values)) a, b = leastsq(x, y) deanomaly_data[idx] = a * idx + b return deanomaly_data
anomalydetector/msanomalydetector/util.py/0
{ "file_path": "anomalydetector/msanomalydetector/util.py", "repo_id": "anomalydetector", "token_count": 1431 }
310
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import gc import math from collections import Counter from typing import List, Optional, Tuple import numpy as np import statopt import torch from torch import Tensor, nn from torch.nn.modules.loss import _Loss from torch.optim import SGD, Adam, lr_scheduler from torch.optim.lr_scheduler import _LRScheduler from torch.optim.optimizer import Optimizer from archai.common.config import Config from archai.trainers.coin_betting_optimizer import CocobBackprop from archai.trainers.gradual_warmup_scheduler import GradualWarmupScheduler from archai.trainers.losses import SmoothCrossEntropyLoss def create_optimizer(conf_opt: Config, params) -> Optimizer: optim_type = conf_opt["type"] lr = conf_opt.get("lr", math.nan) decay = conf_opt.get("decay", math.nan) decay_bn = conf_opt.get("decay_bn", math.nan) # some optim may not support weight decay if not math.isnan(decay_bn): bn_params = [v for n, v in params if "bn" in n] rest_params = [v for n, v in params if not "bn" in n] params = [{"params": bn_params, "weight_decay": decay_bn}, {"params": rest_params, "weight_decay": decay}] if optim_type == "sgd": return SGD(params, lr=lr, momentum=conf_opt["momentum"], weight_decay=decay, nesterov=conf_opt["nesterov"]) elif optim_type == "adam": return Adam(params, lr=lr, betas=conf_opt["betas"], weight_decay=decay) elif optim_type == "cocob": return CocobBackprop(params, alpha=conf_opt["alpha"]) elif optim_type == "salsa": return statopt.SALSA(params, alpha=conf_opt["alpha"]) else: raise ValueError("invalid optimizer type=%s" % optim_type) def get_optim_lr(optimizer: Optimizer) -> float: for param_group in optimizer.param_groups: return param_group["lr"] def set_optim_lr(optimizer: Optimizer, lr: float) -> None: for param_group in optimizer.param_groups: param_group["lr"] = lr def ensure_pytorch_ver(min_ver: str, error_msg: str) -> bool: tv = torch.__version__.split(".") req = min_ver.split(".") for i, j in zip(tv, req): i, j = int(i), int(j) if i > j: return True if i < j: if error_msg: raise RuntimeError( f"Minimum required PyTorch version is {min_ver} but installed version is {torch.__version__}: {error_msg}" ) return False return True def join_chunks(chunks: List[Tensor]) -> Tensor: """If batch was divided in chunks, this functions joins them again""" assert len(chunks) if len(chunks) == 1: return chunks[0] # nothing to concate if len(chunks[0].shape): return torch.cat(chunks) return torch.stack(chunks) # TODO: this adds new dimension def create_lr_scheduler( conf_lrs: Config, epochs: int, optimizer: Optimizer, steps_per_epoch: Optional[int] ) -> Tuple[Optional[_LRScheduler], bool]: # epoch_or_step - apply every epoch or every step scheduler, epoch_or_step = None, True # by default sched step on epoch conf_warmup = conf_lrs.get("warmup", None) warmup_epochs = 0 if conf_warmup is not None and "epochs" in conf_warmup: warmup_epochs = conf_warmup["epochs"] if conf_lrs is not None: lr_scheduler_type = conf_lrs["type"] # TODO: default should be none? if lr_scheduler_type == "cosine": scheduler = lr_scheduler.CosineAnnealingLR( optimizer, T_max=epochs - warmup_epochs, eta_min=conf_lrs["min_lr"] ) elif lr_scheduler_type == "multi_step": scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=conf_lrs["milestones"], gamma=conf_lrs["gamma"]) elif lr_scheduler_type == "pyramid": scheduler = _adjust_learning_rate_pyramid(optimizer, epochs - warmup_epochs, get_optim_lr(optimizer)) elif lr_scheduler_type == "step": decay_period = conf_lrs["decay_period"] gamma = conf_lrs["gamma"] scheduler = lr_scheduler.StepLR(optimizer, decay_period, gamma=gamma) elif lr_scheduler_type == "one_cycle": assert steps_per_epoch is not None ensure_pytorch_ver("1.3.0", "LR scheduler OneCycleLR is not available.") max_lr = conf_lrs["max_lr"] epoch_or_step = False scheduler = lr_scheduler.OneCycleLR( optimizer, max_lr=max_lr, epochs=epochs - warmup_epochs, steps_per_epoch=steps_per_epoch, ) # TODO: other params elif not lr_scheduler_type: scheduler = None else: raise ValueError("invalid lr_schduler=%s" % lr_scheduler_type) # select warmup for LR schedule if warmup_epochs: scheduler = GradualWarmupScheduler( optimizer, multiplier=conf_lrs["warmup"].get("multiplier", 1.0), total_epoch=warmup_epochs, after_scheduler=scheduler, ) return scheduler, epoch_or_step def _adjust_learning_rate_pyramid(optimizer, max_epoch: int, base_lr: float): def _internal_adjust_learning_rate_pyramid(epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = base_lr * (0.1 ** (epoch // (max_epoch * 0.5))) * (0.1 ** (epoch // (max_epoch * 0.75))) return lr return lr_scheduler.LambdaLR(optimizer, _internal_adjust_learning_rate_pyramid) def get_lossfn(conf_lossfn: Config) -> _Loss: type = conf_lossfn["type"] if type == "CrossEntropyLoss": return nn.CrossEntropyLoss() elif type == "CrossEntropyLabelSmooth": return SmoothCrossEntropyLoss(smoothing=conf_lossfn["smoothing"]) else: raise ValueError('criterian type "{}" is not supported'.format(type)) def param_size(module: nn.Module, ignore_aux=True, only_req_grad=False): """count all parameters excluding auxiliary""" return np.sum( v.numel() for name, v in module.named_parameters() if (not ignore_aux or ("auxiliary" not in name)) and (not only_req_grad or v.requires_grad) ) def save_model(model, model_path): torch.save(model.state_dict(), model_path) def load_model(model, model_path): model.load_state_dict(torch.load(model_path)) def drop_path_(x, drop_prob, training): if training and drop_prob > 0.0: keep_prob = 1.0 - drop_prob # Bernoulli returns 1 with pobability p and 0 with 1-p. # Below generates tensor of shape (batch,1,1,1) filled with 1s and 0s # as per keep_prob. mask = torch.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob).to(device=x.device) # scale tensor by 1/p as we will be losing other values # for each tensor in batch, zero out values with probability p x.div_(keep_prob).mul_(mask) return x def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() # one-hot case if target.ndimension() > 1: target = target.max(1)[1] correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].contiguous().view(-1).float().sum(0) res.append(correct_k.mul_(1.0 / batch_size)) return res def channel_norm(dataset, channel_dim=1) -> tuple: # collect tensors in list l = [data for data, *_ in dataset] # join back all tensors so the first dimension is count of tensors l = torch.stack(l, dim=0) # size: [N, X, Y, ...] or [N, C, X, Y, ...] if channel_dim is None: # add redundant first dim l = l.unsqueeze(0) else: # swap channel dimension to first l = torch.transpose(l, 0, channel_dim).contiguous() # size: [C, N, X, Y, ...] # collapse all except first dimension l = l.view(l.size(0), -1) # size: [C, N*X*Y] mean = torch.mean(l, dim=1) # size: [C] std = torch.std(l, dim=1) # size: [C] return mean, std def clear_gpu_memory(): gc.collect() torch.cuda.empty_cache() for obj in gc.get_objects(): if torch.is_tensor(obj): obj.cpu() gc.collect() torch.cuda.empty_cache() def memory_allocated(device=None, max=False) -> float: """Returns allocated memory on device in MBs""" if device: device = torch.device(device) if max: alloc = torch.cuda.max_memory_allocated(device=device) else: alloc = torch.cuda.memory_allocated(device=device) alloc /= 1024**2 return alloc def print_memory_objects(device=None, max=False) -> None: numels = Counter() for obj in gc.get_objects(): if torch.is_tensor(obj): print(type(obj), obj.size()) numels[obj.device] += obj.numel() print() for device, numel in sorted(numels.items()): print("%s: %s elements, %.3f MBs" % (str(device), numel, numel * 4 / 1024**2))
archai/archai/common/ml_utils.py/0
{ "file_path": "archai/archai/common/ml_utils.py", "repo_id": "archai", "token_count": 4003 }
311
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Callable, Optional from overrides import overrides from torch.utils.data import Dataset from torchvision.datasets import Cityscapes from torchvision.transforms import ToTensor from archai.api.dataset_provider import DatasetProvider class CityscapesDatasetProvider(DatasetProvider): """Cityscapes dataset provider.""" def __init__( self, root: Optional[str] = "dataroot", ) -> None: """Initialize Cityscapes dataset provider. Args: root: Root directory of dataset where is saved. """ super().__init__() self.root = root @overrides def get_train_dataset( self, target_type: Optional[str] = "instance", transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, ) -> Dataset: return Cityscapes( self.root, split="train", mode="fine", target_type=target_type, transform=transform or ToTensor(), target_transform=target_transform, ) @overrides def get_val_dataset( self, target_type: Optional[str] = "instance", transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, ) -> Dataset: return Cityscapes( self.root, split="val", mode="fine", target_type=target_type, transform=transform or ToTensor(), target_transform=target_transform, ) @overrides def get_test_dataset( self, target_type: Optional[str] = "instance", transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, ) -> Dataset: return Cityscapes( self.root, split="test", mode="fine", target_type=target_type, transform=transform or ToTensor(), target_transform=target_transform, )
archai/archai/datasets/cv/cityscapes_dataset_provider.py/0
{ "file_path": "archai/archai/datasets/cv/cityscapes_dataset_provider.py", "repo_id": "archai", "token_count": 935 }
312
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from archai.discrete_search.algos.bananas import MoBananasSearch from archai.discrete_search.algos.evolution_pareto import EvolutionParetoSearch from archai.discrete_search.algos.local_search import LocalSearch from archai.discrete_search.algos.random_search import RandomSearch from archai.discrete_search.algos.regularized_evolution import RegularizedEvolutionSearch
archai/archai/discrete_search/algos/__init__.py/0
{ "file_path": "archai/archai/discrete_search/algos/__init__.py", "repo_id": "archai", "token_count": 125 }
313
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import copy import sys from random import Random from typing import Any, Dict, List, Optional, Tuple import numpy as np import tensorwatch as tw import torch from overrides.overrides import overrides from archai.common.ordered_dict_logger import OrderedDictLogger from archai.discrete_search.api.archai_model import ArchaiModel from archai.discrete_search.api.search_space import EvolutionarySearchSpace from archai.discrete_search.search_spaces.cv.segmentation_dag.model import ( OPS, SegmentationDagModel, ) logger = OrderedDictLogger(source=__name__) class SegmentationDagSearchSpace(EvolutionarySearchSpace): """Search space for segmentation DAGs.""" def __init__( self, nb_classes: int, img_size: Tuple[int, int], min_mac: Optional[int] = 0, max_mac: Optional[int] = sys.maxsize, min_layers: Optional[int] = 1, max_layers: Optional[int] = 12, max_downsample_factor: Optional[int] = 16, skip_connections: Optional[bool] = True, max_skip_connection_length: Optional[int] = 3, max_scale_delta: Optional[int] = 1, max_post_upsample_layers: Optional[int] = 3, min_base_channels: Optional[int] = 8, max_base_channels: Optional[int] = 48, base_channels_binwidth: Optional[int] = 8, min_delta_channels: Optional[int] = 8, max_delta_channels: Optional[int] = 48, delta_channels_binwidth: Optional[int] = 8, downsample_prob_ratio: Optional[float] = 1.5, op_subset: Optional[str] = None, mult_delta: Optional[bool] = False, seed: Optional[int] = 1, ) -> None: """Initialize the search space. Args: nb_classes: Number of classes. img_size: Image size. min_mac: Minimum number of MACs. max_mac: Maximum number of MACs. min_layers: Minimum number of layers. max_layers: Maximum number of layers. max_downsample_factor: Maximum downsample factor. skip_connections: Whether to use skip connections. max_skip_connection_length: Maximum skip connection length. max_scale_delta: Maximum scale delta. max_post_upsample_layers: Maximum number of post upsample layers. min_base_channels: Minimum number of base channels. max_base_channels: Maximum number of base channels. base_channels_binwidth: Base channels binwidth. min_delta_channels: Minimum number of delta channels. max_delta_channels: Maximum number of delta channels. delta_channels_binwidth: Delta channels binwidth. downsample_prob_ratio: Downsample probability ratio. op_subset: Subset of operations to use. mult_delta: Whether to multiply delta channels. seed: Seed for random number generator. """ super().__init__() self.nb_classes = nb_classes self.operations = list(OPS.keys()) op_list = op_subset.split(",") if op_subset else [] if op_list: self.operations = [op for op in self.operations if op in op_list] assert len(self.operations) > 0 self.min_mac = min_mac self.max_mac = max_mac assert self.min_mac <= self.max_mac self.min_layers = min_layers self.max_layers = max_layers assert self.min_layers <= self.max_layers self.max_downsample_factor = max_downsample_factor assert self.max_downsample_factor in set([2, 4, 8, 16]) self.max_skip_connection_length = max_skip_connection_length assert self.max_skip_connection_length > 0 self.max_scale_delta = max_scale_delta assert self.max_scale_delta in set([1, 2, 3]) self.post_upsample_layers_list = list(range(1, max_post_upsample_layers + 1)) assert len(self.post_upsample_layers_list) < 5 self.base_channels_list = list(range(min_base_channels, max_base_channels + 1, base_channels_binwidth)) assert min_base_channels <= max_base_channels assert len(self.base_channels_list) > 1 self.delta_channels_list = list(range(min_delta_channels, max_delta_channels + 1, delta_channels_binwidth)) self.mult_delta = mult_delta assert min_delta_channels <= max_delta_channels assert len(self.delta_channels_list) >= 1 self.skip_connections = skip_connections self.downsample_prob_ratio = downsample_prob_ratio self.img_size = img_size self.rng = Random(seed) def is_valid_model(self, model: torch.nn.Module) -> Tuple[bool, int]: """Check if a model is valid and falls inside of the specified MAdds range. Args: model: Model to check. Returns: Tuple of (is_valid, MAdds). """ is_valid = True try: model.validate_forward(torch.randn(1, 3, *self.img_size[::-1])) except Exception: is_valid = False if is_valid: input_tensor_shape = (1, 3, *self.img_size) model_stats = tw.ModelStats(model, input_tensor_shape, clone_model=True) is_valid = model_stats.MAdd >= self.min_mac and model_stats.MAdd <= self.max_mac return is_valid, None if not is_valid else model_stats.MAdd def load_from_graph( self, graph: List[Dict[str, Any]], channels_per_scale: Dict[str, Any], post_upsample_layers: Optional[int] = 1 ) -> ArchaiModel: """Create a SegmentationDagModel from a DAG. Args: graph: DAG graph. channels_per_scale: Number of channels per scale. post_upsample_layers: Number of post upsample layers. Returns: Archai-based model. """ model = SegmentationDagModel( graph, channels_per_scale, post_upsample_layers, img_size=self.img_size, nb_classes=self.nb_classes ) return ArchaiModel(arch=model, archid=model.to_hash(), metadata={"parent": None}) def random_neighbor(self, param_values: List[int], current_value: int) -> int: """Sample a random neighbor from an element of a list. Args: param_values: List of values. current_value: Current value. Returns: Random neighbor. """ param_values = sorted(copy.deepcopy(param_values)) param2idx = {param: idx for idx, param in enumerate(param_values)} # Gets the index of the closest value to the current value if current_value in param2idx: current_idx = param2idx[current_value] else: current_idx = param2idx[min(param2idx, key=lambda k: abs(k - current_value))] offset = self.rng.randint(a=-1 if current_idx > 0 else 0, b=1 if current_idx < len(param_values) - 1 else 0) return param_values[current_idx + offset] def rename_dag_node_list( self, node_list: List[Dict[str, Any]], prefix: Optional[str] = "", rename_input_output: Optional[bool] = True, add_input_output: Optional[bool] = False, ) -> List[Dict[str, Any]]: """Rename a list of nodes from a DAG. Args: node_list: List of nodes. prefix: Prefix to add to the name of each node. rename_input_output: Whether to rename the input and output nodes. add_input_output: Whether to add input and output nodes. Returns: Renamed list of nodes. """ node_list = copy.deepcopy(node_list) prefix = prefix + "_" if prefix else "" rename_map = {} if not rename_input_output: rename_map = {"input": "input", "output": "output"} for i, node in enumerate(node_list): if node["name"] not in rename_map: if add_input_output: new_name = "input" if i == 0 else "output" if i == len(node_list) - 1 else prefix + f"layer_{i}" else: new_name = prefix + f"layer_{i}" rename_map[node["name"]] = new_name node["name"] = new_name if node["inputs"]: node["inputs"] = [ rename_map[inp_name] for inp_name in node["inputs"] if inp_name and inp_name in rename_map ] return node_list @overrides def save_arch(self, model: ArchaiModel, path: str) -> None: model.arch.to_file(path) @overrides def save_model_weights(self, model: ArchaiModel, path: str) -> None: torch.save(model.arch.to("cpu").state_dict(), path) @overrides def load_arch(self, path: str) -> ArchaiModel: model = SegmentationDagModel.from_file(path, img_size=self.img_size, nb_classes=self.nb_classes) return ArchaiModel(model, model.to_hash(), metadata={"parent": None}) @overrides def load_model_weights(self, model: ArchaiModel, path: str) -> None: model.arch.load_state_dict(torch.load(path)) @overrides def random_sample(self) -> ArchaiModel: arch = None while not arch: # randomly pick number of layers nb_layers = self.rng.randint(self.min_layers, self.max_layers) # Samples `base_channels` and `delta_channels` ch_per_scale = { "base_channels": self.rng.choice(self.base_channels_list), "delta_channels": self.rng.choice(self.delta_channels_list), "mult_delta": self.mult_delta, } # Samples `post_upsample_layers` post_upsample_layers = ( self.rng.choice(self.post_upsample_layers_list) if self.post_upsample_layers_list else 1 ) # Builds channels per level map using the sampled `base_channels` and `delta_channels` ch_map = SegmentationDagModel._get_channels_per_scale(ch_per_scale, self.max_downsample_factor, True) # Input node graph = [{"name": "input", "inputs": None, "op": self.rng.choice(self.operations), "scale": 1}] node_list = ["input"] # Used to control `max_scale_delta` idx2scale = list(ch_map.keys()) scale2idx = {scale: i for i, scale in enumerate(ch_map.keys())} for layer in range(nb_layers): is_output = layer == nb_layers - 1 last_layer = graph[-1] new_node = { "name": "output" if is_output else f"layer_{layer}", "op": None if is_output else self.rng.choice(self.operations), "inputs": [last_layer["name"]], } # Choose scale last_scale_idx = scale2idx[last_layer["scale"]] # Samples a delta value for the current scale index scale_options = list( range( max(-self.max_scale_delta, -last_scale_idx), 1 + min(self.max_scale_delta, len(ch_map) - last_scale_idx - 1), ) ) sample_weights = np.array([1 if delta < 0 else self.downsample_prob_ratio for delta in scale_options]) scale_delta = self.rng.choices(scale_options, k=1, weights=sample_weights)[0] # Assigns the new scale to the new node new_node["scale"] = idx2scale[last_scale_idx + scale_delta] # Choose inputs if len(node_list) > 1: for i in range(2, 1 + self.rng.randint(2, min(len(node_list), self.max_skip_connection_length))): if self.skip_connections and self.rng.random() < 0.5: new_node["inputs"].append(node_list[-i]) # Adds node graph.append(new_node) node_list.append(new_node["name"]) # Builds model model = SegmentationDagModel( graph, ch_per_scale, post_upsample_layers, img_size=self.img_size, nb_classes=self.nb_classes ) found_valid, macs = self.is_valid_model(model) if found_valid: arch = ArchaiModel(model, model.to_hash(), {"parent": None, "macs": macs}) return arch @overrides def mutate(self, base_model: ArchaiModel, patience: Optional[int] = 5) -> ArchaiModel: parent_id = base_model.archid nb_tries = 0 while nb_tries < patience: nb_tries += 1 graph = copy.deepcopy(list(base_model.arch.graph.values())) channels_per_scale = copy.deepcopy(base_model.arch.channels_per_scale) # sanity check the graph assert len(graph) > 1 assert graph[-1]["name"] == "output" assert graph[0]["name"] == "input" # `base_channels` and `delta_channels` mutation channels_per_scale = { "base_channels": self.random_neighbor(self.base_channels_list, channels_per_scale["base_channels"]), "delta_channels": self.random_neighbor(self.delta_channels_list, channels_per_scale["delta_channels"]), "mult_delta": self.mult_delta, } # `post_upsample_layers` mutation post_upsample_layers = self.random_neighbor( self.post_upsample_layers_list, base_model.arch.post_upsample_layers ) # pick a node at random (but not input node) # and change its operator at random # and its input sources chosen_node_idx = self.rng.randint(1, len(graph) - 1) node = graph[chosen_node_idx] if node["name"] != "output": node["op"] = self.rng.choice(self.operations) # choose up to k inputs from previous nodes max_inputs = 3 # TODO: make config # Gets the out connections for each node edges = [tuple(k.split("-")) for k in base_model.arch.edge_dict.keys()] def out_degree(x): return len([(orig, dest) for orig, dest in edges if orig == x]) if node["name"] != "input": k = min(chosen_node_idx, self.rng.randint(1, max_inputs)) input_idxs = self.rng.sample(range(chosen_node_idx), k) # Removes everything except inputs that have out degree == 1 node["inputs"] = [input for input in node["inputs"] if out_degree(input) <= 1] # Adds `k` new inputs node["inputs"] += [graph[idx]["name"] for idx in input_idxs if graph[idx]["name"] not in node["inputs"]] # compile the model nbr_model = SegmentationDagModel( graph, channels_per_scale, post_upsample_layers, img_size=self.img_size, nb_classes=self.nb_classes ) if not self.is_valid_model(nbr_model)[0]: logger.info(f"Neighbor generation {base_model.arch.to_hash()} -> {nbr_model.to_hash()} failed.") continue return ArchaiModel(nbr_model, nbr_model.to_hash(), metadata={"parent": parent_id}) @overrides def crossover(self, model_list: List[ArchaiModel], patience: Optional[int] = 30) -> Optional[ArchaiModel]: if len(model_list) < 2: return # Chooses randomly left and right models left_m, right_m = self.rng.sample(model_list, 2) left_arch, right_arch = [list(m.arch.graph.values()) for m in [left_m, right_m]] # Renames nodes to avoid name collision left_arch = self.rename_dag_node_list(left_arch, "left") right_arch = self.rename_dag_node_list(right_arch, "right") # Stores node names left_n, right_n = [[n["name"] for n in g] for g in [left_arch, right_arch]] if len(left_n) <= 2 or len(right_n) <= 2: return # Tries to merge left_m and right_m result_g = None nb_tries = 0 for nb_tries in range(patience): left_g, right_g = copy.deepcopy(left_arch), copy.deepcopy(right_arch) nb_tries += 1 # Samples a pivot node from the left model left_pivot_idx = self.rng.randint(1, len(left_n) - 2) left_pivot = left_n[left_pivot_idx] # Samples a pivot node from the right model w/ the same scale as the left_pivot # excluding input and output nodes right_candidates = [ i for i, fields in enumerate(right_g) if fields["scale"] == left_g[left_pivot_idx]["scale"] and 0 < i < (len(right_n) - 1) ] if len(right_candidates) > 0: # Picks a right pivot right_pivot_idx = self.rng.choice(right_candidates) # Splits right_g and left_g using the pivot nodes left_half = left_g[: left_pivot_idx + 1] right_half = right_g[right_pivot_idx:] # Gets node2idx for right model right_node2idx = {node: i for i, node in enumerate(right_n)} # Corrects connections from right_g for fields in right_half[::-1]: for inp_idx, inp in enumerate(fields["inputs"]): # Checks if this connection falls outside of right_half if inp not in right_n[right_pivot_idx:]: # Finds a new starting node to connect this edge # with the same original input scale candidates = [ n["name"] for n in left_half if n["scale"] == right_g[right_node2idx[inp]]["scale"] ] fields["inputs"][inp_idx] = self.rng.choice(candidates) if len(candidates) > 0 else None # Renames end node right_half[-1]["name"] = "output" # Connects left_half and right_half if left_pivot not in right_half[0]["inputs"]: right_half[0]["inputs"].append(left_pivot) # Merge and rename nodes result_g = self.rename_dag_node_list(left_half + right_half, add_input_output=True) # Pick `channels_per_scale` and `post_upsample_layers` from left_m or right_m ch_map = self.rng.choice( [copy.deepcopy(left_m.arch.channels_per_scale), copy.deepcopy(right_m.arch.channels_per_scale)] ) post_upsample_layers = self.rng.choice( [left_m.arch.post_upsample_layers, right_m.arch.post_upsample_layers] ) try: result_model = self.load_from_graph( result_g, { "base_channels": ch_map["base_channels"], "delta_channels": ch_map["delta_channels"], "mult_delta": ch_map["mult_delta"], }, post_upsample_layers, ) out_shape = result_model.arch.validate_forward( torch.randn(1, 3, *result_model.arch.img_size[::-1]) ).shape assert out_shape == torch.Size([1, self.nb_classes, *result_model.arch.img_size[::-1]]) except Exception as e: logger.info( f"Crossover between {left_m.arch.to_hash()}, {right_m.arch.to_hash()} failed: " f"(nb_tries = {nb_tries})." ) logger.info(str(e)) print(str(e)) continue result_model.metadata["parents"] = left_m.archid + "," + right_m.archid return result_model
archai/archai/discrete_search/search_spaces/cv/segmentation_dag/search_space.py/0
{ "file_path": "archai/archai/discrete_search/search_spaces/cv/segmentation_dag/search_space.py", "repo_id": "archai", "token_count": 9784 }
314
# Downloaded from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/functional/krylov.py """ Compute a Krylov function efficiently. (S4 renames the Krylov function to a "state space kernel") A : (N, N) b : (N,) c : (N,) Return: [c^T A^i b for i in [L]] """ import torch import torch.nn.functional as F from einops import rearrange, repeat from .toeplitz import causal_convolution def krylov_sequential(L, A, b, c=None): """ Constant matrix A A : (..., N, N) b : (..., N) c : (..., N) Returns if c: x : (..., L) x[i, l] = c[i] @ A^l @ b[i] else: x : (..., N, L) x[i, l] = A^l @ b[i] """ # Check which of dim b and c is smaller to save memory if c is not None and c.numel() < b.numel(): return krylov_sequential(L, A.transpose(-1, -2), c, b) b_ = b x = [] for _ in range(L): if c is not None: x_ = torch.sum(c*b_, dim=-1) # (...) # could be faster with matmul or einsum? else: x_ = b_ x.append(x_) b_ = (A @ b_.unsqueeze(-1)).squeeze(-1) x = torch.stack(x, dim=-1) return x def krylov(L, A, b, c=None, return_power=False): """ Compute the Krylov matrix (b, Ab, A^2b, ...) using the squaring trick. If return_power=True, return A^{L-1} as well """ # TODO There is an edge case if L=1 where output doesn't get broadcasted, which might be an issue if caller is expecting broadcasting semantics... can deal with it if it arises x = b.unsqueeze(-1) # (..., N, 1) A_ = A AL = None if return_power: AL = torch.eye(A.shape[-1], dtype=A.dtype, device=A.device) _L = L-1 done = L == 1 # loop invariant: _L represents how many indices left to compute while not done: if return_power: if _L % 2 == 1: AL = A_ @ AL _L //= 2 # Save memory on last iteration l = x.shape[-1] if L - l <= l: done = True _x = x[..., :L-l] else: _x = x _x = A_ @ _x x = torch.cat([x, _x], dim=-1) # there might be a more efficient way of ordering axes if not done: A_ = A_ @ A_ assert x.shape[-1] == L if c is not None: x = torch.einsum('...nl, ...n -> ...l', x, c) x = x.contiguous() # WOW!! if return_power: return x, AL else: return x @torch.no_grad() def power(L, A, v=None): """ Compute A^L and the scan sum_i A^i v_i A: (..., N, N) v: (..., N, L) """ I = torch.eye(A.shape[-1]).to(A) # , dtype=A.dtype, device=A.device) powers = [A] l = 1 while True: if L % 2 == 1: I = powers[-1] @ I L //= 2 if L == 0: break l *= 2 if v is None: powers = [powers[-1] @ powers[-1]] else: powers.append(powers[-1] @ powers[-1]) if v is None: return I # Invariants: # powers[-1] := A^l # l := largest po2 at most L # Note that an alternative divide and conquer to compute the reduction is possible and can be embedded into the above loop without caching intermediate powers of A # We do this reverse divide-and-conquer for efficiency reasons: # 1) it involves fewer padding steps for non-po2 L # 2) it involves more contiguous arrays # Take care of edge case for non-po2 arrays # Note that this initial step is a no-op for the case of power of 2 (l == L) k = v.size(-1) - l v_ = powers.pop() @ v[..., l:] v = v[..., :l] v[..., :k] = v[..., :k] + v_ # Handle reduction for power of 2 while v.size(-1) > 1: v = rearrange(v, '... (z l) -> ... z l', z=2) v = v[..., 0, :] + powers.pop() @ v[..., 1, :] return I, v.squeeze(-1) def krylov_toeplitz(L, A, b, c=None): """ Specializes to lower triangular Toeplitz matrix A represented by its diagonals A : (..., N) b : (..., N) c : (..., N) Returns x : (..., N, L) x[i, l] = A^l @ b[i] """ x = b.unsqueeze(0) # (1, ..., N) A_ = A while x.shape[0] < L: xx = causal_convolution(A_, x) x = torch.cat([x, xx], dim=0) # there might be a more efficient way of ordering axes A_ = causal_convolution(A_, A_) x = x[:L, ...] # (L, ..., N) if c is not None: x = torch.einsum('l...n, ...n -> ...l', x, c) else: x = rearrange(x, 'l ... n -> ... n l') x = x.contiguous() return x def krylov_toeplitz_(L, A, b, c=None): """ Padded version of krylov_toeplitz that saves some fft's TODO currently not faster than original version, not sure why """ N = A.shape[-1] x = b.unsqueeze(0) # (1, ..., N) x = F.pad(x, (0, N)) A = F.pad(A, (0, N)) done = L == 1 while not done: l = x.shape[0] # Save memory on last iteration if L - l <= l: done = True _x = x[:L-l] else: _x = x Af = torch.fft.rfft(A, n=2*N, dim=-1) xf = torch.fft.rfft(_x, n=2*N, dim=-1) xf_ = Af * xf x_ = torch.fft.irfft(xf_, n=2*N, dim=-1) x_[..., N:] = 0 x = torch.cat([x, x_], dim=0) # there might be a more efficient way of ordering axes if not done: A = torch.fft.irfft(Af*Af, n=2*N, dim=-1) A[..., N:] = 0 x = x[:L, ..., :N] # (L, ..., N) if c is not None: x = torch.einsum('l...n, ...n -> ...l', x, c) else: x = rearrange(x, 'l ... n -> ... n l') x = x.contiguous() return x
archai/archai/discrete_search/search_spaces/nlp/tfpp/ops/ssm_utils/ssm_ops/krylov.py/0
{ "file_path": "archai/archai/discrete_search/search_spaces/nlp/tfpp/ops/ssm_utils/ssm_ops/krylov.py", "repo_id": "archai", "token_count": 2690 }
315
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # # Copyright (c) 2018, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0. from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from archai.discrete_search.search_spaces.nlp.transformer_flex.models.mem_transformer_utils.depth_wise_convolution import ( DepthWiseConvolution, ) from archai.discrete_search.search_spaces.nlp.transformer_flex.models.mem_transformer_utils.position_wise_ff import ( PositionWiseFF, PositionWiseFFPrimerEZ, ) class RelPartialLearnableMultiHeadAttn(nn.Module): def __init__( self, n_head: int, d_model: int, d_head: int, dropout: float, dropatt: Optional[float] = 0.0, primer_conv: Optional[bool] = False, pre_lnorm: Optional[bool] = False, r_w_bias: Optional[torch.FloatTensor] = None, r_r_bias: Optional[torch.FloatTensor] = None, layer_norm_epsilon: Optional[float] = 1e-5, ): super().__init__() self.n_head = n_head self.d_model = d_model self.d_head = d_head self.dropout = dropout self.primer_conv = primer_conv self.pre_lnorm = pre_lnorm self.scale = 1 / (d_head**0.5) self.qkv = nn.Linear(d_model, 3 * n_head * d_head, bias=False) self.o = nn.Linear(n_head * d_head, d_model, bias=False) self.r = nn.Linear(d_model, n_head * d_head, bias=False) self.drop = nn.Dropout(dropout) self.dropatt = nn.Dropout(dropatt) if self.primer_conv: self.d_conv = DepthWiseConvolution(self.d_model) self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon) # Bias are not shared, i.e., they are defined per layer if r_w_bias is None or r_r_bias is None: self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head)) else: self.r_w_bias = r_w_bias self.r_r_bias = r_r_bias def _relational_shift(self, inputs: torch.FloatTensor) -> torch.FloatTensor: pad_shape = (inputs.size(0), 1) + inputs.size()[2:] pad = torch.zeros(pad_shape, device=inputs.device, dtype=inputs.dtype) inputs_padded = torch.cat([pad, inputs], dim=1) inputs_padded_shape = (inputs.size(1) + 1, inputs.size(0)) + inputs.size()[2:] inputs_padded = inputs_padded.view(*inputs_padded_shape) output = inputs_padded[1:].view_as(inputs) return output def forward( self, w: torch.FloatTensor, r: torch.FloatTensor, layer_past: Optional[torch.FloatTensor] = None, attn_mask: Optional[torch.FloatTensor] = None, mems: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = False, output_attentions: Optional[bool] = False, ) -> torch.FloatTensor: q_length, r_length, batch_size = w.size(0), r.size(0), w.size(1) if mems is not None: mems_w = torch.cat([mems, w], 0) if self.pre_lnorm: mems_w = self.layer_norm(mems_w) heads_w = self.qkv(mems_w) if self.primer_conv: heads_w = self.d_conv(heads_w) head_wq, head_wk, head_wv = torch.chunk(heads_w, 3, dim=-1) head_wq = head_wq[-q_length:] head_rk = self.r(r) else: if self.pre_lnorm: w = self.layer_norm(w) heads_w = self.qkv(w) if self.primer_conv: heads_w = self.d_conv(heads_w) head_wq, head_wk, head_wv = torch.chunk(heads_w, 3, dim=-1) head_rk = self.r(r) k_length = head_wk.size(0) # Changes the view according to required size # (head_length, batch_size, n_head, d_head) head_wq = head_wq.view(q_length, batch_size, self.n_head, self.d_head) head_wk = head_wk.view(k_length, batch_size, self.n_head, self.d_head) head_wv = head_wv.view(k_length, batch_size, self.n_head, self.d_head) # (head_length, n_head, d_head) head_rk = head_rk.view(r_length, self.n_head, self.d_head) if layer_past is not None: past_k, past_v, past_r = torch.unbind(layer_past, dim=0) past_r = past_r[:, 0, :, :] head_wk = torch.cat((past_k, head_wk), dim=0) head_wv = torch.cat((past_v, head_wv), dim=0) head_rk = torch.cat((head_rk, past_r), dim=0) if use_cache is True: _r_head_k = head_rk.unsqueeze(1).expand(-1, batch_size, -1, -1) present = torch.stack([head_wk, head_wv, _r_head_k], dim=0) else: present = None # Attention score # (q_length, batch_size, n_head, d_head) head_r_wq = head_wq + self.r_w_bias head_r_rq = head_wq + self.r_r_bias # (q_length, k_length, batch_size, n_head) AC = torch.einsum("ibnd,jbnd->ijbn", (head_r_wq, head_wk)) BD = torch.einsum("ibnd,jnd->ijbn", (head_r_rq, head_rk)) BD = self._relational_shift(BD) # (q_length, k_length, batch_size, h_head) attn_score = AC + BD attn_score.mul_(self.scale) # Attention probability if attn_mask is not None and torch.sum(attn_mask).item(): # Switches to a boolean mask attn_mask = attn_mask == 1 # Standard filling for 32-bit float precision fill = -1e30 # If using 16-bit float precision, `fill` should be smaller if next(self.parameters()).dtype == torch.float16: fill = -65000 if attn_mask.dim() == 2: attn_score = attn_score.float().masked_fill(attn_mask[None, :, :, None], fill).type_as(attn_score) elif attn_mask.dim() == 3: attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], fill).type_as(attn_score) # (q_length, k_length, batch_size, n_head) attn_prob = F.softmax(attn_score, dim=1) attn_prob = self.dropatt(attn_prob) # Whether heads should be masked or not if head_mask is not None: attn_prob = attn_prob * head_mask # Attention vector attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, head_wv)) # (q_length, batch_size, n_head, d_head) attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head) # linear projection attn_out = self.o(attn_vec) attn_out = self.drop(attn_out) # Residual connection output = w + attn_out if not self.pre_lnorm: # Layer normalization output = self.layer_norm(output) output = [output, present] if output_attentions: output.append(attn_prob) return output class RelPartialLearnableDecoderLayer(nn.Module): def __init__( self, n_head: int, d_model: int, d_head: int, d_inner: int, dropout: float, dropatt: Optional[float] = 0.0, primer_conv: Optional[bool] = False, primer_square: Optional[bool] = False, pre_lnorm: Optional[bool] = False, layer_norm_epsilon: Optional[float] = 1e-5, r_w_bias: Optional[torch.FloatTensor] = None, r_r_bias: Optional[torch.FloatTensor] = None, ) -> None: super().__init__() self.attn = RelPartialLearnableMultiHeadAttn( n_head, d_model, d_head, dropout, dropatt=dropatt, primer_conv=primer_conv, pre_lnorm=pre_lnorm, layer_norm_epsilon=layer_norm_epsilon, r_w_bias=r_w_bias, r_r_bias=r_r_bias, ) if primer_square: self.pos_ff = PositionWiseFFPrimerEZ( d_model, d_inner, dropout, pre_lnorm=pre_lnorm, layer_norm_epsilon=layer_norm_epsilon, ) else: self.pos_ff = PositionWiseFF( d_model, d_inner, dropout, pre_lnorm=pre_lnorm, layer_norm_epsilon=layer_norm_epsilon, ) def forward( self, inputs: torch.FloatTensor, embeds: torch.FloatTensor, layer_past: Optional[torch.FloatTensor] = None, dec_attn_mask: Optional[torch.FloatTensor] = None, mems: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, ) -> torch.FloatTensor: attn_output = self.attn( inputs, embeds, layer_past=layer_past, attn_mask=dec_attn_mask, mems=mems, head_mask=head_mask, use_cache=use_cache, output_attentions=output_attentions, ) output = [self.pos_ff(attn_output[0])] + attn_output[1:] return output
archai/archai/discrete_search/search_spaces/nlp/transformer_flex/models/mem_transformer_utils/rel_partial_learnable_decoder.py/0
{ "file_path": "archai/archai/discrete_search/search_spaces/nlp/transformer_flex/models/mem_transformer_utils/rel_partial_learnable_decoder.py", "repo_id": "archai", "token_count": 4836 }
316
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Optional from overrides import overrides from torch import Tensor from archai.common import ml_utils from archai.common.config import Config from archai.supergraph.algos.darts.bilevel_optimizer import BilevelOptimizer from archai.supergraph.datasets import data from archai.supergraph.nas.arch_trainer import ArchTrainer from archai.supergraph.nas.model import Model from archai.supergraph.utils.checkpoint import CheckPoint class BilevelArchTrainer(ArchTrainer): def __init__(self, conf_train: Config, model: Model, checkpoint:Optional[CheckPoint]) -> None: super().__init__(conf_train, model, checkpoint) self._conf_w_optim = conf_train['optimizer'] self._conf_w_lossfn = conf_train['lossfn'] self._conf_alpha_optim = conf_train['alpha_optimizer'] @overrides def pre_fit(self, data_loaders:data.DataLoaders)->None: super().pre_fit(data_loaders) # optimizers, schedulers needs to be recreated for each fit call # as they have state assert data_loaders.val_dl is not None w_momentum = self._conf_w_optim['momentum'] w_decay = self._conf_w_optim['decay'] lossfn = ml_utils.get_lossfn(self._conf_w_lossfn).to(self.get_device()) self._bilevel_optim = BilevelOptimizer(self._conf_alpha_optim, w_momentum, w_decay, self.model, lossfn, self.get_device(), self.batch_chunks) @overrides def post_fit(self, data_loaders:data.DataLoaders)->None: # delete state we created in pre_fit del self._bilevel_optim return super().post_fit(data_loaders) @overrides def pre_epoch(self, data_loaders:data.DataLoaders)->None: super().pre_epoch(data_loaders) # prep val set to train alphas assert data_loaders.val_dl is not None self._val_dl = data_loaders.val_dl self._valid_iter = iter(data_loaders.val_dl) # type: ignore @overrides def post_epoch(self, data_loaders:data.DataLoaders)->None: del self._val_dl del self._valid_iter # clean up super().post_epoch(data_loaders) @overrides def pre_step(self, x: Tensor, y: Tensor) -> None: super().pre_step(x, y) # reset val loader if we exausted it try: x_val, y_val = next(self._valid_iter) except StopIteration: # reinit iterator self._valid_iter = iter(self._val_dl) x_val, y_val = next(self._valid_iter) # update alphas self._bilevel_optim.step(x, y, x_val, y_val, super().get_optimizer()) @overrides def update_checkpoint(self, check_point:CheckPoint)->None: super().update_checkpoint(check_point) check_point['bilevel_optim'] = self._bilevel_optim.state_dict() @overrides def restore_checkpoint(self)->None: super().restore_checkpoint() self._bilevel_optim.load_state_dict(self.check_point['bilevel_optim'])
archai/archai/supergraph/algos/darts/bilevel_arch_trainer.py/0
{ "file_path": "archai/archai/supergraph/algos/darts/bilevel_arch_trainer.py", "repo_id": "archai", "token_count": 1359 }
317
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import math from typing import Iterator, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from overrides import overrides from torch import nn from archai.common.common import get_conf from archai.common.utils import zip_eq from archai.supergraph.nas.arch_params import ArchParams from archai.supergraph.nas.model_desc import OpDesc from archai.supergraph.nas.operations import Op # TODO: reduction cell might have output reduced by 2^1=2X due to # stride 2 through input nodes however FactorizedReduce does only # 4X reduction. Is this correct? class DivOp(Op): """The output of DivOp is weighted output of all allowed primitives. """ PRIMITIVES = [ 'max_pool_3x3', 'avg_pool_3x3', 'skip_connect', # identity 'sep_conv_3x3', 'sep_conv_5x5', 'dil_conv_3x3', 'dil_conv_5x5', 'none' # this must be at the end so top1 doesn't choose it ] # def _indices_of_notallowed(self): # ''' computes indices of notallowed ops in PRIMITIVES ''' # self._not_allowed_indices = [] # for op_name in self.NOTALLOWED: # self._not_allowed_indices.append(self.PRIMITIVES.index(op_name)) # self._not_allowed_indices = sorted(self._not_allowed_indices, reverse=True) # def _create_mapping_valid_to_orig(self): # ''' Creates a list with indices of the valid ops to the original list ''' # self._valid_to_orig = [] # for i, prim in enumerate(self.PRIMITIVES): # if prim in self.NOTALLOWED: # continue # else: # self._valid_to_orig.append(i) def __init__(self, op_desc:OpDesc, arch_params:Optional[ArchParams], affine:bool): super().__init__() # assume last PRIMITIVE is 'none' assert DivOp.PRIMITIVES[-1] == 'none' conf = get_conf() trainer = conf['nas']['search']['divnas']['archtrainer'] finalizer = conf['nas']['search']['finalizer'] if trainer == 'noalpha' and finalizer == 'default': raise NotImplementedError('noalpha trainer is not implemented for the default finalizer') if trainer != 'noalpha': self._setup_arch_params(arch_params) else: self._alphas = None self._ops = nn.ModuleList() for primitive in DivOp.PRIMITIVES: op = Op.create( OpDesc(primitive, op_desc.params, in_len=1, trainables=None), affine=affine, arch_params=None) self._ops.append(op) # various state variables for diversity self._collect_activations = False self._forward_counter = 0 self._batch_activs = None #self._indices_of_notallowed() #self._create_mapping_valid_to_orig() @property def collect_activations(self)->bool: return self._collect_activations @collect_activations.setter def collect_activations(self, to_collect:bool)->None: self._collect_activations = to_collect @property def activations(self)->Optional[List[np.array]]: return self._batch_activs @property def num_primitive_ops(self)->int: return len(self.PRIMITIVES) @overrides def forward(self, x): # save activations to object if self._collect_activations: self._forward_counter += 1 activs = [op(x) for op in self._ops] # delete the activation for none type # as we don't consider it activs = activs[:-1] self._batch_activs = [t.cpu().detach().numpy() for t in activs] if self._alphas: asm = F.softmax(self._alphas[0], dim=0) result = sum(w * op(x) for w, op in zip(asm, self._ops)) else: result = sum(op(x) for op in self._ops) return result @overrides def ops(self)->Iterator[Tuple['Op', float]]: # type: ignore return iter(sorted(zip_eq(self._ops, self._alphas[0] if self._alphas is not None else [math.nan for _ in range(len(self._ops))]), key=lambda t:t[1], reverse=True)) # def get_valid_op_desc(self, index:int)->OpDesc: # ''' index: index in the valid index list ''' # assert index <= self.num_valid_div_ops # orig_index = self._valid_to_orig[index] # desc, _ = self._ops[orig_index].finalize() # return desc @overrides def finalize(self) -> Tuple[OpDesc, Optional[float]]: ''' Divnas with default finalizer option needs this override else the finalizer in base class returns the whole divop ''' with torch.no_grad(): # select except 'none' op val, i = torch.topk(self._alphas[0][:-1], 1) desc, _ = self._ops[i].finalize() return desc, float(val.item()) @overrides def can_drop_path(self) -> bool: return False def _setup_arch_params(self, arch_params:Optional[ArchParams])->None: # do we have shared arch params? if arch_params is None: # create our own arch params new_p = nn.Parameter( # TODO: use better init than uniform random? 1.0e-3*torch.randn(len(self.PRIMITIVES)), requires_grad=True) self.create_arch_params([('alphas', new_p)]) else: assert arch_params.has_kind('alphas') self.set_arch_params(arch_params) # we store alphas in list so Pytorch don't register them self._alphas = list(self.arch_params().param_by_kind('alphas')) assert len(self._alphas)==1
archai/archai/supergraph/algos/divnas/divop.py/0
{ "file_path": "archai/archai/supergraph/algos/divnas/divop.py", "repo_id": "archai", "token_count": 2547 }
318
from __future__ import absolute_import, division, print_function import torch.nn as nn class ConvBnRelu(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0): super(ConvBnRelu, self).__init__() self.conv_bn_relu = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True) ) def forward(self, x): return self.conv_bn_relu(x) class Conv3x3BnRelu(nn.Module): """3x3 convolution with batch norm and ReLU activation.""" def __init__(self, in_channels, out_channels): super(Conv3x3BnRelu, self).__init__() self.conv3x3 = ConvBnRelu(in_channels, out_channels, 3, 1, 1) def forward(self, x): x = self.conv3x3(x) return x class Conv1x1BnRelu(nn.Module): """1x1 convolution with batch norm and ReLU activation.""" def __init__(self, in_channels, out_channels): super(Conv1x1BnRelu, self).__init__() self.conv1x1 = ConvBnRelu(in_channels, out_channels, 1, 1, 0) def forward(self, x): x = self.conv1x1(x) return x class MaxPool3x3(nn.Module): """3x3 max pool with no subsampling.""" def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super(MaxPool3x3, self).__init__() self.maxpool = nn.MaxPool2d(kernel_size, stride, padding) def forward(self, x): x = self.maxpool(x) return x # Commas should not be used in op names OP_MAP = { 'conv3x3-bn-relu': Conv3x3BnRelu, 'conv1x1-bn-relu': Conv1x1BnRelu, 'maxpool3x3': MaxPool3x3 }
archai/archai/supergraph/algos/nasbench101/base_ops.py/0
{ "file_path": "archai/archai/supergraph/algos/nasbench101/base_ops.py", "repo_id": "archai", "token_count": 805 }
319
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import heapq from copy import deepcopy from typing import Iterator, List, Optional, Tuple import torch from overrides import overrides from torch import Tensor, nn from archai.common.utils import zip_eq from archai.supergraph.nas.arch_params import ArchParams from archai.supergraph.nas.model_desc import OpDesc from archai.supergraph.nas.operations import FactorizedReduce, Identity, Op class StopForward(Op): def __init__(self): super().__init__() self._sg_op = StopGradient() @overrides def forward(self, x): y = x - self._sg_op(x) return y class StopGradient(Op): @staticmethod def _zero_grad(grad): return torch.zeros_like(grad) @overrides def forward(self, x): y = x * 1 if self.training: # TODO: check with Dey, without this search time validation doesn't work y.register_hook(StopGradient._zero_grad) return y class StopForwardReductionOp(Op): def __init__(self, op_desc:OpDesc, affine:bool): super().__init__() self._op = nn.Sequential( StopForward(), FactorizedReduce(op_desc, affine) ) @overrides def forward(self, x): return self._op(x) class StopGradientReduction(Op): def __init__(self, op_desc:OpDesc, affine:bool): super().__init__() self._op = nn.Sequential( StopGradient(), FactorizedReduce(op_desc, affine) ) @overrides def forward(self, x): return self._op(x) class TempIdentityOp(Identity): def __init__(self, op_desc) -> None: super().__init__(op_desc) @overrides def forward(self, x): return x class PetridishOp(Op): PRIMITIVES = [ 'max_pool_3x3', 'avg_pool_3x3', 'skip_connect', # identity 'sep_conv_3x3', 'sep_conv_5x5', 'dil_conv_3x3', 'dil_conv_5x5', 'none' # this must be at the end so top1 doesn't chose it ] def __init__(self, op_desc:OpDesc, arch_params: Optional[ArchParams], reduction:bool, affine:bool): super().__init__() # assume last PRIMITIVE is 'none' (this is used for finalize) assert PetridishOp.PRIMITIVES[-1] == 'none' # create edges for the op, each edge connects input state, # within each edge we will have all N primitives self._edges = nn.ModuleList() for i in range(op_desc.in_len): # edge contains all primitives with alphas edge = nn.ModuleList() self._edges.append(edge) # for each input stride could be different, # so we will make copy of our params and then set stride for this input params = deepcopy(op_desc.params) params['stride'] = op_desc.params['_strides'][i] # create primitives for the edge for primitive in PetridishOp.PRIMITIVES: primitive_op = Op.create(OpDesc(primitive, params=params, in_len=1, trainables=None), affine=affine, arch_params=None) # wrap primitive with sg op = nn.Sequential(StopGradient(), primitive_op) edge.append(op) # TODO: check with Dey: Do we really need StopForwardReductionOp # or StopGradientReductionOp because these two will only make sense # for cell stems. # NOTE: Consider the case where prev_prev is normal, prev is reduction # then s_0 is twice as big in each dimension as s_1 and the number of channels # won't match. So you have to use StopGradientReductionOp on s_1 to make it match. self._sf = StopForward() # we do this at the end so that we can capture all arch params registered by # any previous child modules self._setup_arch_params(arch_params, op_desc.in_len) @overrides def forward(self, x:List[Tensor]): assert not isinstance(x, torch.Tensor) s = 0.0 # apply each input in the list to associated edge for i, (xi, edge) in enumerate(zip_eq(x, self._edges)): # apply input to each primitive within edge # TODO: is avg better idea than sum here? sum can explode as # number of primitives goes up s = sum(a * op(xi) for a, op in zip_eq(self._alphas[0][i], edge)) + s return self._sf(s) def _flatten_ops_alphas(self): # Create list of (alpha, input_id, op_desc), sort them, select top k. # Here op should be nn.Sequence of sg followed by primitive. # First for loop gets edge and associated alphas. # Second for loop gets op and associated alpha. return ((a, i, op[1]) # op is nn.Sequence of stop grad and primitive op \ for edge_alphas, i, edge in \ zip_eq(self._alphas[0], range(self.desc.in_len), self._edges) \ for a, op in zip_eq(edge_alphas, edge)) @overrides def finalize(self) -> Tuple[OpDesc, Optional[float]]: with torch.no_grad(): # probably this is not needed l = self._flatten_ops_alphas() # select 3 largest ops by alpha sel = heapq.nlargest(3, l, key=lambda t: t[0]) # TODO: add config # multi_op needs to know each input and associated primitive final_op_desc = OpDesc(name='multi_op', params={ # copy convolution parameters 'conv': self.desc.params['conv'] }, # Number of inputs remains same although only 3 of # them will be used. in_len=self.desc.in_len, trainables=None, # primitive's finalize call also records its # weights in description. finalize call returns # (desc, rank) where rank for primitive is None children = [op.finalize()[0] for a,i,op in sel], children_ins = [i for a,i,op in sel] ) # rank=None to indicate no further selection needed as in darts return final_op_desc, None @overrides def ops(self)->Iterator[Tuple['Op', float]]: # type: ignore return iter(sorted(((op, a) for a, i, op in self._flatten_ops_alphas()), key=lambda t:t[1], reverse=True)) def _setup_arch_params(self, arch_params:Optional[ArchParams], in_len:int)->None: # do we have shared arch params? if arch_params is None: # Each nn.Parameter is tensor with alphas for entire edge. # We will create same numbers of nn.Parameter as number of edges n_primitives = len(PetridishOp.PRIMITIVES) pl = nn.ParameterList(( nn.Parameter( # TODO: use better init than uniform random? torch.FloatTensor(n_primitives).uniform_(-0.1, 0.1), requires_grad=True) for _ in range(in_len) )) self.create_arch_params([('alphas', pl)]) else: assert arch_params.has_kind('alphas') self.set_arch_params(arch_params) # we store alphas in list so Pytorch don't register them self._alphas = list(self.arch_params().paramlist_by_kind('alphas')) assert len(self._alphas)==1
archai/archai/supergraph/algos/petridish/petridish_op.py/0
{ "file_path": "archai/archai/supergraph/algos/petridish/petridish_op.py", "repo_id": "archai", "token_count": 3659 }
320
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import math from typing import Iterable, Optional, Tuple import numpy as np import torch import torch.distributed as dist from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit from torch.utils.data import Sampler from torch.utils.data.dataset import Dataset class DistributedStratifiedSampler(Sampler): """Distributed stratified sampling of dataset. This sampler works in distributed as well as non-distributed setting with no penalty in either mode and is a replacement for built-in `torch.util.data.DistributedSampler`. In distributed setting, many instances of the same code runs as process known as replicas. Each replica has sequential number assigned by the launcher, starting from 0 to uniquely identify it. This is known as global rank or simply rank. The number of replicas is known as the world size. For non-distributed setting, `world_size=1` and `rank=0`. This sampler assumes that labels for each datapoint is available in dataset.targets property which should be array like containing as many values as length of the dataset. This is availalble already for many popular datasets such as cifar and, with newer PyTorch versions, `ImageFolder` as well as `DatasetFolder`. If you are using custom dataset, you can usually create this property with one line of code such as `dataset.targets = [yi for _, yi in dataset]`. To do distributed sampling, each replica must shuffle with same seed as all other replicas with every epoch and then chose some subset of dataset for itself. Traditionally, we use epoch number as seed for shuffling for each replica. However, this then requires that training code calls `sampler.set_epoch(epoch)` to set seed at every epoch. """ def __init__( self, dataset: Dataset, world_size: Optional[int] = None, rank: Optional[int] = None, shuffle: Optional[bool] = True, val_ratio: Optional[float] = 0.0, is_val_split: Optional[bool] = False, max_samples: Optional[int] = None, ) -> None: """Initialize the sampler. Args: dataset: Input dataset. world_size: Total number of replicas. If `None` then auto-detect, while 1 for non-distributed setting. rank: Global rank of this replica. If `None` then auto-detect, while 0 for non-distributed setting. shuffle: Whether shuffling should be applied for every epoch. val_ratio: Creates a validation split when set to > 0. is_val_split: Whether the validation split should be returned. max_samples: Maximum number of samples for each replica. """ # CIFAR-10 amd DatasetFolder has this attribute # For others it may be easy to add from outside assert ( hasattr(dataset, "targets") and dataset.targets is not None ), "dataset needs to have targets attribute to work with this sampler" if world_size is None: if dist.is_available() and dist.is_initialized(): world_size = dist.get_world_size() else: world_size = 1 if rank is None: if dist.is_available() and dist.is_initialized(): rank = dist.get_rank() else: rank = 0 if val_ratio is None: val_ratio = 0.0 assert world_size >= 1 assert rank >= 0 and rank < world_size assert val_ratio < 1.0 and val_ratio >= 0.0 self.dataset = dataset self.world_size = world_size self.rank = rank self.epoch = 0 # Used as a seed self.shuffle = shuffle self.data_len = len(self.dataset) self.max_samples = max_samples if max_samples is not None and max_samples >= 0 else None assert self.data_len == len(dataset.targets) self.val_ratio = val_ratio self.is_val_split = is_val_split # Computes duplications of dataset to make it divisible by world_size self.replica_len = self.replica_len_full = int(math.ceil(float(self.data_len) / self.world_size)) self.total_size = self.replica_len_full * self.world_size assert self.total_size >= self.data_len if self.max_samples is not None: self.replica_len = min(self.replica_len_full, self.max_samples) self.main_split_len = int(math.floor(self.replica_len * (1 - val_ratio))) self.val_split_len = self.replica_len - self.main_split_len self._len = self.val_split_len if self.is_val_split else self.main_split_len def __len__(self) -> int: return self._len def __iter__(self) -> Iterable: indices, targets = self._get_indices() indices, targets = self._split_rank(indices, targets) indices, targets = self._limit_indices(indices, targets, self.max_samples) indices, _ = self._split_indices(indices, targets, self.val_split_len, self.is_val_split) assert len(indices) == self._len if self.shuffle and self.val_ratio > 0.0 and self.epoch > 0: np.random.shuffle(indices) return iter(indices) def _split_rank(self, indices: np.ndarray, targets: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: if self.world_size > 1: replica_fold_idxs = None rfolder = StratifiedKFold(n_splits=self.world_size, shuffle=False) folds = rfolder.split(indices, targets) for _ in range(self.rank + 1): _, replica_fold_idxs = next(folds) assert replica_fold_idxs is not None and len(replica_fold_idxs) == self.replica_len_full return indices[replica_fold_idxs], targets[replica_fold_idxs] assert self.world_size == 1 return indices, targets def _get_indices(self) -> Tuple[np.ndarray, np.ndarray]: if self.shuffle: g = torch.Generator() g.manual_seed(self._get_seed()) indices = torch.randperm(self.data_len, generator=g).numpy() else: indices = np.arange(self.data_len) if self.total_size > self.data_len: indices = np.append(indices, indices[: (self.total_size - self.data_len)]) else: assert self.total_size == self.data_len, "`total_size` cannot be less than dataset size." targets = np.array(list(self.dataset.targets[i] for i in indices)) assert len(indices) == self.total_size return indices, targets def _limit_indices( self, indices: np.ndarray, targets: np.ndarray, max_samples: Optional[int] ) -> Tuple[np.ndarray, np.ndarray]: if max_samples is not None: return self._split_indices(indices, targets, len(indices) - max_samples, False) return indices, targets def _get_seed(self) -> int: return self.epoch if self.val_ratio == 0.0 else 0 def _split_indices( self, indices: np.ndarray, targets: np.ndarray, val_size: int, return_val_split: bool ) -> Tuple[np.ndarray, np.ndarray]: if val_size: assert isinstance(val_size, int) vfolder = StratifiedShuffleSplit(n_splits=1, test_size=val_size, random_state=self._get_seed()) vfolder = vfolder.split(indices, targets) train_idx, valid_idx = next(vfolder) idxs = valid_idx if return_val_split else train_idx return indices[idxs], targets[idxs] return indices, targets def set_epoch(self, epoch: int) -> None: """Set the epoch for the current replica, which is used to seed the shuffling. Args: epoch: Epoch number. """ self.epoch = epoch
archai/archai/supergraph/datasets/distributed_stratified_sampler.py/0
{ "file_path": "archai/archai/supergraph/datasets/distributed_stratified_sampler.py", "repo_id": "archai", "token_count": 3200 }
321
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import torchvision from overrides import overrides from torchvision.transforms import transforms from archai.common import utils from archai.common.config import Config from archai.supergraph.datasets.dataset_provider import ( DatasetProvider, ImgSize, TrainTestDatasets, register_dataset_provider, ) class StanfordCarsProvider(DatasetProvider): def __init__(self, conf_dataset:Config): super().__init__(conf_dataset) self._dataroot = utils.full_path(conf_dataset['dataroot']) @overrides def get_datasets(self, load_train:bool, load_test:bool, transform_train, transform_test)->TrainTestDatasets: trainset, testset = None, None if load_train: trainpath = os.path.join(self._dataroot, 'stanfordcars', 'train') trainset = torchvision.datasets.ImageFolder(trainpath, transform=transform_train) if load_test: testpath = os.path.join(self._dataroot, 'stanfordcars', 'test') testset = torchvision.datasets.ImageFolder(testpath, transform=transform_test) return trainset, testset @overrides def get_transforms(self, img_size:ImgSize)->tuple: print(f'IMG SIZE: {img_size}') if isinstance(img_size, int): img_size = (img_size, img_size) # TODO: update MEAN, STD, currently mit67 values MEAN = [0.4893, 0.4270, 0.3625] STD = [0.2631, 0.2565, 0.2582] # transformations match that in # https://github.com/antoyang/NAS-Benchmark/blob/master/DARTS/preproc.py train_transf = [ transforms.RandomResizedCrop(img_size, scale=(0.75, 1)), transforms.RandomHorizontalFlip(), transforms.ColorJitter( brightness=0.4, contrast=0.4, saturation=0.4, hue=0.2) ] margin_size = (int(img_size[0] + img_size[0]*0.1), int(img_size[1] + img_size[1]*0.1)) test_transf = [transforms.Resize(margin_size), transforms.CenterCrop(img_size)] #test_transf = [transforms.Resize(img_size)] normalize = [ transforms.ToTensor(), transforms.Normalize(MEAN, STD) ] train_transform = transforms.Compose(train_transf + normalize) test_transform = transforms.Compose(test_transf + normalize) return train_transform, test_transform register_dataset_provider('stanfordcars', StanfordCarsProvider)
archai/archai/supergraph/datasets/providers/stanfordcars_provider.py/0
{ "file_path": "archai/archai/supergraph/datasets/providers/stanfordcars_provider.py", "repo_id": "archai", "token_count": 1134 }
322
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class ShakeShake(torch.autograd.Function): @staticmethod def forward(ctx, x1, x2, training=True): if training: alpha = torch.cuda.FloatTensor(x1.size(0)).uniform_() alpha = alpha.view(alpha.size(0), 1, 1, 1).expand_as(x1) else: alpha = 0.5 return alpha * x1 + (1 - alpha) * x2 @staticmethod def backward(ctx, grad_output): beta = torch.cuda.FloatTensor(grad_output.size(0)).uniform_() beta = beta.view(beta.size(0), 1, 1, 1).expand_as(grad_output) beta = Variable(beta) return beta * grad_output, (1 - beta) * grad_output, None class Shortcut(nn.Module): def __init__(self, in_ch, out_ch, stride): super(Shortcut, self).__init__() self.stride = stride self.conv1 = nn.Conv2d(in_ch, out_ch // 2, 1, stride=1, padding=0, bias=False) self.conv2 = nn.Conv2d(in_ch, out_ch // 2, 1, stride=1, padding=0, bias=False) self.bn = nn.BatchNorm2d(out_ch) def forward(self, x): h = F.relu(x) h1 = F.avg_pool2d(h, 1, self.stride) h1 = self.conv1(h1) h2 = F.avg_pool2d(F.pad(h, (-1, 1, -1, 1)), 1, self.stride) h2 = self.conv2(h2) h = torch.cat((h1, h2), dim=1) return self.bn(h)
archai/archai/supergraph/models/shakeshake/shakeshake.py/0
{ "file_path": "archai/archai/supergraph/models/shakeshake/shakeshake.py", "repo_id": "archai", "token_count": 700 }
323
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import copy import math from abc import ABC from argparse import ArgumentError from typing import ( Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Tuple, Union, ) import torch from overrides import EnforceOverrides, overrides from torch import Tensor, nn from archai.common import ml_utils from archai.supergraph.nas.arch_module import ArchModule from archai.supergraph.nas.arch_params import ArchParams from archai.supergraph.nas.model_desc import ConvMacroParams, OpDesc # type alias OpFactoryFn = Callable[[OpDesc, Iterable[nn.Parameter]], 'Op'] # Each op is a unary tensor operator, all take same constructor params # TODO: swap order of arch_params and affine to match with create signature _ops_factory:Dict[str, Callable] = { 'max_pool_3x3': lambda op_desc, arch_params, affine: PoolBN('max', op_desc, affine), 'avg_pool_3x3': lambda op_desc, arch_params, affine: PoolBN('avg', op_desc, affine), 'skip_connect': lambda op_desc, arch_params, affine: SkipConnect(op_desc, affine), 'sep_conv_3x3': lambda op_desc, arch_params, affine: SepConv(op_desc, 3, 1, affine), 'sep_conv_5x5': lambda op_desc, arch_params, affine: SepConv(op_desc, 5, 2, affine), 'convbnrelu_3x3': lambda op_desc, arch_params, affine: # used by NASBench-101 ConvBNReLU(op_desc, 3, 1, 1, affine), 'convbnrelu_1x1': lambda op_desc, arch_params, affine: # used by NASBench-101 ConvBNReLU(op_desc, 1, 1, 0, affine), 'dil_conv_3x3': lambda op_desc, arch_params, affine: DilConv(op_desc, 3, op_desc.params['stride'], 2, 2, affine), 'dil_conv_5x5': lambda op_desc, arch_params, affine: DilConv(op_desc, 5, op_desc.params['stride'], 4, 2, affine), 'none': lambda op_desc, arch_params, affine: Zero(op_desc), 'identity': lambda op_desc, arch_params, affine: Identity(op_desc), 'sep_conv_7x7': lambda op_desc, arch_params, affine: SepConv(op_desc, 7, 3, affine), 'conv_7x1_1x7': lambda op_desc, arch_params, affine: FacConv(op_desc, 7, 3, affine), 'prepr_reduce': lambda op_desc, arch_params, affine: FactorizedReduce(op_desc, affine), 'prepr_normal': lambda op_desc, arch_params, affine: ReLUConvBN(op_desc, 1, 1, 0, affine), 'stem_conv3x3': lambda op_desc, arch_params, affine: StemConv3x3(op_desc, affine), 'stem_conv3x3Relu': lambda op_desc, arch_params, affine: StemConv3x3Relu(op_desc, affine), 'stem_conv3x3_s4': lambda op_desc, arch_params, affine: StemConv3x3S4(op_desc, affine), 'stem_conv3x3_s4s2': lambda op_desc, arch_params, affine: StemConv3x3S4S2(op_desc, affine), 'pool_adaptive_avg2d': lambda op_desc, arch_params, affine: PoolAdaptiveAvg2D(), 'pool_avg2d7x7': lambda op_desc, arch_params, affine: AvgPool2d7x7(), 'pool_mean_tensor': lambda op_desc, arch_params, affine: PoolMeanTensor(), 'concate_channels': lambda op_desc, arch_params, affine: ConcateChannelsOp(op_desc, affine), 'proj_channels': lambda op_desc, arch_params, affine: ProjectChannelsOp(op_desc, affine), 'linear': lambda op_desc, arch_params, affine: LinearOp(op_desc), 'multi_op': lambda op_desc, arch_params, affine: MultiOp(op_desc, affine) } class Op(ArchModule, ABC, EnforceOverrides): @staticmethod def create(op_desc:OpDesc, affine:bool, arch_params:Optional[ArchParams]=None)->'Op': global _ops_factory op = _ops_factory[op_desc.name](op_desc, arch_params, affine) # TODO: annotate as Final? op.desc = op_desc # type: ignore # load any pre-trained weights op.set_trainables(op_desc.trainables) return op def get_trainables(self)->Mapping: return {'name': self.desc.name, 'sd': self.state_dict()} def set_trainables(self, state_dict)->None: if state_dict is not None: assert state_dict['name'] == self.desc.name # At search time, batchnorms are not affine so when restoring # weights during pretraining we don't have those keys which is why # we use strict=False # TODO: should we assign op_desc uuid to enforce more strictness? self.load_state_dict(state_dict['sd'], strict=False) @staticmethod def register_op(name: str, factory_fn: Callable, exists_ok=True) -> None: global _ops_factory if name in _ops_factory: if not exists_ok: raise ArgumentError(argument=None, message=f'{name} is already registered in op factory') # else no need to register again else: _ops_factory[name] = factory_fn def finalize(self)->Tuple[OpDesc, Optional[float]]: """for trainable op, return final op and its rank""" # make copy because we are going to modify the trainables desc = self.desc.clone(clone_trainables=False) # make copy of trainables so we don't keep around references desc.trainables = copy.deepcopy(self.get_trainables()) return desc, None # desc, rank (None means op is unranked and cannot be removed) def ops(self)->Iterator[Tuple['Op', float]]: # type: ignore """Return contituent ops, if this op is primitive just return self""" yield self, math.nan # if op should not be dropped during drop path then return False def can_drop_path(self)->bool: return True class PoolBN(Op): """AvgPool or MaxPool - BN """ def __init__(self, pool_type:str, op_desc:OpDesc, affine:bool): """ Args: pool_type: 'max' or 'avg' """ super().__init__() conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in stride = op_desc.params['stride'] kernel_size = op_desc.params.get('kernel_size', 3) padding = op_desc.params.get('padding', 1) if pool_type.lower() == 'max': self.pool = nn.MaxPool2d(kernel_size, stride, padding) elif pool_type.lower() == 'avg': self.pool = nn.AvgPool2d( kernel_size, stride, padding, count_include_pad=False) else: raise ValueError() # TODO: pt.darts applies BN but original implementation doesn't # self.bn = nn.BatchNorm2d(ch_in, affine=affine) @overrides def forward(self, x): out = self.pool(x) #out = self.bn(out) return out class SkipConnect(Op): def __init__(self, op_desc:OpDesc, affine) -> None: super().__init__() stride = op_desc.params['stride'] self._op = Identity(op_desc) if stride == 1 \ else FactorizedReduce(op_desc, affine) @overrides def forward(self, x:Tensor)->Tensor: return self._op(x) @overrides def can_drop_path(self)->bool: # TODO: original darts drops path only for identity, not FactorizedReduce # but that seems wrong. Here we drop path for skip connect. return False class FacConv(Op): """ Factorized conv ReLU - Conv(Kx1) - Conv(1xK) - BN """ def __init__(self, op_desc:OpDesc, kernel_length:int, padding:int, affine:bool): super().__init__() conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out stride = op_desc.params['stride'] self.net = nn.Sequential( nn.ReLU(), nn.Conv2d(ch_in, ch_in, (kernel_length, 1), stride, padding, bias=False), nn.Conv2d(ch_in, ch_out, (1, kernel_length), stride, padding, bias=False), nn.BatchNorm2d(ch_out, affine=affine) ) @overrides def forward(self, x): return self.net(x) class ReLUConvBN(Op): # std DARTS op has BN at the end def __init__(self, op_desc:OpDesc, kernel_size:int, stride:int, padding:int, affine:bool): conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out super(ReLUConvBN, self).__init__() self.op = nn.Sequential( nn.ReLU(), nn.Conv2d(ch_in, ch_out, kernel_size, stride=stride, padding=padding, bias=False), nn.BatchNorm2d(ch_out, affine=affine) ) @overrides def forward(self, x): return self.op(x) class ConvBNReLU(Op): # NAS bench op has BN in the middle def __init__(self, op_desc:OpDesc, kernel_size:int, stride:int, padding:int, affine:bool): conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out super(ConvBNReLU, self).__init__() self.op = nn.Sequential( nn.Conv2d(ch_in, ch_out, kernel_size, stride=stride, padding=padding, bias=False), nn.BatchNorm2d(ch_out, affine=affine), nn.ReLU(inplace=True) #TODO: review inplace ) @overrides def forward(self, x): return self.op(x) class DilConv(Op): """ (Dilated) depthwise separable conv ReLU - (Dilated) depthwise separable - Pointwise - BN If dilation == 2, 3x3 conv => 5x5 receptive field 5x5 conv => 9x9 receptive field """ def __init__(self, op_desc:OpDesc, kernel_size:int, stride:int, padding:int, dilation:int, affine:bool): super(DilConv, self).__init__() conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out self.op = nn.Sequential( nn.ReLU(), nn.Conv2d(ch_in, ch_in, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=ch_in, bias=False), nn.Conv2d(ch_in, ch_out, kernel_size=1, padding=0, bias=False), nn.BatchNorm2d(ch_out, affine=affine), ) @overrides def forward(self, x): return self.op(x) class SepConv(Op): """ Depthwise separable conv DilConv(dilation=1) * 2 This is same as two DilConv stacked with dilation=1 """ def __init__(self, op_desc:OpDesc, kernel_size:int, padding:int, affine:bool): super(SepConv, self).__init__() self.op = nn.Sequential( DilConv(op_desc, kernel_size, op_desc.params['stride'], padding, dilation=1, affine=affine), DilConv(op_desc, kernel_size, 1, padding, dilation=1, affine=affine)) @overrides def forward(self, x): return self.op(x) class Identity(Op): def __init__(self, op_desc:OpDesc): super().__init__() stride, conv_params = op_desc.params['stride'], op_desc.params['conv'] assert stride == 1 assert conv_params.ch_in == conv_params.ch_out @overrides def forward(self, x): return x @overrides def can_drop_path(self)->bool: return False class Zero(Op): """Represents no connection. Zero op can be thought of 1x1 kernel with fixed zero weight. For stride=1, it will produce output of same dimension as input but with all 0s. Now with stride of 2, it will zero out every other pixel in output. """ def __init__(self, op_desc:OpDesc): super().__init__() stride = op_desc.params['stride'] self.stride = stride @overrides def forward(self, x): if self.stride == 1: return x.mul(0.) return x[:, :, ::self.stride, ::self.stride].mul(0.) class FactorizedReduce(Op): """ reduce feature maps height/width by 2X while doubling channels using two 1x1 convs, each with stride=2. """ # TODO: modify to take number of nodes in reduction cells where stride 2 was applied (currently only first two input nodes) def __init__(self, op_desc:OpDesc, affine:bool): super(FactorizedReduce, self).__init__() conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out assert ch_out % 2 == 0 self.relu = nn.ReLU() # this conv layer operates on even pixels to produce half width, half channels self.conv_1 = nn.Conv2d(ch_in, ch_out // 2, 1, stride=2, padding=0, bias=False) # this conv layer operates on odd pixels (because of code in forward()) to produce half width, half channels self.conv_2 = nn.Conv2d(ch_in, ch_out // 2, 1, stride=2, padding=0, bias=False) self.bn = nn.BatchNorm2d(ch_out, affine=affine) @overrides def forward(self, x): x = self.relu(x) # x: torch.Size([32, 32, 32, 32]) # conv1: [b, c_out//2, d//2, d//2] # conv2: [] # out: torch.Size([32, 32, 16, 16]) # concate two half channels to produce same number of channels as before but with output as only half the width out = torch.cat([self.conv_1(x), self.conv_2(x[:, :, 1:, 1:])], dim=1) out = self.bn(out) return out class StemBase(Op): """Abstract base class for model stems that enforces reduction property indicating amount of spatial map reductions performed by stem, i.e., reduction=2 for each stride=2""" def __init__(self, reduction:int) -> None: super().__init__() self.reduction = reduction class StemConv3x3(StemBase): def __init__(self, op_desc:OpDesc, affine:bool)->None: super().__init__(1) conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out self._op = nn.Sequential( # 3 => 48 # batchnorm is added after each layer. Bias is turned off due to # BN in conv layer. nn.Conv2d(ch_in, ch_out, 3, padding=1, bias=False), nn.BatchNorm2d(ch_out, affine=affine) ) @overrides def forward(self, x): return self._op(x) @overrides def can_drop_path(self)->bool: return False class StemConv3x3Relu(StemBase): # used in NASbench-101 def __init__(self, op_desc:OpDesc, affine:bool)->None: super().__init__(1) conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out self._op = nn.Sequential( # 3 => 48 # batchnorm is added after each layer. Bias is turned off due to # BN in conv layer. nn.Conv2d(ch_in, ch_out, 3, padding=1, bias=False), nn.BatchNorm2d(ch_out, affine=affine), nn.ReLU(inplace=True) ) @overrides def forward(self, x): return self._op(x) @overrides def can_drop_path(self)->bool: return False class StemConv3x3S4(StemBase): def __init__(self, op_desc, affine:bool)->None: super().__init__(4) conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out self._op = nn.Sequential( # keep in sync with StemConv3x3S4S2 nn.Conv2d(ch_in, ch_out//2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(ch_out//2, affine=affine), nn.ReLU(inplace=True), nn.Conv2d(ch_out//2, ch_out, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(ch_out, affine=affine) ) @overrides def forward(self, x): return self._op(x) @overrides def can_drop_path(self)->bool: return False class StemConv3x3S4S2(StemBase): def __init__(self, op_desc, affine:bool)->None: super().__init__(8) conv_params:ConvMacroParams = op_desc.params['conv'] ch_in = conv_params.ch_in ch_out = conv_params.ch_out self._op = nn.Sequential( # s4 ops - keep in sync with StemConv3x3S4 nn.Conv2d(ch_in, ch_out//2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(ch_out//2, affine=affine), nn.ReLU(inplace=True), nn.Conv2d(ch_out//2, ch_out, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(ch_out, affine=affine), # s2 ops nn.ReLU(inplace=True), nn.Conv2d(ch_out, ch_out, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(ch_out, affine=affine) ) @overrides def forward(self, x): return self._op(x) @overrides def can_drop_path(self)->bool: return False class AvgPool2d7x7(Op): def __init__(self)->None: super().__init__() self._op = nn.AvgPool2d(7) @overrides def forward(self, x): return self._op(x) @overrides def can_drop_path(self)->bool: return False class PoolAdaptiveAvg2D(Op): def __init__(self)->None: super().__init__() self._op = nn.AdaptiveAvgPool2d(1) @overrides def forward(self, x): return self._op(x) @overrides def can_drop_path(self)->bool: return False class PoolMeanTensor(Op): # used in Nasbench-101 def __init__(self)->None: super().__init__() @overrides def forward(self, x): return torch.mean(x, (2, 3)) @overrides def can_drop_path(self)->bool: return False class LinearOp(Op): def __init__(self, op_desc:OpDesc)->None: super().__init__() n_ch = op_desc.params['n_ch'] n_classes = op_desc.params['n_classes'] self._op = nn.Linear(n_ch, n_classes) @overrides def forward(self, x:torch.Tensor): flattened = x.view(x.size(0), -1) return self._op(flattened) @overrides def can_drop_path(self)->bool: return False class MergeOp(Op, ABC): def __init__(self, op_desc:OpDesc, affine:bool)->None: super().__init__() self.ch_in = op_desc.params['conv'].ch_in self.ch_out = op_desc.params['conv'].ch_out self.out_states = op_desc.params['out_states'] @overrides def forward(self, states:List[torch.Tensor]): raise NotImplementedError() @overrides def can_drop_path(self)->bool: return False class ConcateChannelsOp(MergeOp): def __init__(self, op_desc:OpDesc, affine:bool)->None: super().__init__(op_desc, affine) @overrides def forward(self, states:List[torch.Tensor]): return torch.cat(states[-self.out_states:], dim=1) class ProjectChannelsOp(MergeOp): def __init__(self, op_desc:OpDesc, affine:bool)->None: super().__init__(op_desc, affine) self._op = nn.Sequential( nn.Conv2d(self.ch_in, self.ch_out, 1, # 1x1 conv stride=1, padding=0, bias=False), nn.BatchNorm2d(self.ch_out, affine=affine) ) @overrides def forward(self, states:List[torch.Tensor]): concatenated = torch.cat(states[-self.out_states:], dim=1) return self._op(concatenated) class DropPath_(nn.Module): """Replace values in tensor by 0. with probability p Ref: https://arxiv.org/abs/1605.07648 """ def __init__(self, p:float=0.): """ [!] DropPath is inplace module Args: p: probability of an path to be zeroed. """ super().__init__() self.p = p def extra_repr(self): return 'p={}, inplace'.format(self.p) @overrides def forward(self, x): return ml_utils.drop_path_(x, self.p, self.training) class MultiOp(Op): def __init__(self, op_desc:OpDesc, affine:bool) -> None: """MultiOp combines multiple ops to one op. The set of ops to combine if passed through op_desc.children and each of children's inputs are passed through op_desc.children_ins. This op will receive list of inputs in forward() and each of the children works on one of these inputs and generates an output. All outputs of children are then combined using projection operation to produce final output of the overall op. """ super().__init__() # get list of inputs and associated primitives iop_descs = op_desc.children ins = op_desc.children_ins assert iop_descs is not None and ins is not None and len(iop_descs) == len(ins) # conv params typically specified by macro builder conv_params:ConvMacroParams = op_desc.params['conv'] self._ops = nn.ModuleList() self._ins:List[int] = [] for i, iop_desc in zip(ins, iop_descs): iop_desc.params['conv'] = conv_params self._ops.append(Op.create(iop_desc, affine=affine)) self._ins.append(i) # number of channels as we will concate output of ops ch_out_sum = conv_params.ch_out * len(self._ins) ch_adj_desc = OpDesc('proj_channels', { 'conv': ConvMacroParams(ch_out_sum, conv_params.ch_out), 'out_states': len(self._ins) }, in_len=1, trainables=None, children=None) self._ch_adj = Op.create(ch_adj_desc, affine=affine) @overrides def forward(self, x:Union[Tensor, List[Tensor]])->Tensor: # we may receive k=1..N tensors as inputs. Currently DagEdge will pass # tensor as-is if k=1 to support primitives and create list of tensors # if k > 1. So below we handle k = 1 case. if not isinstance(x, list): x = [x] return self._ch_adj([op(x[i]) for op, i in zip(self._ops, self._ins)])
archai/archai/supergraph/nas/operations.py/0
{ "file_path": "archai/archai/supergraph/nas/operations.py", "repo_id": "archai", "token_count": 10862 }
324
__include__: "darts.yaml" # just use darts defaults nas: search: trainer: epochs: 200 alpha_optimizer: type: 'sgd' lr: 0.025 # init learning rate decay: 3.0e-4 momentum: 0.9 # pytorch default is 0 nesterov: False decay_bn: .NaN # if NaN then same as decay otherwise apply different decay to BN layers alpha_lr_schedule: type: 'cosine' min_lr: 0.0 # 0.001 min learning rate, this will be used in eta_min param of scheduler warmup: null loader: val_ratio: 0.1 #split portion for test set, 0 to 1
archai/confs/algos/didarts.yaml/0
{ "file_path": "archai/confs/algos/didarts.yaml", "repo_id": "archai", "token_count": 268 }
325
__include__: './dataroot.yaml' # default dataset settings are for cifar dataset: name: 'person_coco_cut_paste' n_classes: 2 channels: 3 # number of channels in image max_batches: -1 # if >= 0 then only these many batches are generated (useful for debugging) storage_name: 'train_cut_paste_256' # name of folder or tar file to copy from cloud storage person_coco_256 train_cut_paste_256 train_cut_paste_clutter_256
archai/confs/datasets/person_coco_cut_paste.yaml/0
{ "file_path": "archai/confs/datasets/person_coco_cut_paste.yaml", "repo_id": "archai", "token_count": 139 }
326
Azure ===== The notebooks in this section show how to use Azure to run some different neural architecture searches. The Quickstart runs a simple cpu only search in an Azure VM using .. toctree:: :maxdepth: 2 Quickstart <notebooks/quickstart/quickstart.ipynb> Text Generation <notebooks/text_generation/text_generation.ipynb> Multi node search <notebooks/multi_node_search/multi_node_search.ipynb>
archai/docs/advanced_guide/cloud/azure/notebooks.rst/0
{ "file_path": "archai/docs/advanced_guide/cloud/azure/notebooks.rst", "repo_id": "archai", "token_count": 122 }
327
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from torch import nn import torch import pytorch_lightning as pl from torchmetrics import Accuracy from archai.discrete_search.search_spaces.config import ArchConfig class MyModel(pl.LightningModule): """ This is a simple CNN model that can learn how to do MNIST classification. It is parametrized by a given ArchConfig that defines number of layers, the convolution kernel size, and the number of features. """ def __init__(self, arch_config: ArchConfig, lr: float = 1e-4): super().__init__() self.lr = lr self.cross_entropy_loss = nn.CrossEntropyLoss() self.nb_layers = arch_config.pick('nb_layers') self.kernel_size = arch_config.pick('kernel_size') self.hidden_dim = arch_config.pick('hidden_dim') layer_list = [] for i in range(self.nb_layers): in_ch = (1 if i == 0 else self.hidden_dim) layer_list += [ nn.Conv2d(in_ch, self.hidden_dim, kernel_size=self.kernel_size, padding=(self.kernel_size-1)//2), nn.BatchNorm2d(self.hidden_dim), nn.ReLU(), ] layer_list += [ nn.AdaptiveAvgPool2d(output_size=(1, 1)), nn.Conv2d(self.hidden_dim, 10, kernel_size=1) ] self.model = nn.Sequential(*layer_list) def forward(self, x): return self.model(x).squeeze() def get_archid(self): return f'({self.nb_layers}, {self.kernel_size}, {self.hidden_dim})' def export_onnx(self, input_shape, path): # add batch and channel dimensions shape = [1, 1] + list(input_shape) dummy_input = torch.randn(shape, device="cpu") torch.onnx.export(self.model, dummy_input, path, input_names=['input'], output_names=['output']) def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.lr) def training_step(self, train_batch, batch_idx): x, y = train_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) self.log('train_loss', loss) return loss def validation_step(self, val_batch, batch_idx): x, y = val_batch device = x.device logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) accuracy = Accuracy(task="multiclass", num_classes=10).to(device) acc = accuracy(logits, y) self.log('accuracy', acc) return loss @staticmethod def from_archid(model_id): nb_layers, kernel_size, hidden_dim = eval(model_id) return MyModel(ArchConfig({ "nb_layers": nb_layers, "kernel_size": kernel_size, "hidden_dim": hidden_dim }))
archai/docs/advanced_guide/cloud/azure/notebooks/multi_node_search/scripts/model.py/0
{ "file_path": "archai/docs/advanced_guide/cloud/azure/notebooks/multi_node_search/scripts/model.py", "repo_id": "archai", "token_count": 1295 }
328
:root { --primary: #623eb2; --secondary: #8776ae; } li > a { color: #5a5a5a !important; } a, a.current, p.prev-next-title { color: var(--primary) !important; } a:hover { color: var(--secondary) !important; } a.nav-link.active { border-left: 2px solid var(--primary) !important; } a.navbar-brand > img { max-width: 85% !important; } .tab-set > input:checked + label { color: var(--primary) !important; border-color: var(--primary) !important; } .tab-set > label:hover { color: var(--primary) !important; } .tab-content { width: 100% !important; } div.output_area.rendered_html.docutils.container > div > table { width: auto !important; }
archai/docs/assets/css/custom.css/0
{ "file_path": "archai/docs/assets/css/custom.css", "repo_id": "archai", "token_count": 287 }
329
API === .. toctree:: :maxdepth: 2 Dataset Provider <api/dataset_provider.ipynb> Trainer (Base) <api/trainer_base.ipynb>
archai/docs/getting_started/notebooks/api.rst/0
{ "file_path": "archai/docs/getting_started/notebooks/api.rst", "repo_id": "archai", "token_count": 59 }
330
API === The API reference for Archai provides detailed information about the software's application programming interface (API), including a complete list of available functions and methods, their arguments and return values, and examples of how to use them. This section of the documentation is intended for developers and researchers who want to use Archai as a building block for their own projects, and who need a detailed understanding of the software's capabilities and functionality. .. toctree:: :maxdepth: 2 api/archai.api api/archai.common api/archai.datasets api/archai.discrete_search api/archai.onnx api/archai.quantization api/archai.supergraph api/archai.trainers
archai/docs/reference/api.rst/0
{ "file_path": "archai/docs/reference/api.rst", "repo_id": "archai", "token_count": 188 }
331
Benchmark ========= NATS-Bench ---------- .. automodule:: archai.discrete_search.search_spaces.benchmark.natsbench_tss :members: :undoc-members:
archai/docs/reference/api/archai.discrete_search.search_spaces.benchmark.rst/0
{ "file_path": "archai/docs/reference/api/archai.discrete_search.search_spaces.benchmark.rst", "repo_id": "archai", "token_count": 58 }
332
DivNAS ====== Activations Analyser -------------------- .. automodule:: archai.supergraph.algos.divnas.analyse_activations :members: :undoc-members: Cell ---- .. automodule:: archai.supergraph.algos.divnas.divnas_cell :members: :undoc-members: Experiment Runner ----------------- .. automodule:: archai.supergraph.algos.divnas.divnas_exp_runner :members: :undoc-members: Finalizers ---------- .. automodule:: archai.supergraph.algos.divnas.divnas_finalizers :members: :undoc-members: Model Description Builder ------------------------- .. automodule:: archai.supergraph.algos.divnas.divnas_model_desc_builder :members: :undoc-members: Rank Finalizer -------------- .. automodule:: archai.supergraph.algos.divnas.divnas_rank_finalizer :members: :undoc-members: Div-Based Operators ------------------- .. automodule:: archai.supergraph.algos.divnas.divop :members: :undoc-members: Sequential Operators -------------------- .. automodule:: archai.supergraph.algos.divnas.seqopt :members: :undoc-members: Randomized Weighted Majority ---------------------------- .. automodule:: archai.supergraph.algos.divnas.wmr :members: :undoc-members:
archai/docs/reference/api/archai.supergraph.algos.divnas.rst/0
{ "file_path": "archai/docs/reference/api/archai.supergraph.algos.divnas.rst", "repo_id": "archai", "token_count": 423 }
333
Natural Language Processing =========================== DeepSpeed --------- Trainer ^^^^^^^ .. automodule:: archai.trainers.nlp.ds_trainer :members: :undoc-members: Training Arguments ^^^^^^^^^^^^^^^^^^ .. automodule:: archai.trainers.nlp.ds_training_args :members: :undoc-members: Hugging Face ------------ Callbacks ^^^^^^^^^ .. automodule:: archai.trainers.nlp.hf_callbacks :members: :undoc-members: Trainer ^^^^^^^ .. automodule:: archai.trainers.nlp.hf_trainer :members: :undoc-members: Training Arguments ^^^^^^^^^^^^^^^^^^ .. automodule:: archai.trainers.nlp.hf_training_args :members: :undoc-members: NVIDIA ------ Trainer ^^^^^^^ .. automodule:: archai.trainers.nlp.nvidia_trainer :members: :undoc-members: Training Arguments ^^^^^^^^^^^^^^^^^^ .. automodule:: archai.trainers.nlp.nvidia_training_args :members: :undoc-members:
archai/docs/reference/api/archai.trainers.nlp.rst/0
{ "file_path": "archai/docs/reference/api/archai.trainers.nlp.rst", "repo_id": "archai", "token_count": 344 }
334
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from typing import Any, Dict, List, Optional from datasets.arrow_dataset import Dataset from datasets.download import DownloadMode from evaluate import load from lm_eval.base import Task from lm_eval.metrics import mean from lm_eval_harness.utils.request_factory import Request, rf # Allow code evaluation os.environ["HF_ALLOW_CODE_EVAL"] = "1" class HumanEval(Task): VERSION = 0 DATASET_PATH = "openai_humaneval" DATASET_NAME = "openai_humaneval" def __init__( self, data_dir: Optional[str] = None, cache_dir: Optional[str] = None, download_mode: Optional[DownloadMode] = None, stop_tokens: Optional[List[str]] = None, n_samples: Optional[int] = 1, temperature: Optional[float] = 0.01, top_p: Optional[float] = 0.95, max_new_tokens: Optional[int] = 300, pass_at_k: Optional[List[int]] = None, ) -> None: super().__init__(data_dir=data_dir, cache_dir=cache_dir, download_mode=download_mode) self.stop_tokens = stop_tokens or ["\nclass", "\ndef", "\n#", "\nif", "\nprint"] self.n_samples = n_samples self.temperature = temperature self.top_p = top_p self.max_new_tokens = max_new_tokens self.pass_at_k = pass_at_k or [1] def should_decontaminate(self) -> bool: return False def has_training_docs(self) -> bool: return False def has_validation_docs(self) -> bool: return False def has_test_docs(self) -> bool: return True def test_docs(self) -> Dataset: return self.dataset["test"] def doc_to_text(self, doc: Dict[str, Any]) -> str: return doc["prompt"] def doc_to_target(self, doc: Dict[str, Any]) -> str: return "\n" + doc["canonical_solution"] def construct_requests(self, doc: Dict[str, Any], ctx: str) -> List[Request]: return [ rf.generate( ctx, self.stop_tokens, True, self.temperature, self.top_p, self.max_new_tokens, ) for _ in range(self.n_samples) ] def process_results(self, doc: Dict[str, Any], results: List[str]) -> Dict[str, Any]: test_case = doc["test"] entry_point = f"check({doc['entry_point']})" prediction = [list(results)] reference = [f"{test_case}\n{entry_point}"] metric = load("code_eval") metric.add_batch(predictions=prediction, references=reference) pass_at_k = metric.compute(k=self.pass_at_k)[0] return {k: v for k, v in pass_at_k.items()} def aggregation(self) -> Dict[str, Any]: return {f"pass@{k}": mean for k in self.pass_at_k} def higher_is_better(self) -> Dict[str, Any]: return {f"pass@{k}": True for k in self.pass_at_k}
archai/research/lm_eval_harness/lm_eval_harness/tasks/human_eval.py/0
{ "file_path": "archai/research/lm_eval_harness/lm_eval_harness/tasks/human_eval.py", "repo_id": "archai", "token_count": 1346 }
335
# Policy found on CIFAR-10 and CIFAR-100 from __future__ import absolute_import, division, print_function from collections import defaultdict from archai.supergraph.datasets.augmentation import augment_list, get_augment def arsaug_policy(): exp0_0 = [ [("Solarize", 0.66, 0.34), ("Equalize", 0.56, 0.61)], [("Equalize", 0.43, 0.06), ("AutoContrast", 0.66, 0.08)], [("Color", 0.72, 0.47), ("Contrast", 0.88, 0.86)], [("Brightness", 0.84, 0.71), ("Color", 0.31, 0.74)], [("Rotate", 0.68, 0.26), ("TranslateX", 0.38, 0.88)], ] exp0_1 = [ [("TranslateY", 0.88, 0.96), ("TranslateY", 0.53, 0.79)], [("AutoContrast", 0.44, 0.36), ("Solarize", 0.22, 0.48)], [("AutoContrast", 0.93, 0.32), ("Solarize", 0.85, 0.26)], [("Solarize", 0.55, 0.38), ("Equalize", 0.43, 0.48)], [("TranslateY", 0.72, 0.93), ("AutoContrast", 0.83, 0.95)], ] exp0_2 = [ [("Solarize", 0.43, 0.58), ("AutoContrast", 0.82, 0.26)], [("TranslateY", 0.71, 0.79), ("AutoContrast", 0.81, 0.94)], [("AutoContrast", 0.92, 0.18), ("TranslateY", 0.77, 0.85)], [("Equalize", 0.71, 0.69), ("Color", 0.23, 0.33)], [("Sharpness", 0.36, 0.98), ("Brightness", 0.72, 0.78)], ] exp0_3 = [ [("Equalize", 0.74, 0.49), ("TranslateY", 0.86, 0.91)], [("TranslateY", 0.82, 0.91), ("TranslateY", 0.96, 0.79)], [("AutoContrast", 0.53, 0.37), ("Solarize", 0.39, 0.47)], [("TranslateY", 0.22, 0.78), ("Color", 0.91, 0.65)], [("Brightness", 0.82, 0.46), ("Color", 0.23, 0.91)], ] exp0_4 = [ [("Cutout", 0.27, 0.45), ("Equalize", 0.37, 0.21)], [("Color", 0.43, 0.23), ("Brightness", 0.65, 0.71)], [("ShearX", 0.49, 0.31), ("AutoContrast", 0.92, 0.28)], [("Equalize", 0.62, 0.59), ("Equalize", 0.38, 0.91)], [("Solarize", 0.57, 0.31), ("Equalize", 0.61, 0.51)], ] exp0_5 = [ [("TranslateY", 0.29, 0.35), ("Sharpness", 0.31, 0.64)], [("Color", 0.73, 0.77), ("TranslateX", 0.65, 0.76)], [("ShearY", 0.29, 0.74), ("Posterize", 0.42, 0.58)], [("Color", 0.92, 0.79), ("Equalize", 0.68, 0.54)], [("Sharpness", 0.87, 0.91), ("Sharpness", 0.93, 0.41)], ] exp0_6 = [ [("Solarize", 0.39, 0.35), ("Color", 0.31, 0.44)], [("Color", 0.33, 0.77), ("Color", 0.25, 0.46)], [("ShearY", 0.29, 0.74), ("Posterize", 0.42, 0.58)], [("AutoContrast", 0.32, 0.79), ("Cutout", 0.68, 0.34)], [("AutoContrast", 0.67, 0.91), ("AutoContrast", 0.73, 0.83)], ] return exp0_0 + exp0_1 + exp0_2 + exp0_3 + exp0_4 + exp0_5 + exp0_6 def autoaug2arsaug(f): def autoaug(): mapper = defaultdict(lambda: lambda x: x) mapper.update( { "ShearX": lambda x: float_parameter(x, 0.3), "ShearY": lambda x: float_parameter(x, 0.3), "TranslateX": lambda x: int_parameter(x, 10), "TranslateY": lambda x: int_parameter(x, 10), "Rotate": lambda x: int_parameter(x, 30), "Solarize": lambda x: 256 - int_parameter(x, 256), "Posterize2": lambda x: 4 - int_parameter(x, 4), "Contrast": lambda x: float_parameter(x, 1.8) + 0.1, "Color": lambda x: float_parameter(x, 1.8) + 0.1, "Brightness": lambda x: float_parameter(x, 1.8) + 0.1, "Sharpness": lambda x: float_parameter(x, 1.8) + 0.1, "CutoutAbs": lambda x: int_parameter(x, 20), } ) def low_high(name, prev_value): _, low, high = get_augment(name) return float(prev_value - low) / (high - low) policies = f() new_policies = [] for policy in policies: new_policies.append([(name, pr, low_high(name, mapper[name](level))) for name, pr, level in policy]) return new_policies return autoaug @autoaug2arsaug def autoaug_paper_cifar10(): return [ [("Invert", 0.1, 7), ("Contrast", 0.2, 6)], [("Rotate", 0.7, 2), ("TranslateXAbs", 0.3, 9)], [("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)], [("ShearY", 0.5, 8), ("TranslateYAbs", 0.7, 9)], [("AutoContrast", 0.5, 8), ("Equalize", 0.9, 2)], [("ShearY", 0.2, 7), ("Posterize2", 0.3, 7)], [("Color", 0.4, 3), ("Brightness", 0.6, 7)], [("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)], [("Equalize", 0.6, 5), ("Equalize", 0.5, 1)], [("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)], [("Color", 0.7, 7), ("TranslateXAbs", 0.5, 8)], [("Equalize", 0.3, 7), ("AutoContrast", 0.4, 8)], [("TranslateYAbs", 0.4, 3), ("Sharpness", 0.2, 6)], [("Brightness", 0.9, 6), ("Color", 0.2, 8)], [("Solarize", 0.5, 2), ("Invert", 0.0, 3)], [("Equalize", 0.2, 0), ("AutoContrast", 0.6, 0)], [("Equalize", 0.2, 8), ("Equalize", 0.6, 4)], [("Color", 0.9, 9), ("Equalize", 0.6, 6)], [("AutoContrast", 0.8, 4), ("Solarize", 0.2, 8)], [("Brightness", 0.1, 3), ("Color", 0.7, 0)], [("Solarize", 0.4, 5), ("AutoContrast", 0.9, 3)], [("TranslateYAbs", 0.9, 9), ("TranslateYAbs", 0.7, 9)], [("AutoContrast", 0.9, 2), ("Solarize", 0.8, 3)], [("Equalize", 0.8, 8), ("Invert", 0.1, 3)], [("TranslateYAbs", 0.7, 9), ("AutoContrast", 0.9, 1)], ] @autoaug2arsaug def autoaug_policy(): """AutoAugment policies found on Cifar.""" exp0_0 = [ [("Invert", 0.1, 7), ("Contrast", 0.2, 6)], [("Rotate", 0.7, 2), ("TranslateXAbs", 0.3, 9)], [("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)], [("ShearY", 0.5, 8), ("TranslateYAbs", 0.7, 9)], [("AutoContrast", 0.5, 8), ("Equalize", 0.9, 2)], ] exp0_1 = [ [("Solarize", 0.4, 5), ("AutoContrast", 0.9, 3)], [("TranslateYAbs", 0.9, 9), ("TranslateYAbs", 0.7, 9)], [("AutoContrast", 0.9, 2), ("Solarize", 0.8, 3)], [("Equalize", 0.8, 8), ("Invert", 0.1, 3)], [("TranslateYAbs", 0.7, 9), ("AutoContrast", 0.9, 1)], ] exp0_2 = [ [("Solarize", 0.4, 5), ("AutoContrast", 0.0, 2)], [("TranslateYAbs", 0.7, 9), ("TranslateYAbs", 0.7, 9)], [("AutoContrast", 0.9, 0), ("Solarize", 0.4, 3)], [("Equalize", 0.7, 5), ("Invert", 0.1, 3)], [("TranslateYAbs", 0.7, 9), ("TranslateYAbs", 0.7, 9)], ] exp0_3 = [ [("Solarize", 0.4, 5), ("AutoContrast", 0.9, 1)], [("TranslateYAbs", 0.8, 9), ("TranslateYAbs", 0.9, 9)], [("AutoContrast", 0.8, 0), ("TranslateYAbs", 0.7, 9)], [("TranslateYAbs", 0.2, 7), ("Color", 0.9, 6)], [("Equalize", 0.7, 6), ("Color", 0.4, 9)], ] exp1_0 = [ [("ShearY", 0.2, 7), ("Posterize2", 0.3, 7)], [("Color", 0.4, 3), ("Brightness", 0.6, 7)], [("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)], [("Equalize", 0.6, 5), ("Equalize", 0.5, 1)], [("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)], ] exp1_1 = [ [("Brightness", 0.3, 7), ("AutoContrast", 0.5, 8)], [("AutoContrast", 0.9, 4), ("AutoContrast", 0.5, 6)], [("Solarize", 0.3, 5), ("Equalize", 0.6, 5)], [("TranslateYAbs", 0.2, 4), ("Sharpness", 0.3, 3)], [("Brightness", 0.0, 8), ("Color", 0.8, 8)], ] exp1_2 = [ [("Solarize", 0.2, 6), ("Color", 0.8, 6)], [("Solarize", 0.2, 6), ("AutoContrast", 0.8, 1)], [("Solarize", 0.4, 1), ("Equalize", 0.6, 5)], [("Brightness", 0.0, 0), ("Solarize", 0.5, 2)], [("AutoContrast", 0.9, 5), ("Brightness", 0.5, 3)], ] exp1_3 = [ [("Contrast", 0.7, 5), ("Brightness", 0.0, 2)], [("Solarize", 0.2, 8), ("Solarize", 0.1, 5)], [("Contrast", 0.5, 1), ("TranslateYAbs", 0.2, 9)], [("AutoContrast", 0.6, 5), ("TranslateYAbs", 0.0, 9)], [("AutoContrast", 0.9, 4), ("Equalize", 0.8, 4)], ] exp1_4 = [ [("Brightness", 0.0, 7), ("Equalize", 0.4, 7)], [("Solarize", 0.2, 5), ("Equalize", 0.7, 5)], [("Equalize", 0.6, 8), ("Color", 0.6, 2)], [("Color", 0.3, 7), ("Color", 0.2, 4)], [("AutoContrast", 0.5, 2), ("Solarize", 0.7, 2)], ] exp1_5 = [ [("AutoContrast", 0.2, 0), ("Equalize", 0.1, 0)], [("ShearY", 0.6, 5), ("Equalize", 0.6, 5)], [("Brightness", 0.9, 3), ("AutoContrast", 0.4, 1)], [("Equalize", 0.8, 8), ("Equalize", 0.7, 7)], [("Equalize", 0.7, 7), ("Solarize", 0.5, 0)], ] exp1_6 = [ [("Equalize", 0.8, 4), ("TranslateYAbs", 0.8, 9)], [("TranslateYAbs", 0.8, 9), ("TranslateYAbs", 0.6, 9)], [("TranslateYAbs", 0.9, 0), ("TranslateYAbs", 0.5, 9)], [("AutoContrast", 0.5, 3), ("Solarize", 0.3, 4)], [("Solarize", 0.5, 3), ("Equalize", 0.4, 4)], ] exp2_0 = [ [("Color", 0.7, 7), ("TranslateXAbs", 0.5, 8)], [("Equalize", 0.3, 7), ("AutoContrast", 0.4, 8)], [("TranslateYAbs", 0.4, 3), ("Sharpness", 0.2, 6)], [("Brightness", 0.9, 6), ("Color", 0.2, 8)], [("Solarize", 0.5, 2), ("Invert", 0.0, 3)], ] exp2_1 = [ [("AutoContrast", 0.1, 5), ("Brightness", 0.0, 0)], [("CutoutAbs", 0.2, 4), ("Equalize", 0.1, 1)], [("Equalize", 0.7, 7), ("AutoContrast", 0.6, 4)], [("Color", 0.1, 8), ("ShearY", 0.2, 3)], [("ShearY", 0.4, 2), ("Rotate", 0.7, 0)], ] exp2_2 = [ [("ShearY", 0.1, 3), ("AutoContrast", 0.9, 5)], [("TranslateYAbs", 0.3, 6), ("CutoutAbs", 0.3, 3)], [("Equalize", 0.5, 0), ("Solarize", 0.6, 6)], [("AutoContrast", 0.3, 5), ("Rotate", 0.2, 7)], [("Equalize", 0.8, 2), ("Invert", 0.4, 0)], ] exp2_3 = [ [("Equalize", 0.9, 5), ("Color", 0.7, 0)], [("Equalize", 0.1, 1), ("ShearY", 0.1, 3)], [("AutoContrast", 0.7, 3), ("Equalize", 0.7, 0)], [("Brightness", 0.5, 1), ("Contrast", 0.1, 7)], [("Contrast", 0.1, 4), ("Solarize", 0.6, 5)], ] exp2_4 = [ [("Solarize", 0.2, 3), ("ShearX", 0.0, 0)], [("TranslateXAbs", 0.3, 0), ("TranslateXAbs", 0.6, 0)], [("Equalize", 0.5, 9), ("TranslateYAbs", 0.6, 7)], [("ShearX", 0.1, 0), ("Sharpness", 0.5, 1)], [("Equalize", 0.8, 6), ("Invert", 0.3, 6)], ] exp2_5 = [ [("AutoContrast", 0.3, 9), ("CutoutAbs", 0.5, 3)], [("ShearX", 0.4, 4), ("AutoContrast", 0.9, 2)], [("ShearX", 0.0, 3), ("Posterize2", 0.0, 3)], [("Solarize", 0.4, 3), ("Color", 0.2, 4)], [("Equalize", 0.1, 4), ("Equalize", 0.7, 6)], ] exp2_6 = [ [("Equalize", 0.3, 8), ("AutoContrast", 0.4, 3)], [("Solarize", 0.6, 4), ("AutoContrast", 0.7, 6)], [("AutoContrast", 0.2, 9), ("Brightness", 0.4, 8)], [("Equalize", 0.1, 0), ("Equalize", 0.0, 6)], [("Equalize", 0.8, 4), ("Equalize", 0.0, 4)], ] exp2_7 = [ [("Equalize", 0.5, 5), ("AutoContrast", 0.1, 2)], [("Solarize", 0.5, 5), ("AutoContrast", 0.9, 5)], [("AutoContrast", 0.6, 1), ("AutoContrast", 0.7, 8)], [("Equalize", 0.2, 0), ("AutoContrast", 0.1, 2)], [("Equalize", 0.6, 9), ("Equalize", 0.4, 4)], ] exp0s = exp0_0 + exp0_1 + exp0_2 + exp0_3 exp1s = exp1_0 + exp1_1 + exp1_2 + exp1_3 + exp1_4 + exp1_5 + exp1_6 exp2s = exp2_0 + exp2_1 + exp2_2 + exp2_3 + exp2_4 + exp2_5 + exp2_6 + exp2_7 return exp0s + exp1s + exp2s PARAMETER_MAX = 10 def float_parameter(level, maxval): return float(level) * maxval / PARAMETER_MAX def int_parameter(level, maxval): return int(float_parameter(level, maxval)) def no_duplicates(f): def wrap_remove_duplicates(): policies = f() return remove_deplicates(policies) return wrap_remove_duplicates def remove_deplicates(policies): s = set() new_policies = [] for ops in policies: key = [] for op in ops: key.append(op[0]) key = "_".join(key) if key in s: continue else: s.add(key) new_policies.append(ops) return new_policies def fa_reduced_cifar10(): p = [ [["Contrast", 0.8320659688593578, 0.49884310562180767], ["TranslateX", 0.41849883971249136, 0.394023086494538]], [["Color", 0.3500483749890918, 0.43355143929883955], ["Color", 0.5120716140300229, 0.7508299643325016]], [["Rotate", 0.9447932604389472, 0.29723465088990375], ["Sharpness", 0.1564936149799504, 0.47169309978091745]], [["Rotate", 0.5430015349185097, 0.6518626678905443], ["Color", 0.5694844928020679, 0.3494533005430269]], [ ["AutoContrast", 0.5558922032451064, 0.783136004977799], ["TranslateY", 0.683914191471972, 0.7597025305860181], ], [ ["TranslateX", 0.03489224481658926, 0.021025488042663354], ["Equalize", 0.4788637403857401, 0.3535481281496117], ], [ ["Sharpness", 0.6428916269794158, 0.22791511918580576], ["Contrast", 0.016014045073950323, 0.26811312269487575], ], [["Rotate", 0.2972727228410451, 0.7654251516829896], ["AutoContrast", 0.16005809254943348, 0.5380523650108116]], [["Contrast", 0.5823671057717301, 0.7521166301398389], ["TranslateY", 0.9949449214751978, 0.9612671341689751]], [["Equalize", 0.8372126687702321, 0.6944127225621206], ["Rotate", 0.25393282929784755, 0.3261658365286546]], [["Invert", 0.8222011603194572, 0.6597915864008403], ["Posterize", 0.31858707654447327, 0.9541013715579584]], [["Sharpness", 0.41314621282107045, 0.9437344470879956], ["Cutout", 0.6610495837889337, 0.674411664255093]], [["Contrast", 0.780121736705407, 0.40826152397463156], ["Color", 0.344019192125256, 0.1942922781355767]], [["Rotate", 0.17153139555621344, 0.798745732456474], ["Invert", 0.6010555860501262, 0.320742172554767]], [["Invert", 0.26816063450777416, 0.27152062163148327], ["Equalize", 0.6786829200236982, 0.7469412443514213]], [["Contrast", 0.3920564414367518, 0.7493644582838497], ["TranslateY", 0.8941657805606704, 0.6580846856375955]], [["Equalize", 0.875509207399372, 0.9061130537645283], ["Cutout", 0.4940280679087308, 0.7896229623628276]], [["Contrast", 0.3331423298065147, 0.7170041362529597], ["ShearX", 0.7425484291842793, 0.5285117152426109]], [["Equalize", 0.97344237365026, 0.4745759720473106], ["TranslateY", 0.055863458430295276, 0.9625142022954672]], [ ["TranslateX", 0.6810614083109192, 0.7509937355495521], ["TranslateY", 0.3866463019475701, 0.5185481505576112], ], [["Sharpness", 0.4751529944753671, 0.550464012488733], ["Cutout", 0.9472914750534814, 0.5584925992985023]], [["Contrast", 0.054606784909375095, 0.17257080196712182], ["Cutout", 0.6077026782754803, 0.7996504165944938]], [["ShearX", 0.328798428243695, 0.2769563264079157], ["Cutout", 0.9037632437023772, 0.4915809476763595]], [["Cutout", 0.6891202672363478, 0.9951490996172914], ["Posterize", 0.06532762462628705, 0.4005246609075227]], [["TranslateY", 0.6908583592523334, 0.725612120376128], ["Rotate", 0.39907735501746666, 0.36505798032223147]], [["TranslateX", 0.10398364107399072, 0.5913918470536627], ["Rotate", 0.7169811539340365, 0.8283850670648724]], [["ShearY", 0.9526373530768361, 0.4482347365639251], ["Contrast", 0.4203947336351471, 0.41526799558953864]], [["Contrast", 0.24894431199700073, 0.09578870500994707], ["Solarize", 0.2273713345927395, 0.6214942914963707]], [["TranslateX", 0.06331228870032912, 0.8961907489444944], ["Cutout", 0.5110007859958743, 0.23704875994050723]], [["Cutout", 0.3769183548846172, 0.6560944580253987], ["TranslateY", 0.7201924599434143, 0.4132476526938319]], [["Invert", 0.6707431156338866, 0.11622795952464149], ["Posterize", 0.12075972752370845, 0.18024933294172307]], [["Color", 0.5010057264087142, 0.5277767327434318], ["Rotate", 0.9486115946366559, 0.31485546630220784]], [["ShearX", 0.31741302466630406, 0.1991215806270692], ["Invert", 0.3744727015523084, 0.6914113986757578]], [ ["Brightness", 0.40348479064392617, 0.8924182735724888], ["Brightness", 0.1973098763857779, 0.3939288933689655], ], [["Color", 0.01208688664030888, 0.6055693000885217], ["Equalize", 0.433259451147881, 0.420711137966155]], [["Cutout", 0.2620018360076487, 0.11594468278143644], ["Rotate", 0.1310401567856766, 0.7244318146544101]], [["ShearX", 0.15249651845933576, 0.35277277071866986], ["Contrast", 0.28221794032094016, 0.42036586509397444]], [["Brightness", 0.8492912150468908, 0.26386920887886056], ["Solarize", 0.8764208056263386, 0.1258195122766067]], [["ShearX", 0.8537058239675831, 0.8415101816171269], ["AutoContrast", 0.23958568830416294, 0.9889049529564014]], [["Rotate", 0.6463207930684552, 0.8750192129056532], ["Contrast", 0.6865032211768652, 0.8564981333033417]], [ ["Equalize", 0.8877190311811044, 0.7370995897848609], ["TranslateX", 0.9979660314391368, 0.005683998913244781], ], [["Color", 0.6420017551677819, 0.6225337265571229], ["Solarize", 0.8344504978566362, 0.8332856969941151]], [["ShearX", 0.7439332981992567, 0.9747608698582039], ["Equalize", 0.6259189804002959, 0.028017478098245174]], [["TranslateY", 0.39794770293366843, 0.8482966537902709], ["Rotate", 0.9312935630405351, 0.5300586925826072]], [["Cutout", 0.8904075572021911, 0.3522934742068766], ["Equalize", 0.6431186289473937, 0.9930577962126151]], [["Contrast", 0.9183553386089476, 0.44974266209396685], ["TranslateY", 0.8193684583123862, 0.9633741156526566]], [["ShearY", 0.616078299924283, 0.19219314358924766], ["Solarize", 0.1480945914138868, 0.05922109541654652]], [["Solarize", 0.25332455064128157, 0.18853037431947994], ["ShearY", 0.9518390093954243, 0.14603930044061142]], [["Color", 0.8094378664335412, 0.37029830225408433], ["Contrast", 0.29504113617467465, 0.065096365468442]], [ ["AutoContrast", 0.7075167558685455, 0.7084621693458267], ["Sharpness", 0.03555539453323875, 0.5651948313888351], ], [["TranslateY", 0.5969982600930229, 0.9857264201029572], ["Rotate", 0.9898628564873607, 0.1985685534926911]], [["Invert", 0.14915939942810352, 0.6595839632446547], ["Posterize", 0.768535289994361, 0.5997358684618563]], [["Equalize", 0.9162691815967111, 0.3331035307653627], ["Color", 0.8169118187605557, 0.7653910258006366]], [["Rotate", 0.43489185299530897, 0.752215269135173], ["Brightness", 0.1569828560334806, 0.8002808712857853]], [["Invert", 0.931876215328345, 0.029428644395760872], ["Equalize", 0.6330036052674145, 0.7235531014288485]], [["ShearX", 0.5216138393704968, 0.849272958911589], ["AutoContrast", 0.19572688655120263, 0.9786551568639575]], [["ShearX", 0.9899586208275011, 0.22580547500610293], ["Brightness", 0.9831311903178727, 0.5055159610855606]], [ ["Brightness", 0.29179117009211486, 0.48003584672937294], ["Solarize", 0.7544252317330058, 0.05806581735063043], ], [ ["AutoContrast", 0.8919800329537786, 0.8511261613698553], ["Contrast", 0.49199446084551035, 0.7302297140181429], ], [ ["Cutout", 0.7079723710644835, 0.032565015538375874], ["AutoContrast", 0.8259782090388609, 0.7860708789468442], ], [["Posterize", 0.9980262659801914, 0.6725084224935673], ["ShearY", 0.6195568269664682, 0.5444170291816751]], [["Posterize", 0.8687351834713217, 0.9978004914422602], ["Equalize", 0.4532646848325955, 0.6486748015710573]], [["Contrast", 0.2713928776950594, 0.15255249557027806], ["ShearY", 0.9276834387970199, 0.5266542862333478]], [ ["AutoContrast", 0.5240786618055582, 0.9325642258930253], ["Cutout", 0.38448627892037357, 0.21219415055662394], ], [ ["TranslateX", 0.4299517937295352, 0.20133751201386152], ["TranslateX", 0.6753468310276597, 0.6985621035400441], ], [["Rotate", 0.4006472499103597, 0.6704748473357586], ["Equalize", 0.674161668148079, 0.6528530101705237]], [["Equalize", 0.9139902833674455, 0.9015103149680278], ["Sharpness", 0.7289667720691948, 0.7623606352376232]], [["Cutout", 0.5911267429414259, 0.5953141187177585], ["Rotate", 0.5219064817468504, 0.11085141355857986]], [["TranslateX", 0.3620095133946267, 0.26194039409492476], ["Rotate", 0.3929841359545597, 0.4913406720338047]], [["Invert", 0.5175298901458896, 0.001661410821811482], ["Invert", 0.004656581318332242, 0.8157622192213624]], [ ["AutoContrast", 0.013609693335051465, 0.9318651749409604], ["Invert", 0.8980844358979592, 0.2268511862780368], ], [["ShearY", 0.7717126261142194, 0.09975547983707711], ["Equalize", 0.7808494401429572, 0.4141412091009955]], [ ["TranslateX", 0.5878675721341552, 0.29813268038163376], ["Posterize", 0.21257276051591356, 0.2837285296666412], ], [["Brightness", 0.4268335108566488, 0.4723784991635417], ["Cutout", 0.9386262901570471, 0.6597686851494288]], [["ShearX", 0.8259423807590159, 0.6215304795389204], ["Invert", 0.6663365779667443, 0.7729669184580387]], [["ShearY", 0.4801338723951297, 0.5220145420100984], ["Solarize", 0.9165803796596582, 0.04299335502862134]], [["Color", 0.17621114853558817, 0.7092601754635434], ["ShearX", 0.9014406936728542, 0.6028711944367818]], [["Rotate", 0.13073284972300658, 0.9088831512880851], ["ShearX", 0.4228105332316806, 0.7985249783662675]], [["Brightness", 0.9182753692730031, 0.0063635477774044436], ["Color", 0.4279825602663798, 0.28727149118585327]], [["Equalize", 0.578218285372267, 0.9611758542158054], ["Contrast", 0.5471552264150691, 0.8819635504027596]], [["Brightness", 0.3208589067274543, 0.45324733565167497], ["Solarize", 0.5218455808633233, 0.5946097503647126]], [["Equalize", 0.3790381278653, 0.8796082535775276], ["Solarize", 0.4875526773149246, 0.5186585878052613]], [["ShearY", 0.12026461479557571, 0.1336953429068397], ["Posterize", 0.34373988646025766, 0.8557727670803785]], [["Cutout", 0.2396745247507467, 0.8123036135209865], ["Equalize", 0.05022807681008945, 0.6648492261984383]], [["Brightness", 0.35226676470748264, 0.5950011514888855], ["Rotate", 0.27555076067000894, 0.9170063321486026]], [["ShearX", 0.320224630647278, 0.9683584649071976], ["Invert", 0.6905585196648905, 0.5929115667894518]], [["Color", 0.9941395717559652, 0.7474441679798101], ["Sharpness", 0.7559998478658021, 0.6656052889626682]], [["ShearY", 0.4004220568345669, 0.5737646992826074], ["Equalize", 0.9983495213746147, 0.8307907033362303]], [["Color", 0.13726809242038207, 0.9378850119950549], ["Equalize", 0.9853362454752445, 0.42670264496554156]], [["Invert", 0.13514636153298576, 0.13516363849081958], ["Sharpness", 0.2031189356693901, 0.6110226359872745]], [["TranslateX", 0.7360305209630797, 0.41849698571655614], ["Contrast", 0.8972161549144564, 0.7820296625565641]], [["Color", 0.02713118828682548, 0.717110684828096], ["TranslateY", 0.8118759006836348, 0.9120098002024992]], [["Sharpness", 0.2915428949403711, 0.7630303724396518], ["Solarize", 0.22030536162851078, 0.38654526772661757]], [ ["Equalize", 0.9949114839538582, 0.7193630656062793], ["AutoContrast", 0.00889496657931299, 0.2291400476524672], ], [["Rotate", 0.7120948976490488, 0.7804359309791055], ["Cutout", 0.10445418104923654, 0.8022999156052766]], [["Equalize", 0.7941710117902707, 0.8648170634288153], ["Invert", 0.9235642581144047, 0.23810725859722381]], [["Cutout", 0.3669397998623156, 0.42612815083245004], ["Solarize", 0.5896322046441561, 0.40525016166956795]], [["Color", 0.8389858785714184, 0.4805764176488667], ["Rotate", 0.7483931487048825, 0.4731174601400677]], [ ["Sharpness", 0.19006538611394763, 0.9480745790240234], ["TranslateY", 0.13904429049439282, 0.04117685330615939], ], [["TranslateY", 0.9958097661701637, 0.34853788612580905], ["Cutout", 0.2235829624082113, 0.3737887095480745]], [["ShearX", 0.635453761342424, 0.6063917273421382], ["Posterize", 0.8738297843709666, 0.4893042590265556]], [["Brightness", 0.7907245198402727, 0.7082189713070691], ["Color", 0.030313003541849737, 0.6927897798493439]], [["Cutout", 0.6965622481073525, 0.8103522907758203], ["ShearY", 0.6186794303078708, 0.28640671575703547]], [["ShearY", 0.43734910588450226, 0.32549342535621517], ["ShearX", 0.08154980987651872, 0.3286764923112455]], [["AutoContrast", 0.5262462005050853, 0.8175584582465848], ["Contrast", 0.8683217097363655, 0.548776281479276]], [["ShearY", 0.03957878500311707, 0.5102350637943197], ["Rotate", 0.13794708520303778, 0.38035687712954236]], [ ["Sharpness", 0.634288567312677, 0.6387948309075822], ["AutoContrast", 0.13437288694693272, 0.7150448869023095], ], [["Contrast", 0.5198339640088544, 0.9409429390321714], ["Cutout", 0.09489154903321972, 0.6228488803821982]], [ ["Equalize", 0.8955909061806043, 0.7727336527163008], ["AutoContrast", 0.6459479564441762, 0.7065467781139214], ], [["Invert", 0.07214420843537739, 0.15334721382249505], ["ShearX", 0.9242027778363903, 0.5809187849982554]], [["Equalize", 0.9144084379856188, 0.9457539278608998], ["Sharpness", 0.14337499858300173, 0.5978054365425495]], [["Posterize", 0.18894269796951202, 0.14676331276539045], ["Equalize", 0.846204299950047, 0.0720601838168885]], [["Contrast", 0.47354445405741163, 0.1793650330107468], ["Solarize", 0.9086106327264657, 0.7578807802091502]], [ ["AutoContrast", 0.11805466892967886, 0.6773620948318575], ["TranslateX", 0.584222568299264, 0.9475693349391936], ], [ ["Brightness", 0.5833017701352768, 0.6892593824176294], ["AutoContrast", 0.9073141314561828, 0.5823085733964589], ], [["TranslateY", 0.5711231614144834, 0.6436240447620021], ["Contrast", 0.21466964050052473, 0.8042843954486391]], [["Contrast", 0.22967904487976765, 0.2343103109298762], ["Invert", 0.5502897289159286, 0.386181060792375]], [["Invert", 0.7008423439928628, 0.4234003051405053], ["Rotate", 0.77270460187611, 0.6650852696828039]], [["Invert", 0.050618322309703534, 0.24277027926683614], ["TranslateX", 0.789703489736613, 0.5116446685339312]], [["Color", 0.363898083076868, 0.7870323584210503], ["ShearY", 0.009608425513626617, 0.6188625018465327]], [["TranslateY", 0.9447601615216088, 0.8605867115798349], ["Equalize", 0.24139180127003634, 0.9587337957930782]], [["Equalize", 0.3968589440144503, 0.626206375426996], ["Solarize", 0.3215967960673186, 0.826785464835443]], [ ["TranslateX", 0.06947339047121326, 0.016705969558222122], ["Contrast", 0.6203392406528407, 0.6433525559906872], ], [["Solarize", 0.2479835265518212, 0.6335009955617831], ["Sharpness", 0.6260191862978083, 0.18998095149428562]], [["Invert", 0.9818841924943431, 0.03252098144087934], ["TranslateY", 0.9740718042586802, 0.32038951753031475]], [ ["Solarize", 0.8795784664090814, 0.7014953994354041], ["AutoContrast", 0.8508018319577783, 0.09321935255338443], ], [["Color", 0.8067046326105318, 0.13732893832354054], ["Contrast", 0.7358549680271418, 0.7880588355974301]], [["Posterize", 0.5005885536838065, 0.7152229305267599], ["ShearX", 0.6714249591308944, 0.7732232697859908]], [ ["TranslateY", 0.5657943483353953, 0.04622399873706862], ["AutoContrast", 0.2787442688649845, 0.567024378767143], ], [["ShearY", 0.7589839214283295, 0.041071003934029404], ["Equalize", 0.3719852873722692, 0.43285778682687326]], [["Posterize", 0.8841266183653291, 0.42441306955476366], ["Cutout", 0.06578801759412933, 0.5961125797961526]], [ ["Rotate", 0.4057875004314082, 0.20241115848366442], ["AutoContrast", 0.19331542807918067, 0.7175484678480565], ], [["Contrast", 0.20331327116693088, 0.17135387852218742], ["Cutout", 0.6282459410351067, 0.6690015305529187]], [["ShearX", 0.4309850328306535, 0.99321178125828], ["AutoContrast", 0.01809604030453338, 0.693838277506365]], [["Rotate", 0.24343531125298268, 0.5326412444169899], ["Sharpness", 0.8663989992597494, 0.7643990609130789]], [["Rotate", 0.9785019204622459, 0.8941922576710696], ["ShearY", 0.3823185048761075, 0.9258854046017292]], [["ShearY", 0.5502613342963388, 0.6193478797355644], ["Sharpness", 0.2212116534610532, 0.6648232390110979]], [["TranslateY", 0.43222920981513757, 0.5657636397633089], ["ShearY", 0.9153733286073634, 0.4868521171273169]], [["Posterize", 0.12246560519738336, 0.9132288825898972], ["Cutout", 0.6058471327881816, 0.6426901876150983]], [["Color", 0.3693970222695844, 0.038929141432555436], ["Equalize", 0.6228052875653781, 0.05064436511347281]], [["Color", 0.7172600331356893, 0.2824542634766688], ["Color", 0.425293116261649, 0.1796441283313972]], [["Cutout", 0.7539608428122959, 0.9896141728228921], ["Solarize", 0.17811081117364758, 0.9064195503634402]], [ ["AutoContrast", 0.6761242607012717, 0.6484842446399923], ["AutoContrast", 0.1978135076901828, 0.42166879492601317], ], [["ShearY", 0.25901666379802524, 0.4770778270322449], ["Solarize", 0.7640963173407052, 0.7548463227094349]], [["TranslateY", 0.9222487731783499, 0.33658389819616463], ["Equalize", 0.9159112511468139, 0.8877136302394797]], [ ["TranslateX", 0.8994836977137054, 0.11036053676846591], ["Sharpness", 0.9040333410652747, 0.007266095214664592], ], [["Invert", 0.627758632524958, 0.8075245097227242], ["Color", 0.7525387912148516, 0.05950239294733184]], [ ["TranslateX", 0.43505193292761857, 0.38108822876120796], ["TranslateY", 0.7432578052364004, 0.685678116134759], ], [ ["Contrast", 0.9293507582470425, 0.052266842951356196], ["Posterize", 0.45187123977747456, 0.8228290399726782], ], [["ShearX", 0.07240786542746291, 0.8945667925365756], ["Brightness", 0.5305443506561034, 0.12025274552427578]], [["Invert", 0.40157564448143335, 0.5364745514006678], ["Posterize", 0.3316124671813876, 0.43002413237035997]], [["ShearY", 0.7152314630009072, 0.1938339083417453], ["Invert", 0.14102478508140615, 0.41047623580174253]], [ ["Equalize", 0.19862832613849246, 0.5058521685279254], ["Sharpness", 0.16481208629549782, 0.29126323102770557], ], [["Equalize", 0.6951591703541872, 0.7294822018800076], ["ShearX", 0.8726656726111219, 0.3151484225786487]], [["Rotate", 0.17234370554263745, 0.9356543193000078], ["TranslateX", 0.4954374070084091, 0.05496727345849217]], [["Contrast", 0.347405480122842, 0.831553005022885], ["ShearX", 0.28946367213071134, 0.11905898704394013]], [["Rotate", 0.28096672507990683, 0.16181284050307398], ["Color", 0.6554918515385365, 0.8739728050797386]], [ ["Solarize", 0.05408073374114053, 0.5357087283758337], ["Posterize", 0.42457175211495335, 0.051807130609045515], ], [["TranslateY", 0.6216669362331361, 0.9691341207381867], ["Rotate", 0.9833579358130944, 0.12227426932415297]], [ ["AutoContrast", 0.7572619475282892, 0.8062834082727393], ["Contrast", 0.1447865402875591, 0.40242646573228436], ], [["Rotate", 0.7035658783466086, 0.9840285268256428], ["Contrast", 0.04613961510519471, 0.7666683217450163]], [ ["TranslateX", 0.4580462177951252, 0.6448678609474686], ["AutoContrast", 0.14845695613708987, 0.1581134188537895], ], [["Color", 0.06795037145259564, 0.9115552821158709], ["TranslateY", 0.9972953449677655, 0.6791016521791214]], [["Cutout", 0.3586908443690823, 0.11578558293480945], ["Color", 0.49083981719164294, 0.6924851425917189]], [ ["Brightness", 0.7994717831637873, 0.7887316255321768], ["Posterize", 0.01280463502435425, 0.2799086732858721], ], [ ["ShearY", 0.6733451536131859, 0.8122332639516706], ["AutoContrast", 0.20433889615637357, 0.29023346867819966], ], [["TranslateY", 0.709913512385177, 0.6538196931503809], ["Invert", 0.06629795606579203, 0.40913219547548296]], [["Sharpness", 0.4704559834362948, 0.4235993305308414], ["Equalize", 0.7578132044306966, 0.9388824249397175]], [["AutoContrast", 0.5281702802395268, 0.8077253610116979], ["Equalize", 0.856446858814119, 0.0479755681647559]], [["Color", 0.8244145826797791, 0.038409264586238945], ["Equalize", 0.4933123249234237, 0.8251940933672189]], [["TranslateX", 0.23949314158035084, 0.13576027004706692], ["ShearX", 0.8547563771688399, 0.8309262160483606]], [["Cutout", 0.4655680937486001, 0.2819807000622825], ["Contrast", 0.8439552665937905, 0.4843617871587037]], [ ["TranslateX", 0.19142454476784831, 0.7516148119169537], ["AutoContrast", 0.8677128351329768, 0.34967990912346336], ], [["Contrast", 0.2997868299880966, 0.919508054854469], ["AutoContrast", 0.3003418493384957, 0.812314984368542]], [["Invert", 0.1070424236198183, 0.614674386498809], ["TranslateX", 0.5010973510899923, 0.20828478805259465]], [["Contrast", 0.6775882415611454, 0.6938564815591685], ["Cutout", 0.4814634264207498, 0.3086844939744179]], [["TranslateY", 0.939427105020265, 0.02531043619423201], ["Contrast", 0.793754257944812, 0.6676072472565451]], [["Sharpness", 0.09833672397575444, 0.5937214638292085], ["Rotate", 0.32530675291753763, 0.08302275740932441]], [ ["Sharpness", 0.3096455511562728, 0.6726732004553959], ["TranslateY", 0.43268997648796537, 0.8755012330217743], ], [["ShearY", 0.9290771880324833, 0.22114736271319912], ["Equalize", 0.5520199288501478, 0.34269650332060553]], [ ["AutoContrast", 0.39763980746649374, 0.4597414582725454], ["Contrast", 0.941507852412761, 0.24991270562477041], ], [["Contrast", 0.19419400547588095, 0.9127524785329233], ["Invert", 0.40544905179551727, 0.770081532844878]], [["Invert", 0.30473757368608334, 0.23534811781828846], ["Cutout", 0.26090722356706686, 0.5478390909877727]], [["Posterize", 0.49434361308057373, 0.05018423270527428], ["Color", 0.3041910676883317, 0.2603810415446437]], [["Invert", 0.5149061746764011, 0.9507449210221298], ["TranslateY", 0.4458076521892904, 0.8235358255774426]], [["Cutout", 0.7900006753351625, 0.905578861382507], ["Cutout", 0.6707153655762056, 0.8236715672258502]], [["Solarize", 0.8750534386579575, 0.10337670467100568], ["Posterize", 0.6102379615481381, 0.9264503915416868]], [["ShearY", 0.08448689377082852, 0.13981233725811626], ["TranslateX", 0.13979689669329498, 0.768774869872818]], [ ["TranslateY", 0.35752572266759985, 0.22827299847812488], ["Solarize", 0.3906957174236011, 0.5663314388307709], ], [["ShearY", 0.29155240367061563, 0.8427516352971683], ["ShearX", 0.988825367441916, 0.9371258864857649]], [["Posterize", 0.3470780859769458, 0.5467686612321239], ["Rotate", 0.5758606274160093, 0.8843838082656007]], [["Cutout", 0.07825368363221841, 0.3230799425855425], ["Equalize", 0.2319163865298529, 0.42133965674727325]], [["Invert", 0.41972172597448654, 0.34618622513582953], ["ShearX", 0.33638469398198834, 0.9098575535928108]], [["Invert", 0.7322652233340448, 0.7747502957687412], ["Cutout", 0.9643121397298106, 0.7983335094634907]], [ ["TranslateY", 0.30039942808098496, 0.229018798182827], ["TranslateY", 0.27009499739380194, 0.6435577237846236], ], [["Color", 0.38245274994070644, 0.7030758568461645], ["ShearX", 0.4429321461666281, 0.6963787864044149]], [ ["AutoContrast", 0.8432798685515605, 0.5775214369578088], ["Brightness", 0.7140899735355927, 0.8545854720117658], ], [["Rotate", 0.14418935535613786, 0.5637968282213426], ["Color", 0.7115231912479835, 0.32584796564566776]], [ ["Sharpness", 0.4023501062807533, 0.4162097130412771], ["Brightness", 0.5536372686153666, 0.03004023273348777], ], [["TranslateX", 0.7526053265574295, 0.5365938133399961], ["Cutout", 0.07914142706557492, 0.7544953091603148]], [["TranslateY", 0.6932934644882822, 0.5302211727137424], ["Invert", 0.5040606028391255, 0.6074863635108957]], [ ["Sharpness", 0.5013938602431629, 0.9572417724333157], ["TranslateY", 0.9160516359783026, 0.41798927975391675], ], [["ShearY", 0.5130018836722556, 0.30209438428424185], ["Color", 0.15017170588500262, 0.20653495360587826]], [["TranslateX", 0.5293300090022314, 0.6407011888285266], ["Rotate", 0.4809817860439001, 0.3537850070371702]], [["Equalize", 0.42243081336551014, 0.13472721311046565], ["Posterize", 0.4700309639484068, 0.5197704360874883]], [ ["AutoContrast", 0.40674959899687235, 0.7312824868168921], ["TranslateX", 0.7397527975920833, 0.7068339877944815], ], [["TranslateY", 0.5880995184787206, 0.41294111378078946], ["ShearX", 0.3181387627799316, 0.4810010147143413]], [["Color", 0.9898680233928507, 0.13241525577655167], ["Contrast", 0.9824932511238534, 0.5081145010853807]], [["Invert", 0.1591854062582687, 0.9760371953250404], ["Color", 0.9913399302056851, 0.8388709501056177]], [ ["Rotate", 0.6427451962231163, 0.9486793975292853], ["AutoContrast", 0.8501937877930463, 0.021326757974406196], ], [["Contrast", 0.13611684531087598, 0.3050858709483848], ["Posterize", 0.06618644756084646, 0.8776928511951034]], [["TranslateX", 0.41021065663839407, 0.4965319749091702], ["Rotate", 0.07088831484595115, 0.4435516708223345]], [["Sharpness", 0.3151707977154323, 0.28275482520179296], ["Invert", 0.36980384682133804, 0.20813616084536624]], [["Cutout", 0.9979060206661017, 0.39712948644725854], ["Brightness", 0.42451052896163466, 0.942623075649937]], [ ["Equalize", 0.5300853308425644, 0.010183500830128867], ["AutoContrast", 0.06930788523716991, 0.5403125318991522], ], [["Contrast", 0.010385458959237814, 0.2588311035539086], ["ShearY", 0.9347048553928764, 0.10439028366854963]], [["ShearY", 0.9867649486508592, 0.8409258132716434], ["ShearX", 0.48031199530836444, 0.7703375364614137]], [["ShearY", 0.04835889473136512, 0.2671081675890492], ["Brightness", 0.7856432618509617, 0.8032169570159564]], [ ["Posterize", 0.11112884927351185, 0.7116956530752987], ["TranslateY", 0.7339151092128607, 0.3331241226029017], ], [["Invert", 0.13527036207875454, 0.8425980515358883], ["Color", 0.7836395778298139, 0.5517059252678862]], [ ["Sharpness", 0.012541163521491816, 0.013197550692292892], ["Invert", 0.6295957932861318, 0.43276521236056054], ], [ ["AutoContrast", 0.7681480991225756, 0.3634284648496289], ["Brightness", 0.09708289828517969, 0.45016725043529726], ], [ ["Brightness", 0.5839450499487329, 0.47525965678316795], ["Posterize", 0.43096581990183735, 0.9332382960125196], ], [["Contrast", 0.9725334964552795, 0.9142902966863341], ["Contrast", 0.12376116410622995, 0.4355916974126801]], [ ["TranslateX", 0.8572708473690132, 0.02544522678265526], ["Sharpness", 0.37902120723460364, 0.9606092969833118], ], [["TranslateY", 0.8907359001296927, 0.8011363927236099], ["Color", 0.7693777154407178, 0.0936768686746503]], [["Equalize", 0.0002657688243309364, 0.08190798535970034], ["Rotate", 0.5215478065240905, 0.5773519995038368]], [["TranslateY", 0.3383007813932477, 0.5733428274739165], ["Sharpness", 0.2436110797174722, 0.4757790814590501]], [["Cutout", 0.0957402176213592, 0.8914395928996034], ["Cutout", 0.4959915628586883, 0.25890349461645246]], [["AutoContrast", 0.594787300189186, 0.9627455357634459], ["ShearY", 0.5136027621132064, 0.10419602450259002]], [["Solarize", 0.4684077211553732, 0.6592850629431414], ["Sharpness", 0.2382385935956325, 0.6589291408243176]], [["Cutout", 0.4478786947325877, 0.6893616643143388], ["TranslateX", 0.2761781720270474, 0.21750622627277727]], [["Sharpness", 0.39476077929016484, 0.930902796668923], ["Cutout", 0.9073012208742808, 0.9881122386614257]], [["TranslateY", 0.0933719180021565, 0.7206252503441172], ["ShearX", 0.5151400441789256, 0.6307540083648309]], [ ["AutoContrast", 0.7772689258806401, 0.8159317013156503], ["AutoContrast", 0.5932793713915097, 0.05262217353927168], ], [["Equalize", 0.38017352056118914, 0.8084724050448412], ["ShearY", 0.7239725628380852, 0.4246314890359326]], [["Cutout", 0.741157483503503, 0.13244380646497977], ["Invert", 0.03395378056675935, 0.7140036618098844]], [["Rotate", 0.0662727247460636, 0.7099861732415447], ["Rotate", 0.3168532707508249, 0.3553167425022127]], [ ["AutoContrast", 0.7429303516734129, 0.07117444599776435], ["Posterize", 0.5379537435918104, 0.807221330263993], ], [["TranslateY", 0.9788586874795164, 0.7967243851346594], ["Invert", 0.4479103376922362, 0.04260360776727545]], [ ["Cutout", 0.28318121763188997, 0.7748680701406292], ["AutoContrast", 0.9109258369403016, 0.17126397858002085], ], [["Color", 0.30183727885272027, 0.46718354750112456], ["TranslateX", 0.9628952256033627, 0.10269543754135535]], [ ["AutoContrast", 0.6316709389784041, 0.84287698792044], ["Brightness", 0.5544761629904337, 0.025264772745200004], ], [["Rotate", 0.08803313299532567, 0.306059720523696], ["Invert", 0.5222165872425064, 0.045935208620454304]], [ ["TranslateY", 0.21912346831923835, 0.48529224559004436], ["TranslateY", 0.15466734731903942, 0.8929485418495068], ], [["ShearX", 0.17141022847016563, 0.8607600402165531], ["ShearX", 0.6890511341106859, 0.7540899265679949]], [["Invert", 0.9417455522972059, 0.9021733684991224], ["Solarize", 0.7693107057723746, 0.7268007946568782]], [["Posterize", 0.02376991543373752, 0.6768442864453844], ["Rotate", 0.7736875065112697, 0.6706331753139825]], [["Contrast", 0.3623841610390669, 0.15023657344457686], ["Equalize", 0.32975472189318666, 0.05629246869510651]], [ ["Sharpness", 0.7874882420165824, 0.49535778020457066], ["Posterize", 0.09485578893387558, 0.6170768580482466], ], [ ["Brightness", 0.7099280202949585, 0.021523012961427335], ["Posterize", 0.2076371467666719, 0.17168118578815206], ], [["Color", 0.8546367645761538, 0.832011891505731], ["Equalize", 0.6429734783051777, 0.2618995960561532]], [["Rotate", 0.8780793721476224, 0.5920897827664297], ["ShearX", 0.5338303685064825, 0.8605424531336439]], [["Sharpness", 0.7504493806631884, 0.9723552387375258], ["Sharpness", 0.3206385634203266, 0.45127845905824693]], [["ShearX", 0.23794709526711355, 0.06257530645720066], ["Solarize", 0.9132374030587093, 0.6240819934824045]], [["Sharpness", 0.790583587969259, 0.28551171786655405], ["Contrast", 0.39872982844590554, 0.09644706751019538]], [["Equalize", 0.30681999237432944, 0.5645045018157916], ["Posterize", 0.525966242669736, 0.7360106111256014]], [["TranslateX", 0.4881014179825114, 0.6317220208872226], ["ShearX", 0.2935158995550958, 0.23104608987381758]], [["Rotate", 0.49977116738568395, 0.6610761068306319], ["TranslateY", 0.7396566602715687, 0.09386747830045217]], [["ShearY", 0.5909773790018789, 0.16229529902832718], ["Equalize", 0.06461394468918358, 0.6661349001143908]], [["TranslateX", 0.7218443721851834, 0.04435720302810153], ["Cutout", 0.986686540951642, 0.734771197038724]], [["ShearX", 0.5353800096911666, 0.8120139502148365], ["Equalize", 0.4613239578449774, 0.5159528929124512]], [["Color", 0.0871713897628631, 0.7708895183198486], ["Solarize", 0.5811386808912219, 0.35260648120785887]], [["Posterize", 0.3910857927477053, 0.4329219555775561], ["Color", 0.9115983668789468, 0.6043069944145293]], [ ["Posterize", 0.07493067637060635, 0.4258000066006725], ["AutoContrast", 0.4740957581389772, 0.49069587151651295], ], [["Rotate", 0.34086200894268937, 0.9812149332288828], ["Solarize", 0.6801012471371733, 0.17271491146753837]], [["Color", 0.20542270872895207, 0.5532087457727624], ["Contrast", 0.2718692536563381, 0.20313287569510108]], [ ["Equalize", 0.05199827210980934, 0.0832859890912212], ["AutoContrast", 0.8092395764794107, 0.7778945136511004], ], [["Sharpness", 0.1907689513066838, 0.7705754572256907], ["Color", 0.3911178658498049, 0.41791326933095485]], [ ["Solarize", 0.19611855804748257, 0.2407807485604081], ["AutoContrast", 0.5343964972940493, 0.9034209455548394], ], [["Color", 0.43586520148538865, 0.4711164626521439], ["ShearY", 0.28635408186820555, 0.8417816793020271]], [["Cutout", 0.09818482420382535, 0.1649767430954796], ["Cutout", 0.34582392911178494, 0.3927982995799828]], [["ShearX", 0.001253882705272269, 0.48661629027584596], ["Solarize", 0.9229221435457137, 0.44374894836659073]], [["Contrast", 0.6829734655718668, 0.8201750485099037], ["Cutout", 0.7886756837648936, 0.8423285219631946]], [["TranslateY", 0.857017093561528, 0.3038537151773969], ["Invert", 0.12809228606383538, 0.23637166191748027]], [["Solarize", 0.9829027723424164, 0.9723093910674763], ["Color", 0.6346495302126811, 0.5405494753107188]], [ ["AutoContrast", 0.06868643520377715, 0.23758659417688077], ["AutoContrast", 0.6648225411500879, 0.5618315648260103], ], [["Invert", 0.44202305603311676, 0.9945938909685547], ["Equalize", 0.7991650497684454, 0.16014142656347097]], [ ["AutoContrast", 0.8778631604769588, 0.03951977631894088], ["ShearY", 0.8495160088963707, 0.35771447321250416], ], [["Color", 0.5365078341001592, 0.21102444169782308], ["ShearX", 0.7168869678248874, 0.3904298719872734]], [["TranslateX", 0.6517203786101899, 0.6467598990650437], ["Invert", 0.26552491504364517, 0.1210812827294625]], [["Posterize", 0.35196021684368994, 0.8420648319941891], ["Invert", 0.7796829363930631, 0.9520895999240896]], [["Sharpness", 0.7391572148971984, 0.4853940393452846], ["TranslateX", 0.7641915295592839, 0.6351349057666782]], [["Posterize", 0.18485880221115913, 0.6117603277356728], ["Rotate", 0.6541660490605724, 0.5704041108375348]], [["TranslateY", 0.27517423188070533, 0.6610080904072458], ["Contrast", 0.6091250547289317, 0.7702443247557892]], [["Equalize", 0.3611798581067118, 0.6623615672642768], ["TranslateX", 0.9537265090885917, 0.06352772509358584]], [["ShearX", 0.09720029389103535, 0.7800423126320308], ["Invert", 0.30314352455858884, 0.8519925470889914]], [["Brightness", 0.06931529763458055, 0.57760829499712], ["Cutout", 0.637251974467394, 0.7184346129191052]], [ ["AutoContrast", 0.5026722100286064, 0.32025257156541886], ["Contrast", 0.9667478703047919, 0.14178519432669368], ], [["Equalize", 0.5924463845816984, 0.7187610262181517], ["TranslateY", 0.7059479079159405, 0.06551471830655187]], [ ["Sharpness", 0.18161164512332928, 0.7576138481173385], ["Brightness", 0.19191138767695282, 0.7865880269424701], ], [ ["Brightness", 0.36780861866078696, 0.0677855546737901], ["AutoContrast", 0.8491446654142264, 0.09217782099938121], ], [ ["TranslateY", 0.06011399855120858, 0.8374487034710264], ["TranslateY", 0.8373922962070498, 0.1991295720254297], ], [["Posterize", 0.702559916122481, 0.30257509683007755], ["Rotate", 0.249899495398891, 0.9370437251176267]], [["ShearX", 0.9237874098232075, 0.26241907483351146], ["Brightness", 0.7221766836146657, 0.6880749752986671]], [["Cutout", 0.37994098189193104, 0.7836874473657957], ["ShearX", 0.9212861960976824, 0.8140948561570449]], [["Posterize", 0.2584098274786417, 0.7990847652004848], ["Invert", 0.6357731737590063, 0.1066304859116326]], [["Sharpness", 0.4412790857539922, 0.9692465283229825], ["Color", 0.9857401617339051, 0.26755393929808713]], [["Equalize", 0.22348671644912665, 0.7370019910830038], ["Posterize", 0.5396106339575417, 0.5559536849843303]], [["Equalize", 0.8742967663495852, 0.2797122599926307], ["Rotate", 0.4697322053105951, 0.8769872942579476]], [["Sharpness", 0.44279911640509206, 0.07729581896071613], ["Cutout", 0.3589177366154631, 0.2704031551235969]], [ ["TranslateX", 0.614216412574085, 0.47929659784170453], ["Brightness", 0.6686234118438007, 0.05700784068205689], ], [["ShearY", 0.17920614630857634, 0.4699685075827862], ["Color", 0.38251870810870003, 0.7262706923005887]], [["Solarize", 0.4951799001144561, 0.212775278026479], ["TranslateX", 0.8666105646463097, 0.6750496637519537]], [["Color", 0.8110864170849051, 0.5154263861958484], ["Sharpness", 0.2489044083898776, 0.3763372541462343]], [["Cutout", 0.04888193613483871, 0.06041664638981603], ["Color", 0.06438587718683708, 0.5797881428892969]], [["Rotate", 0.032427448352152166, 0.4445797818376559], ["Posterize", 0.4459357828482998, 0.5879865187630777]], [["ShearX", 0.1617179557693058, 0.050796802246318884], ["Cutout", 0.8142465452060423, 0.3836391305618707]], [["TranslateY", 0.1806857249209416, 0.36697730355422675], ["Rotate", 0.9897576550818276, 0.7483432452225264]], [["Brightness", 0.18278016458098223, 0.952352527690299], ["Cutout", 0.3269735224453044, 0.3924869905012752]], [["ShearX", 0.870832707718742, 0.3214743207190739], ["Cutout", 0.6805560681792573, 0.6984188155282459]], [["TranslateX", 0.4157118388833776, 0.3964216288135384], ["TranslateX", 0.3253012682285006, 0.624835513104391]], [["Contrast", 0.7678168037628158, 0.31033802162621793], ["ShearX", 0.27022424855977134, 0.3773245605126201]], [["TranslateX", 0.37812621869017593, 0.7657993810740699], ["Rotate", 0.18081890120092914, 0.8893511219618171]], [["Posterize", 0.8735859716088367, 0.18243793043074286], ["TranslateX", 0.90435994250313, 0.24116383818819453]], [["Invert", 0.06666709253664793, 0.3881076083593933], ["TranslateX", 0.3783333964963522, 0.14411014979589543]], [["Equalize", 0.8741147867162096, 0.14203839235846816], ["TranslateX", 0.7801536758037405, 0.6952401607812743]], [["Cutout", 0.6095335117944475, 0.5679026063718094], ["Posterize", 0.06433868172233115, 0.07139559616012303]], [["TranslateY", 0.3020364047315408, 0.21459810361176246], ["Cutout", 0.7097677414888889, 0.2942144632587549]], [["Brightness", 0.8223662419048653, 0.195700694016108], ["Invert", 0.09345407040803999, 0.779843655582099]], [["TranslateY", 0.7353462929356228, 0.0468520680237382], ["Cutout", 0.36530918247940425, 0.3897292909049672]], [["Invert", 0.9676896451721213, 0.24473302189463453], ["Invert", 0.7369271521408992, 0.8193267003356975]], [["Sharpness", 0.8691871972054326, 0.4441713912682772], ["ShearY", 0.47385584832119887, 0.23521684584675429]], [["ShearY", 0.9266946026184021, 0.7611986713358834], ["TranslateX", 0.6195820760253926, 0.14661428669483678]], [ ["Sharpness", 0.08470870576026868, 0.3380219099907229], ["TranslateX", 0.3062343307496658, 0.7135777338095889], ], [["Sharpness", 0.5246448204194909, 0.3193061215236702], ["ShearX", 0.8160637208508432, 0.9720697396582731]], [["Posterize", 0.5249259956549405, 0.3492042382504774], ["Invert", 0.8183138799547441, 0.11107271762524618]], [["TranslateY", 0.210869733350744, 0.7138905840721885], ["Sharpness", 0.7773226404450125, 0.8005353621959782]], [ ["Posterize", 0.33067522385556025, 0.32046239220630124], ["AutoContrast", 0.18918147708798405, 0.4646281070474484], ], [["TranslateX", 0.929502026131094, 0.8029128121556285], ["Invert", 0.7319794306118105, 0.5421878712623392]], [["ShearX", 0.25645940834182723, 0.42754710760160963], ["ShearX", 0.44640695310173306, 0.8132185532296811]], [["Color", 0.018436846416536312, 0.8439313862001113], ["Sharpness", 0.3722867661453415, 0.5103570873163251]], [ ["TranslateX", 0.7285989086776543, 0.4809027697099264], ["TranslateY", 0.9740807004893643, 0.8241085438636939], ], [["Posterize", 0.8721868989693397, 0.5700907310383815], ["Posterize", 0.4219074410577852, 0.8032643572845402]], [["Contrast", 0.9811380092558266, 0.8498397471632105], ["Sharpness", 0.8380884329421594, 0.18351306571903125]], [["TranslateY", 0.3878939366762001, 0.4699103438753077], ["Invert", 0.6055556353233807, 0.8774727658400134]], [ ["TranslateY", 0.052317005261018346, 0.39471450378745787], ["ShearX", 0.8612486845942395, 0.28834103278807466], ], [["Color", 0.511993351208063, 0.07251427040525904], ["Solarize", 0.9898097047354855, 0.299761565689576]], [["Equalize", 0.2721248231619904, 0.6870975927455507], ["Cutout", 0.8787327242363994, 0.06228061428917098]], [["Invert", 0.8931880335225408, 0.49720931867378193], ["Posterize", 0.9619698792159256, 0.17859639696940088]], [ ["Posterize", 0.0061688075074411985, 0.08082938731035938], ["Brightness", 0.27745128028826993, 0.8638528796903816], ], [["ShearY", 0.9140200609222026, 0.8240421430867707], ["Invert", 0.651734417415332, 0.08871906369930926]], [["Color", 0.45585010413511196, 0.44705070078574316], ["Color", 0.26394624901633146, 0.11242877788650807]], [["ShearY", 0.9200278466372522, 0.2995901331149652], ["Cutout", 0.8445407215116278, 0.7410524214287446]], [["ShearY", 0.9950483746990132, 0.112964468262847], ["ShearY", 0.4118332303218585, 0.44839613407553636]], [["Contrast", 0.7905821952255192, 0.23360046159385106], ["Posterize", 0.8611787233956044, 0.8984260048943528]], [["TranslateY", 0.21448061359312853, 0.8228112806838331], ["Contrast", 0.8992297266152983, 0.9179231590570998]], [["Invert", 0.3924194798946006, 0.31830516468371495], ["Rotate", 0.8399556845248508, 0.3764892022932781]], [ ["Cutout", 0.7037916990046816, 0.9214620769502728], ["AutoContrast", 0.02913794613018239, 0.07808607528954048], ], [["ShearY", 0.6041490474263381, 0.6094184590800105], ["Equalize", 0.2932954517354919, 0.5840888946081727]], [["ShearX", 0.6056801676269449, 0.6948580442549543], ["Cutout", 0.3028001021044615, 0.15117101733894078]], [ ["Brightness", 0.8011486803860253, 0.18864079729374195], ["Solarize", 0.014965327213230961, 0.8842620292527029], ], [["Invert", 0.902244007904273, 0.5634673798052033], ["Equalize", 0.13422913507398349, 0.4110956745883727]], [["TranslateY", 0.9981773319103838, 0.09568550987216096], ["Color", 0.7627662124105109, 0.8494409737419493]], [["Cutout", 0.3013527640416782, 0.03377226729898486], ["ShearX", 0.5727964831614619, 0.8784196638222834]], [ ["TranslateX", 0.6050722426803684, 0.3650103962378708], ["TranslateX", 0.8392084589130886, 0.6479816470292911], ], [["Rotate", 0.5032806606500023, 0.09276980118866307], ["TranslateY", 0.7800234515261191, 0.18896454379343308]], [["Invert", 0.9266027256244017, 0.8246111062199752], ["Contrast", 0.12112023357797697, 0.33870762271759436]], [["Brightness", 0.8688784756993134, 0.17263759696106606], ["ShearX", 0.5133700431071326, 0.6686811994542494]], [["Invert", 0.8347840440941976, 0.03774897445901726], ["Brightness", 0.24925057499276548, 0.04293631677355758]], [["Color", 0.5998145279485104, 0.4820093200092529], ["TranslateY", 0.6709586184077769, 0.07377334081382858]], [["AutoContrast", 0.7898846202957984, 0.325293526672498], ["Contrast", 0.5156435596826767, 0.2889223168660645]], [["ShearX", 0.08147389674998307, 0.7978924681113669], ["Contrast", 0.7270003309106291, 0.009571215234092656]], [["Sharpness", 0.417607614440786, 0.9532566433338661], ["Posterize", 0.7186586546796782, 0.6936509907073302]], [["ShearX", 0.9555300215926675, 0.1399385550263872], ["Color", 0.9981041061848231, 0.5037462398323248]], [["Equalize", 0.8003487831375474, 0.5413759363796945], ["ShearY", 0.0026607045117773565, 0.019262273030984933]], [["TranslateY", 0.04845391502469176, 0.10063445212118283], ["Cutout", 0.8273170186786745, 0.5045257728554577]], [ ["TranslateX", 0.9690985344978033, 0.505202991815533], ["TranslateY", 0.7255326592928096, 0.02103609500701631], ], [["Solarize", 0.4030771176836736, 0.8424237871457034], ["Cutout", 0.28705805963928965, 0.9601617893682582]], [["Sharpness", 0.16865290353070606, 0.6899673563468826], ["Posterize", 0.3985430034869616, 0.6540651997730774]], [["ShearY", 0.21395578485362032, 0.09519358818949009], ["Solarize", 0.6692821708524135, 0.6462523623552485]], [ ["AutoContrast", 0.912360598054091, 0.029800239085051583], ["Invert", 0.04319256403746308, 0.7712501517098587], ], [["ShearY", 0.9081969961839055, 0.4581560239984739], ["AutoContrast", 0.5313894814729159, 0.5508393335751848]], [["ShearY", 0.860528568424097, 0.8196987216301588], ["Posterize", 0.41134650331494205, 0.3686632018978778]], [ ["AutoContrast", 0.8753670810078598, 0.3679438326304749], ["Invert", 0.010444228965415858, 0.9581244779208277], ], [ ["Equalize", 0.07071836206680682, 0.7173594756186462], ["Brightness", 0.06111434312497388, 0.16175064669049277], ], [ ["AutoContrast", 0.10522219073562122, 0.9768776621069855], ["TranslateY", 0.2744795945215529, 0.8577967957127298], ], [["AutoContrast", 0.7628146493166175, 0.996157376418147], ["Contrast", 0.9255565598518469, 0.6826126662976868]], [ ["TranslateX", 0.017225816199011312, 0.2470332491402908], ["Solarize", 0.44048494909493807, 0.4492422515972162], ], [["ShearY", 0.38885252627795064, 0.10272256704901939], ["Equalize", 0.686154959829183, 0.8973517148655337]], [["Rotate", 0.29628991573592967, 0.16639926575004715], ["ShearX", 0.9013782324726413, 0.0838318162771563]], [["Color", 0.04968391374688563, 0.6138600739645352], ["Invert", 0.11177127838716283, 0.10650198522261578]], [["Invert", 0.49655016367624016, 0.8603374164829688], ["ShearY", 0.40625439617553727, 0.4516437918820778]], [ ["TranslateX", 0.15015718916062992, 0.13867777502116208], ["Brightness", 0.3374464418810188, 0.7613355669536931], ], [["Invert", 0.644644393321966, 0.19005804481199562], ["AutoContrast", 0.2293259789431853, 0.30335723256340186]], [["Solarize", 0.004968793254801596, 0.5370892072646645], ["Contrast", 0.9136902637865596, 0.9510587477779084]], [["Rotate", 0.38991518440867123, 0.24796987467455756], ["Sharpness", 0.9911180315669776, 0.5265657122981591]], [["Solarize", 0.3919646484436238, 0.6814994037194909], ["Sharpness", 0.4920838987787103, 0.023425724294012018]], [["TranslateX", 0.25107587874378867, 0.5414936560189212], ["Cutout", 0.7932919623814599, 0.9891303444820169]], [ ["Brightness", 0.07863012174272999, 0.045175652208389594], ["Solarize", 0.889609658064552, 0.8228793315963948], ], [["Cutout", 0.20477096178169596, 0.6535063675027364], ["ShearX", 0.9216318577173639, 0.2908690977359947]], [["Contrast", 0.7035118947423187, 0.45982709058312454], ["Contrast", 0.7130268070749464, 0.8635123354235471]], [["Sharpness", 0.26319477541228997, 0.7451278726847078], ["Rotate", 0.8170499362173754, 0.13998593411788207]], [["Rotate", 0.8699365715164192, 0.8878057721750832], ["Equalize", 0.06682350555715044, 0.7164702080630689]], [["ShearY", 0.3137466057521987, 0.6747433496011368], ["Rotate", 0.42118828936218133, 0.980121180104441]], [["Solarize", 0.8470375049950615, 0.15287589264139223], ["Cutout", 0.14438435054693055, 0.24296463267973512]], [ ["TranslateY", 0.08822241792224905, 0.36163911974799356], ["TranslateY", 0.11729726813270003, 0.6230889726445291], ], [["ShearX", 0.7720112337718541, 0.2773292905760122], ["Sharpness", 0.756290929398613, 0.27830353710507705]], [["Color", 0.33825031007968287, 0.4657590047522816], ["ShearY", 0.3566628994713067, 0.859750504071925]], [ ["TranslateY", 0.06830147433378053, 0.9348778582086664], ["TranslateX", 0.15509346516378553, 0.26320778885339435], ], [ ["Posterize", 0.20266751150740858, 0.008351463842578233], ["Sharpness", 0.06506971109417259, 0.7294471760284555], ], [["TranslateY", 0.6278911394418829, 0.8702181892620695], ["Invert", 0.9367073860264247, 0.9219230428944211]], [["Sharpness", 0.1553425337673321, 0.17601557714491345], ["Solarize", 0.7040449681338888, 0.08764313147327729]], [ ["Equalize", 0.6082233904624664, 0.4177428549911376], ["AutoContrast", 0.04987405274618151, 0.34516208204700916], ], [ ["Brightness", 0.9616085936167699, 0.14561237331885468], ["Solarize", 0.8927707736296572, 0.31176907850205704], ], [ ["Brightness", 0.6707778304730988, 0.9046457117525516], ["Brightness", 0.6801448953060988, 0.20015313057149042], ], [["Color", 0.8292680845499386, 0.5181603879593888], ["Brightness", 0.08549161770369762, 0.6567870536463203]], [["ShearY", 0.267802208078051, 0.8388133819588173], ["Sharpness", 0.13453409120796123, 0.10028351311149486]], [["Posterize", 0.775796593610272, 0.05359034561289766], ["Cutout", 0.5067360625733027, 0.054451986840317934]], [ ["TranslateX", 0.5845238647690084, 0.7507147553486293], ["Brightness", 0.2642051786121197, 0.2578358927056452], ], [["Cutout", 0.10787517610922692, 0.8147986902794228], ["Contrast", 0.2190149206329539, 0.902210615462459]], [["TranslateX", 0.5663614214181296, 0.05309965916414028], ["ShearX", 0.9682797885154938, 0.41791929533938466]], [["ShearX", 0.2345325577621098, 0.383780128037189], ["TranslateX", 0.7298083748149163, 0.644325797667087]], [ ["Posterize", 0.5138725709682734, 0.7901809917259563], ["AutoContrast", 0.7966018627776853, 0.14529337543427345], ], [["Invert", 0.5973031989249785, 0.417399314592829], ["Solarize", 0.9147539948653116, 0.8221272315548086]], [["Posterize", 0.601596043336383, 0.18969646160963938], ["Color", 0.7527275484079655, 0.431793831326888]], [["Equalize", 0.6731483454430538, 0.7866786558207602], ["TranslateX", 0.97574396899191, 0.5970255778044692]], [["Cutout", 0.15919495850169718, 0.8916094305850562], ["Invert", 0.8351348834751027, 0.4029937360314928]], [["Invert", 0.5894085405226027, 0.7283806854157764], ["Brightness", 0.3973976860470554, 0.949681121498567]], [ ["AutoContrast", 0.3707914135327408, 0.21192068592079616], ["ShearX", 0.28040127351140676, 0.6754553511344856], ], [["Solarize", 0.07955132378694896, 0.15073572961927306], ["ShearY", 0.5735850168851625, 0.27147326850217746]], [["Equalize", 0.678653949549764, 0.8097796067861455], ["Contrast", 0.2283048527510083, 0.15507804874474185]], [["Equalize", 0.286013868374536, 0.186785848694501], ["Posterize", 0.16319021740810458, 0.1201304443285659]], [ ["Sharpness", 0.9601590830563757, 0.06267915026513238], ["AutoContrast", 0.3813920685124327, 0.294224403296912], ], [["Brightness", 0.2703246632402241, 0.9168405377492277], ["ShearX", 0.6156009855831097, 0.4955986055846403]], [["Color", 0.9065504424987322, 0.03393612216080133], ["ShearY", 0.6768595880405884, 0.9981068127818191]], [["Equalize", 0.28812842368483904, 0.300387487349145], ["ShearY", 0.28812248704858345, 0.27105076231533964]], [["Brightness", 0.6864882730513477, 0.8205553299102412], ["Cutout", 0.45995236371265424, 0.5422030370297759]], [["Color", 0.34941404877084326, 0.25857961830158516], ["AutoContrast", 0.3451390878441899, 0.5000938249040454]], [["Invert", 0.8268247541815854, 0.6691380821226468], ["Cutout", 0.46489193601530476, 0.22620873109485895]], [["Rotate", 0.17879730528062376, 0.22670425330593935], ["Sharpness", 0.8692795688221834, 0.36586055020855723]], [["Brightness", 0.31203975139659634, 0.6934046293010939], ["Cutout", 0.31649437872271236, 0.08078625004157935]], [["Cutout", 0.3119482836150119, 0.6397160035509996], ["Contrast", 0.8311248624784223, 0.22897510169718616]], [ ["TranslateX", 0.7631157841429582, 0.6482890521284557], ["Brightness", 0.12681196272427664, 0.3669813784257344], ], [ ["TranslateX", 0.06027722649179801, 0.3101104512201861], ["Sharpness", 0.5652076706249394, 0.05210008400968136], ], [["AutoContrast", 0.39213552101583127, 0.5047021194355596], ["ShearY", 0.7164003055682187, 0.8063370761002899]], [ ["Solarize", 0.9574307011238342, 0.21472064809226854], ["AutoContrast", 0.8102612285047174, 0.716870148067014], ], [ ["Rotate", 0.3592634277567387, 0.6452602893051465], ["AutoContrast", 0.27188430331411506, 0.06003099168464854], ], [["Cutout", 0.9529536554825503, 0.5285505311027461], ["Solarize", 0.08478231903311029, 0.15986449762728216]], [ ["TranslateY", 0.31176130458018936, 0.5642853506158253], ["Equalize", 0.008890883901317648, 0.5146121040955942], ], [["Color", 0.40773645085566157, 0.7110398926612682], ["Color", 0.18233100156439364, 0.7830036002758337]], [["Posterize", 0.5793809197821732, 0.043748553135581236], ["Invert", 0.4479962016131668, 0.7349663010359488]], [["TranslateX", 0.1994882312299382, 0.05216859488899439], ["Rotate", 0.48288726352035416, 0.44713829026777585]], [ ["Posterize", 0.22122838185154603, 0.5034546841241283], ["TranslateX", 0.2538745835410222, 0.6129055170893385], ], [["Color", 0.6786559960640814, 0.4529749369803212], ["Equalize", 0.30215879674415336, 0.8733394611096772]], [["Contrast", 0.47316062430673456, 0.46669538897311447], ["Invert", 0.6514906551984854, 0.3053339444067804]], [["Equalize", 0.6443202625334524, 0.8689731394616441], ["Color", 0.7549183794057628, 0.8889001426329578]], [["Solarize", 0.616709740662654, 0.7792180816399313], ["ShearX", 0.9659155537406062, 0.39436937531179495]], [ ["Equalize", 0.23694011299406226, 0.027711152164392128], ["TranslateY", 0.1677339686527083, 0.3482126536808231], ], [ ["Solarize", 0.15234175951790285, 0.7893840414281341], ["TranslateX", 0.2396395768284183, 0.27727219214979715], ], [["Contrast", 0.3792017455380605, 0.32323660409845334], ["Contrast", 0.1356037413846466, 0.9127772969992305]], [["ShearX", 0.02642732222284716, 0.9184662576502115], ["Equalize", 0.11504884472142995, 0.8957638893097964]], [["TranslateY", 0.3193812913345325, 0.8828100030493128], ["ShearY", 0.9374975727563528, 0.09909415611083694]], [ ["AutoContrast", 0.025840721736048122, 0.7941037581373024], ["TranslateY", 0.498518003323313, 0.5777122846572548], ], [["ShearY", 0.6042199307830248, 0.44809668754508836], ["Cutout", 0.3243978207701482, 0.9379740926294765]], [["ShearY", 0.6858549297583574, 0.9993252035788924], ["Sharpness", 0.04682428732773203, 0.21698099707915652]], [["ShearY", 0.7737469436637263, 0.8810127181224531], ["ShearY", 0.8995655445246451, 0.4312416220354539]], [["TranslateY", 0.4953094136709374, 0.8144161580138571], ["Solarize", 0.26301211718928097, 0.518345311180405]], [["Brightness", 0.8820246486031275, 0.571075863786249], ["ShearX", 0.8586669146703955, 0.0060476383595142735]], [ ["Sharpness", 0.20519233710982254, 0.6144574759149729], ["Posterize", 0.07976625267460813, 0.7480145046726968], ], [["ShearY", 0.374075419680195, 0.3386105402023202], ["ShearX", 0.8228083637082115, 0.5885174783155361]], [ ["Brightness", 0.3528780713814561, 0.6999884884306623], ["Sharpness", 0.3680348120526238, 0.16953358258959617], ], [ ["Brightness", 0.24891223104442084, 0.7973853494920095], ["TranslateX", 0.004256803835524736, 0.0470216343108546], ], [["Posterize", 0.1947344282646012, 0.7694802711054367], ["Cutout", 0.9594385534844785, 0.5469744140592429]], [ ["Invert", 0.19012504762806026, 0.7816140211434693], ["TranslateY", 0.17479746932338402, 0.024249345245078602], ], [["Rotate", 0.9669262055946796, 0.510166180775991], ["TranslateX", 0.8990602034610352, 0.6657802719304693]], [["ShearY", 0.5453049050407278, 0.8476872739603525], ["Cutout", 0.14226529093962592, 0.15756960661106634]], [["Equalize", 0.5895291156113004, 0.6797218994447763], ["TranslateY", 0.3541442192192753, 0.05166001155849864]], [["Equalize", 0.39530681662726097, 0.8448335365081087], ["Brightness", 0.6785483272734143, 0.8805568647038574]], [["Cutout", 0.28633258271917905, 0.7750870268336066], ["Equalize", 0.7221097824537182, 0.5865506280531162]], [["Posterize", 0.9044429629421187, 0.4620266401793388], ["Invert", 0.1803008045494473, 0.8073190766288534]], [ ["Sharpness", 0.7054649148075851, 0.3877207948962055], ["TranslateX", 0.49260224225927285, 0.8987462620731029], ], [ ["Sharpness", 0.11196934729294483, 0.5953704422694938], ["Contrast", 0.13969334315069737, 0.19310569898434204], ], [ ["Posterize", 0.5484346101051778, 0.7914140118600685], ["Brightness", 0.6428044691630473, 0.18811316670808076], ], [["Invert", 0.22294834094984717, 0.05173157689962704], ["Cutout", 0.6091129168510456, 0.6280845506243643]], [["AutoContrast", 0.5726444076195267, 0.2799840903601295], ["Cutout", 0.3055752727786235, 0.591639807512993]], [["Brightness", 0.3707116723204462, 0.4049175910826627], ["Rotate", 0.4811601625588309, 0.2710760253723644]], [["ShearY", 0.627791719653608, 0.6877498291550205], ["TranslateX", 0.8751753308366824, 0.011164650018719358]], [["Posterize", 0.33832547954522263, 0.7087039872581657], ["Posterize", 0.6247474435007484, 0.7707784192114796]], [["Contrast", 0.17620186308493468, 0.9946224854942095], ["Solarize", 0.5431896088395964, 0.5867904203742308]], [["ShearX", 0.4667959516719652, 0.8938082224109446], ["TranslateY", 0.7311343008292865, 0.6829842246020277]], [["ShearX", 0.6130281467237769, 0.9924010909612302], ["Brightness", 0.41039241699696916, 0.9753218875311392]], [["TranslateY", 0.0747250386427123, 0.34602725521067534], ["Rotate", 0.5902597465515901, 0.361094672021087]], [["Invert", 0.05234890878959486, 0.36914978664919407], ["Sharpness", 0.42140532878231374, 0.19204058551048275]], [["ShearY", 0.11590485361909497, 0.6518540857972316], ["Invert", 0.6482444740361704, 0.48256237896163945]], [["Rotate", 0.4931329446923608, 0.037076242417301675], ["Contrast", 0.9097939772412852, 0.5619594905306389]], [["Posterize", 0.7311032479626216, 0.4796364593912915], ["Color", 0.13912123993932402, 0.03997286439663705]], [["AutoContrast", 0.6196602944085344, 0.2531430457527588], ["Rotate", 0.5583937060431972, 0.9893379795224023]], [ ["AutoContrast", 0.8847753125072959, 0.19123028952580057], ["TranslateY", 0.494361716097206, 0.14232297727461696], ], [ ["Invert", 0.6212360716340707, 0.033898871473033165], ["AutoContrast", 0.30839896957008295, 0.23603569542166247], ], [["Equalize", 0.8255583546605049, 0.613736933157845], ["AutoContrast", 0.6357166629525485, 0.7894617347709095]], [["Brightness", 0.33840706322846814, 0.07917167871493658], ["ShearY", 0.15693175752528676, 0.6282773652129153]], [["Cutout", 0.7550520024859294, 0.08982367300605598], ["ShearX", 0.5844942417320858, 0.36051195083380105]], ] return p def fa_resnet50_rimagenet(): p = [ [["ShearY", 0.14143816458479197, 0.513124791615952], ["Sharpness", 0.9290316227291179, 0.9788406212603302]], [["Color", 0.21502874228385338, 0.3698477943880306], ["TranslateY", 0.49865058747734736, 0.4352676987103321]], [["Brightness", 0.6603452126485386, 0.6990174510500261], ["Cutout", 0.7742953773992511, 0.8362550883640804]], [["Posterize", 0.5188375788270497, 0.9863648925446865], ["TranslateY", 0.8365230108655313, 0.6000972236440252]], [["ShearY", 0.9714994964711299, 0.2563663552809896], ["Equalize", 0.8987567223581153, 0.1181761775609772]], [ ["Sharpness", 0.14346409304565366, 0.5342189791746006], ["Sharpness", 0.1219714162835897, 0.44746801278319975], ], [ ["TranslateX", 0.08089260772173967, 0.028011721602479833], ["TranslateX", 0.34767877352421406, 0.45131294688688794], ], [["Brightness", 0.9191164585327378, 0.5143232242627864], ["Color", 0.9235247849934283, 0.30604586249462173]], [["Contrast", 0.4584173187505879, 0.40314219914942756], ["Rotate", 0.550289356406774, 0.38419022293237126]], [["Posterize", 0.37046156420799325, 0.052693291117634544], ["Cutout", 0.7597581409366909, 0.7535799791937421]], [["Color", 0.42583964114658746, 0.6776641859552079], ["ShearY", 0.2864805671096011, 0.07580175477739545]], [ ["Brightness", 0.5065952125552232, 0.5508640233704984], ["Brightness", 0.4760021616081475, 0.3544313318097987], ], [["Posterize", 0.5169630851995185, 0.9466018906715961], ["Posterize", 0.5390336503396841, 0.1171015788193209]], [["Posterize", 0.41153170909576176, 0.7213063942615204], ["Rotate", 0.6232230424824348, 0.7291984098675746]], [["Color", 0.06704687234714028, 0.5278429246040438], ["Sharpness", 0.9146652195810183, 0.4581415618941407]], [["ShearX", 0.22404644446773492, 0.6508620171913467], ["Brightness", 0.06421961538672451, 0.06859528721039095]], [["Rotate", 0.29864103693134797, 0.5244313199644495], ["Sharpness", 0.4006161706584276, 0.5203708477368657]], [ ["AutoContrast", 0.5748186910788027, 0.8185482599354216], ["Posterize", 0.9571441684265188, 0.1921474117448481], ], [["ShearY", 0.5214786760436251, 0.8375629059785009], ["Invert", 0.6872393349333636, 0.9307694335024579]], [["Contrast", 0.47219838080793364, 0.8228524484275648], ["TranslateY", 0.7435518856840543, 0.5888865560614439]], [["Posterize", 0.10773482839638836, 0.6597021018893648], ["Contrast", 0.5218466423129691, 0.562985661685268]], [["Rotate", 0.4401753067886466, 0.055198255925702475], ["Rotate", 0.3702153509335602, 0.5821574425474759]], [ ["TranslateY", 0.6714729117832363, 0.7145542887432927], ["Equalize", 0.0023263758097700205, 0.25837341854887885], ], [["Cutout", 0.3159707561240235, 0.19539664199170742], ["TranslateY", 0.8702824829864558, 0.5832348977243467]], [ ["AutoContrast", 0.24800812729140026, 0.08017301277245716], ["Brightness", 0.5775505849482201, 0.4905904775616114], ], [["Color", 0.4143517886294533, 0.8445937742921498], ["ShearY", 0.28688910858536587, 0.17539366839474402]], [ ["Brightness", 0.6341134194059947, 0.43683815933640435], ["Brightness", 0.3362277685899835, 0.4612826163288225], ], [["Sharpness", 0.4504035748829761, 0.6698294470467474], ["Posterize", 0.9610055612671645, 0.21070714173174876]], [["Posterize", 0.19490421920029832, 0.7235798208354267], ["Rotate", 0.8675551331308305, 0.46335565746433094]], [["Color", 0.35097958351003306, 0.42199181561523186], ["Invert", 0.914112788087429, 0.44775583211984815]], [["Cutout", 0.223575616055454, 0.6328591417299063], ["TranslateY", 0.09269465212259387, 0.5101073959070608]], [["Rotate", 0.3315734525975911, 0.9983593458299167], ["Sharpness", 0.12245416662856974, 0.6258689139914664]], [["ShearY", 0.696116760180471, 0.6317805202283014], ["Color", 0.847501151593963, 0.4440116609830195]], [["Solarize", 0.24945891607225948, 0.7651150206105561], ["Cutout", 0.7229677092930331, 0.12674657348602494]], [["TranslateX", 0.43461945065713675, 0.06476571036747841], ["Color", 0.6139316940180952, 0.7376264330632316]], [["Invert", 0.1933003530637138, 0.4497819016184308], ["Invert", 0.18391634069983653, 0.3199769100951113]], [["Color", 0.20418296626476137, 0.36785101882029814], ["Posterize", 0.624658293920083, 0.8390081535735991]], [["Sharpness", 0.5864963540530814, 0.586672446690273], ["Posterize", 0.1980280647652339, 0.222114611452575]], [["Invert", 0.3543654961628104, 0.5146369635250309], ["Equalize", 0.40751271919434434, 0.4325310837291978]], [["ShearY", 0.22602859359451877, 0.13137880879778158], ["Posterize", 0.7475029061591305, 0.803900538461099]], [["Sharpness", 0.12426276165599924, 0.5965912716602046], ["Invert", 0.22603903038966913, 0.4346802001255868]], [ ["TranslateY", 0.010307035630661765, 0.16577665156754046], ["Posterize", 0.4114319141395257, 0.829872913683949], ], [["TranslateY", 0.9353069865746215, 0.5327821671247214], ["Color", 0.16990443486261103, 0.38794866007484197]], [["Cutout", 0.1028174322829021, 0.3955952903458266], ["ShearY", 0.4311995281335693, 0.48024695395374734]], [["Posterize", 0.1800334334284686, 0.0548749478418862], ["Brightness", 0.7545808536793187, 0.7699080551646432]], [["Color", 0.48695305373084197, 0.6674269768464615], ["ShearY", 0.4306032279086781, 0.06057690550239343]], [ ["Brightness", 0.4919399683825053, 0.677338905806407], ["Brightness", 0.24112708387760828, 0.42761103121157656], ], [ ["Posterize", 0.4434818644882532, 0.9489450593207714], ["Posterize", 0.40957675116385955, 0.015664946759584186], ], [["Posterize", 0.41307949855153797, 0.6843276552020272], ["Rotate", 0.8003545094091291, 0.7002300783416026]], [["Color", 0.7038570031770905, 0.4697612983649519], ["Sharpness", 0.9700016496081002, 0.25185103545948884]], [ ["AutoContrast", 0.714641656154856, 0.7962423001719023], ["Sharpness", 0.2410097684093468, 0.5919171048019731], ], [["TranslateX", 0.8101567644494714, 0.7156447005337443], ["Solarize", 0.5634727831229329, 0.8875158446846]], [["Sharpness", 0.5335258857303261, 0.364743126378182], ["Color", 0.453280875871377, 0.5621962714743068]], [["Cutout", 0.7423678127672542, 0.7726370777867049], ["Invert", 0.2806161382641934, 0.6021111986900146]], [["TranslateY", 0.15190341320343761, 0.3860373175487939], ["Cutout", 0.9980805818665679, 0.05332384819400854]], [ ["Posterize", 0.36518675678786605, 0.2935819027397963], ["TranslateX", 0.26586180351840005, 0.303641300745208], ], [["Brightness", 0.19994509744377761, 0.90813953707639], ["Equalize", 0.8447217761297836, 0.3449396603478335]], [["Sharpness", 0.9294773669936768, 0.999713346583839], ["Brightness", 0.1359744825665662, 0.1658489221872924]], [ ["TranslateX", 0.11456529257659381, 0.9063795878367734], ["Equalize", 0.017438134319894553, 0.15776887259743755], ], [["ShearX", 0.9833726383270114, 0.5688194948373335], ["Equalize", 0.04975615490994345, 0.8078130016227757]], [ ["Brightness", 0.2654654830488695, 0.8989789725280538], ["TranslateX", 0.3681535065952329, 0.36433345713161036], ], [["Rotate", 0.04956524209892327, 0.5371942433238247], ["ShearY", 0.0005527499145153714, 0.56082571605602]], [["Rotate", 0.7918337108932019, 0.5906896260060501], ["Posterize", 0.8223967034091191, 0.450216998388943]], [["Color", 0.43595106766978337, 0.5253013785221605], ["Sharpness", 0.9169421073531799, 0.8439997639348893]], [ ["TranslateY", 0.20052300197155504, 0.8202662448307549], ["Sharpness", 0.2875792108435686, 0.6997181624527842], ], [["Color", 0.10568089980973616, 0.3349467065132249], ["Brightness", 0.13070947282207768, 0.5757725013960775]], [ ["AutoContrast", 0.3749999712869779, 0.6665578760607657], ["Brightness", 0.8101178402610292, 0.23271946112218125], ], [["Color", 0.6473605933679651, 0.7903409763232029], ["ShearX", 0.588080941572581, 0.27223524148254086]], [["Cutout", 0.46293361616697304, 0.7107761001833921], ["AutoContrast", 0.3063766931658412, 0.8026114219854579]], [ ["Brightness", 0.7884854981520251, 0.5503669863113797], ["Brightness", 0.5832456158675261, 0.5840349298921661], ], [["Solarize", 0.4157539625058916, 0.9161905834309929], ["Sharpness", 0.30628197221802017, 0.5386291658995193]], [["Sharpness", 0.03329610069672856, 0.17066672983670506], ["Invert", 0.9900547302690527, 0.6276238841220477]], [["Solarize", 0.551015648982762, 0.6937104775938737], ["Color", 0.8838491591064375, 0.31596634380795385]], [ ["AutoContrast", 0.16224182418148447, 0.6068227969351896], ["Sharpness", 0.9599468096118623, 0.4885289719905087], ], [ ["TranslateY", 0.06576432526133724, 0.6899544605400214], ["Posterize", 0.2177096480169678, 0.9949164789616582], ], [["Solarize", 0.529820544480292, 0.7576047224165541], ["Sharpness", 0.027047878909321643, 0.45425231553970685]], [["Sharpness", 0.9102526010473146, 0.8311987141993857], ["Invert", 0.5191838751826638, 0.6906136644742229]], [["Solarize", 0.4762773516008588, 0.7703654263842423], ["Color", 0.8048437792602289, 0.4741523094238038]], [["Sharpness", 0.7095055508594206, 0.7047344238075169], ["Sharpness", 0.5059623654132546, 0.6127255499234886]], [ ["TranslateY", 0.02150725921966186, 0.3515764519224378], ["Posterize", 0.12482170119714735, 0.7829851754051393], ], [["Color", 0.7983830079184816, 0.6964694521670339], ["Brightness", 0.3666527856286296, 0.16093151636495978]], [ ["AutoContrast", 0.6724982375829505, 0.536777706678488], ["Sharpness", 0.43091754837597646, 0.7363240924241439], ], [["Brightness", 0.2889770401966227, 0.4556557902380539], ["Sharpness", 0.8805303296690755, 0.6262218017754902]], [["Sharpness", 0.5341939854581068, 0.6697109101429343], ["Rotate", 0.6806606655137529, 0.4896914517968317]], [ ["Sharpness", 0.5690509737059344, 0.32790632371915096], ["Posterize", 0.7951894258661069, 0.08377850335209162], ], [["Color", 0.6124132978216081, 0.5756485920709012], ["Brightness", 0.33053544654445344, 0.23321841707002083]], [["TranslateX", 0.0654795026615917, 0.5227246924310244], ["ShearX", 0.2932320531132063, 0.6732066478183716]], [["Cutout", 0.6226071187083615, 0.01009274433736012], ["ShearX", 0.7176799968189801, 0.3758780240463811]], [["Rotate", 0.18172339508029314, 0.18099184896819184], ["ShearY", 0.7862658331645667, 0.295658135767252]], [["Contrast", 0.4156099177015862, 0.7015784500878446], ["Sharpness", 0.6454135310009, 0.32335858947955287]], [["Color", 0.6215885089922037, 0.6882673235388836], ["Brightness", 0.3539881732605379, 0.39486736455795496]], [["Invert", 0.8164816716866418, 0.7238192000817796], ["Sharpness", 0.3876355847343607, 0.9870077619731956]], [["Brightness", 0.1875628712629315, 0.5068115936257], ["Sharpness", 0.8732419122060423, 0.5028019258530066]], [["Sharpness", 0.6140734993408259, 0.6458239834366959], ["Rotate", 0.5250107862824867, 0.533419456933602]], [["Sharpness", 0.5710893143725344, 0.15551651073007305], ["ShearY", 0.6548487860151722, 0.021365083044319146]], [["Color", 0.7610250354649954, 0.9084452893074055], ["Brightness", 0.6934611792619156, 0.4108071412071374]], [["ShearY", 0.07512550098923898, 0.32923768385754293], ["ShearY", 0.2559588911696498, 0.7082337365398496]], [["Cutout", 0.5401319018926146, 0.004750568603408445], ["ShearX", 0.7473354415031975, 0.34472481968368773]], [["Rotate", 0.02284154583679092, 0.1353450082435801], ["ShearY", 0.8192458031684238, 0.2811653613473772]], [["Contrast", 0.21142896718139154, 0.7230739568811746], ["Sharpness", 0.6902690582665707, 0.13488436112901683]], [["Posterize", 0.21701219600958138, 0.5900695769640687], ["Rotate", 0.7541095031505971, 0.5341162375286219]], [ ["Posterize", 0.5772853064792737, 0.45808311743269936], ["Brightness", 0.14366050177823675, 0.4644871239446629], ], [["Cutout", 0.8951718842805059, 0.4970074074310499], ["Equalize", 0.3863835903119882, 0.9986531042150006]], [["Equalize", 0.039411354473938925, 0.7475477254908457], ["Sharpness", 0.8741966378291861, 0.7304822679596362]], [["Solarize", 0.4908704265218634, 0.5160677350249471], ["Color", 0.24961813832742435, 0.09362352627360726]], [["Rotate", 7.870457075154214e-05, 0.8086950025500952], ["Solarize", 0.10200484521793163, 0.12312889222989265]], [["Contrast", 0.8052564975559727, 0.3403813036543645], ["Solarize", 0.7690158533600184, 0.8234626822018851]], [ ["AutoContrast", 0.680362728854513, 0.9415320040873628], ["TranslateY", 0.5305871824686941, 0.8030609611614028], ], [["Cutout", 0.1748050257378294, 0.06565343731910589], ["TranslateX", 0.1812738872339903, 0.6254461448344308]], [["Brightness", 0.4230502644722749, 0.3346463682905031], ["ShearX", 0.19107198973659312, 0.6715789128604919]], [["ShearX", 0.1706528684548394, 0.7816570201200446], ["TranslateX", 0.494545185948171, 0.4710810058360291]], [ ["TranslateX", 0.42356251508933324, 0.23865307292867322], ["TranslateX", 0.24407503619326745, 0.6013778508137331], ], [["AutoContrast", 0.7719512185744232, 0.3107905373009763], ["ShearY", 0.49448082925617176, 0.5777951230577671]], [["Cutout", 0.13026983827940525, 0.30120438757485657], ["Brightness", 0.8857896834516185, 0.7731541459513939]], [ ["AutoContrast", 0.6422800349197934, 0.38637401090264556], ["TranslateX", 0.25085431400995084, 0.3170642592664873], ], [["Sharpness", 0.22336654455367122, 0.4137774852324138], ["ShearY", 0.22446851054920894, 0.518341735882535]], [["Color", 0.2597579403253848, 0.7289643913060193], ["Sharpness", 0.5227416670468619, 0.9239943674030637]], [ ["Cutout", 0.6835337711563527, 0.24777620448593812], ["AutoContrast", 0.37260245353051846, 0.4840361183247263], ], [["Posterize", 0.32756602788628375, 0.21185124493743707], ["ShearX", 0.25431504951763967, 0.19585996561416225]], [ ["AutoContrast", 0.07930627591849979, 0.5719381348340309], ["AutoContrast", 0.335512380071304, 0.4208050118308541], ], [["Rotate", 0.2924360268257798, 0.5317629242879337], ["Sharpness", 0.4531050021499891, 0.4102650087199528]], [["Equalize", 0.5908862210984079, 0.468742362277498], ["Brightness", 0.08571766548550425, 0.5629320703375056]], [["Cutout", 0.52751122383816, 0.7287774744737556], ["Equalize", 0.28721628275296274, 0.8075179887475786]], [ ["AutoContrast", 0.24208377391366226, 0.34616549409607644], ["TranslateX", 0.17454707403766834, 0.5278055700078459], ], [["Brightness", 0.5511881924749478, 0.999638675514418], ["Equalize", 0.14076197797220913, 0.2573030693317552]], [["ShearX", 0.668731433926434, 0.7564253049646743], ["Color", 0.63235486543845, 0.43954436063340785]], [["ShearX", 0.40511960873276237, 0.5710419512142979], ["Contrast", 0.9256769948746423, 0.7461350716211649]], [["Cutout", 0.9995917204023061, 0.22908419326246265], ["TranslateX", 0.5440902956629469, 0.9965570051216295]], [["Color", 0.22552987172228894, 0.4514558960849747], ["Sharpness", 0.638058150559443, 0.9987829481002615]], [["Contrast", 0.5362775837534763, 0.7052133185951871], ["ShearY", 0.220369845547023, 0.7593922994775721]], [["ShearX", 0.0317785822935219, 0.775536785253455], ["TranslateX", 0.7939510227015061, 0.5355620618496535]], [["Cutout", 0.46027969917602196, 0.31561199122527517], ["Color", 0.06154066467629451, 0.5384660000729091]], [["Sharpness", 0.7205483743301113, 0.552222392539886], ["Posterize", 0.5146496404711752, 0.9224333144307473]], [["ShearX", 0.00014547730356910538, 0.3553954298642108], ["TranslateY", 0.9625736029090676, 0.57403418640424]], [["Posterize", 0.9199917903297341, 0.6690259107633706], ["Posterize", 0.0932558110217602, 0.22279303372106138]], [["Invert", 0.25401453476874863, 0.3354329544078385], ["Posterize", 0.1832673201325652, 0.4304718799821412]], [["TranslateY", 0.02084122674367607, 0.12826181437197323], ["ShearY", 0.655862534043703, 0.3838330909470975]], [["Contrast", 0.35231797644104523, 0.3379356652070079], ["Cutout", 0.19685599014304822, 0.1254328595280942]], [["Sharpness", 0.18795594984191433, 0.09488678946484895], ["ShearX", 0.33332876790679306, 0.633523782574133]], [["Cutout", 0.28267175940290246, 0.7901991550267817], ["Contrast", 0.021200195312951198, 0.4733128702798515]], [["ShearX", 0.966231043411256, 0.7700673327786812], ["TranslateX", 0.7102390777763321, 0.12161245817120675]], [["Cutout", 0.5183324259533826, 0.30766086003013055], ["Color", 0.48399078150128927, 0.4967477809069189]], [["Sharpness", 0.8160855187385873, 0.47937658961644], ["Posterize", 0.46360395447862535, 0.7685454058155061]], [["ShearX", 0.10173571421694395, 0.3987290690178754], ["TranslateY", 0.8939980277379345, 0.5669994143735713]], [ ["Posterize", 0.6768089584801844, 0.7113149244621721], ["Posterize", 0.054896856043358935, 0.3660837250743921], ], [ ["AutoContrast", 0.5915576211896306, 0.33607718177676493], ["Contrast", 0.3809408206617828, 0.5712201773913784], ], [ ["AutoContrast", 0.012321347472748323, 0.06379072432796573], ["Rotate", 0.0017964439160045656, 0.7598026295973337], ], [["Contrast", 0.6007100085192627, 0.36171972473370206], ["Invert", 0.09553573684975913, 0.12218510774295901]], [ ["AutoContrast", 0.32848604643836266, 0.2619457656206414], ["Invert", 0.27082113532501784, 0.9967965642293485], ], [ ["AutoContrast", 0.6156282120903395, 0.9422706516080884], ["Sharpness", 0.4215509247379262, 0.4063347716503587], ], [["Solarize", 0.25059210436331264, 0.7215305521159305], ["Invert", 0.1654465185253614, 0.9605851884186778]], [["AutoContrast", 0.4464438610980994, 0.685334175815482], ["Cutout", 0.24358625461158645, 0.4699066834058694]], [["Rotate", 0.5931657741857909, 0.6813978655574067], ["AutoContrast", 0.9259100547738681, 0.4903201223870492]], [["Color", 0.8203976071280751, 0.9777824466585101], ["Posterize", 0.4620669369254169, 0.2738895968716055]], [ ["Contrast", 0.13754352055786848, 0.3369433962088463], ["Posterize", 0.48371187792441916, 0.025718004361451302], ], [["Rotate", 0.5208233630704999, 0.1760188899913535], ["TranslateX", 0.49753461392937226, 0.4142935276250922]], [["Cutout", 0.5967418240931212, 0.8028675552639539], ["Cutout", 0.20021854152659121, 0.19426330549590076]], [["ShearY", 0.549583567386676, 0.6601326640171705], ["Cutout", 0.6111813470383047, 0.4141935587984994]], [ ["Brightness", 0.6354891977535064, 0.31591459747846745], ["AutoContrast", 0.7853952208711621, 0.6555861906702081], ], [["AutoContrast", 0.7333725370546154, 0.9919410576081586], ["Cutout", 0.9984177877923588, 0.2938253683694291]], [["Color", 0.33219296307742263, 0.6378995578424113], ["AutoContrast", 0.15432820754183288, 0.7897899838932103]], [["Contrast", 0.5905289460222578, 0.8158577207653422], ["Cutout", 0.3980284381203051, 0.43030531250317217]], [["TranslateX", 0.452093693346745, 0.5251475931559115], ["Rotate", 0.991422504871258, 0.4556503729269001]], [["Color", 0.04560406292983776, 0.061574671308480766], ["Brightness", 0.05161079440128734, 0.6718398142425688]], [["Contrast", 0.02913302416506853, 0.14402056093217708], ["Rotate", 0.7306930378774588, 0.47088249057922094]], [["Solarize", 0.3283072384190169, 0.82680847744367], ["Invert", 0.21632614168418854, 0.8792241691482687]], [["Equalize", 0.4860808352478527, 0.9440534949023064], ["Cutout", 0.31395897639184694, 0.41805859306017523]], [["Rotate", 0.2816043232522335, 0.5451282807926706], ["Color", 0.7388520447173302, 0.7706503658143311]], [["Color", 0.9342776719536201, 0.9039981381514299], ["Rotate", 0.6646389177840164, 0.5147917008383647]], [["Cutout", 0.08929430082050335, 0.22416445996932374], ["Posterize", 0.454485751267457, 0.500958345348237]], [["TranslateX", 0.14674201106374488, 0.7018633472428202], ["Sharpness", 0.6128796723832848, 0.743535235614809]], [["TranslateX", 0.5189900164469432, 0.6491132403587601], ["Contrast", 0.26309555778227806, 0.5976857969656114]], [["Solarize", 0.23569808291972655, 0.3315781686591778], ["ShearY", 0.07292078937544964, 0.7460326987587573]], [["ShearY", 0.7090542757477153, 0.5246437008439621], ["Sharpness", 0.9666919148538443, 0.4841687888767071]], [["Solarize", 0.3486952615189488, 0.7012877201721799], ["Invert", 0.1933387967311534, 0.9535472742828175]], [["AutoContrast", 0.5393460721514914, 0.6924005011697713], ["Cutout", 0.16988156769247176, 0.3667207571712882]], [["Rotate", 0.5815329514554719, 0.5390406879316949], ["AutoContrast", 0.7370538341589625, 0.7708822194197815]], [["Color", 0.8463701017918459, 0.9893491045831084], ["Invert", 0.06537367901579016, 0.5238468509941635]], [ ["Contrast", 0.8099771812443645, 0.39371603893945184], ["Posterize", 0.38273629875646487, 0.46493786058573966], ], [["Color", 0.11164686537114032, 0.6771450570033168], ["Posterize", 0.27921361289661406, 0.7214300893597819]], [["Contrast", 0.5958265906571906, 0.5963959447666958], ["Sharpness", 0.2640889223630885, 0.3365870842641453]], [["Color", 0.255634146724125, 0.5610029792926452], ["ShearY", 0.7476893976084721, 0.36613194760395557]], [["ShearX", 0.2167581882130063, 0.022978065071245002], ["TranslateX", 0.1686864409720319, 0.4919575435512007]], [["Solarize", 0.10702753776284957, 0.3954707963684698], ["Contrast", 0.7256100635368403, 0.48845259655719686]], [["Sharpness", 0.6165615058519549, 0.2624079463213861], ["ShearX", 0.3804820351860919, 0.4738994677544202]], [ ["TranslateX", 0.18066394808448177, 0.8174509422318228], ["Solarize", 0.07964569396290502, 0.45495935736800974], ], [["Sharpness", 0.2741884021129658, 0.9311045302358317], ["Cutout", 0.0009101326429323388, 0.5932102256756948]], [["Rotate", 0.8501796375826188, 0.5092564038282137], ["Brightness", 0.6520146983999912, 0.724091283316938]], [ ["Brightness", 0.10079744898900078, 0.7644088017429471], ["AutoContrast", 0.33540215138213575, 0.1487538541758792], ], [["ShearY", 0.10632545944757177, 0.9565164562996977], ["Rotate", 0.275833816849538, 0.6200731548023757]], [["Color", 0.6749819274397422, 0.41042188598168844], ["AutoContrast", 0.22396590966461932, 0.5048018491863738]], [["Equalize", 0.5044277111650255, 0.2649182381110667], ["Brightness", 0.35715133289571355, 0.8653260893016869]], [["Cutout", 0.49083594426355326, 0.5602781291093129], ["Posterize", 0.721795488514384, 0.5525847430754974]], [ ["Sharpness", 0.5081835448947317, 0.7453323423804428], ["TranslateX", 0.11511932212234266, 0.4337766796030984], ], [["Solarize", 0.3817050641766593, 0.6879004573473403], ["Invert", 0.0015041436267447528, 0.9793134066888262]], [["AutoContrast", 0.5107410439697935, 0.8276720355454423], ["Cutout", 0.2786270701864015, 0.43993387208414564]], [["Rotate", 0.6711202569428987, 0.6342930903972932], ["Posterize", 0.802820231163559, 0.42770002619222053]], [["Color", 0.9426854321337312, 0.9055431782458764], ["AutoContrast", 0.3556422423506799, 0.2773922428787449]], [ ["Contrast", 0.10318991257659992, 0.30841372533347416], ["Posterize", 0.4202264962677853, 0.05060395018085634], ], [["Invert", 0.549305630337048, 0.886056156681853], ["Cutout", 0.9314157033373055, 0.3485836940307909]], [["ShearX", 0.5642891775895684, 0.16427372934801418], ["Invert", 0.228741164726475, 0.5066345406806475]], [["ShearY", 0.5813123201003086, 0.33474363490586106], ["Equalize", 0.11803439432255824, 0.8583936440614798]], [["Sharpness", 0.1642809706111211, 0.6958675237301609], ["ShearY", 0.5989560762277414, 0.6194018060415276]], [["Rotate", 0.05092104774529638, 0.9358045394527796], ["Cutout", 0.6443254331615441, 0.28548414658857657]], [["Brightness", 0.6986036769232594, 0.9618046340942727], ["Sharpness", 0.5564490243465492, 0.6295231286085622]], [ ["Brightness", 0.42725649792574105, 0.17628028916784244], ["Equalize", 0.4425109360966546, 0.6392872650036018], ], [["ShearY", 0.5758622795525444, 0.8773349286588288], ["ShearX", 0.038525646435423666, 0.8755366512394268]], [["Sharpness", 0.3704459924265827, 0.9236361456197351], ["Color", 0.6379842432311235, 0.4548767717224531]], [ ["Contrast", 0.1619523824549347, 0.4506528800882731], ["AutoContrast", 0.34513874426188385, 0.3580290330996726], ], [["Contrast", 0.728699731513527, 0.6932238009822878], ["Brightness", 0.8602917375630352, 0.5341445123280423]], [["Equalize", 0.3574552353044203, 0.16814745124536548], ["Rotate", 0.24191717169379262, 0.3279497108179034]], [["ShearY", 0.8567478695576244, 0.37746117240238164], ["ShearX", 0.9654125389830487, 0.9283047610798827]], [["ShearY", 0.4339052480582405, 0.5394548246617406], ["Cutout", 0.5070570647967001, 0.7846286976687882]], [ ["AutoContrast", 0.021620100406875065, 0.44425839772845227], ["AutoContrast", 0.33978157614075183, 0.47716564815092244], ], [["Contrast", 0.9727600659025666, 0.6651758819229426], ["Brightness", 0.9893133904996626, 0.39176397622636105]], [["Equalize", 0.283428620586305, 0.18727922861893637], ["Rotate", 0.3556063466797136, 0.3722839913107821]], [["ShearY", 0.7276172841941864, 0.4834188516302227], ["ShearX", 0.010783217950465884, 0.9756458772142235]], [["ShearY", 0.2901753295101581, 0.5684700238749064], ["Cutout", 0.655585564610337, 0.9490071307790201]], [ ["AutoContrast", 0.008507193981450278, 0.4881150103902877], ["AutoContrast", 0.6561989723231185, 0.3715071329838596], ], [["Contrast", 0.7702505530948414, 0.6961371266519999], ["Brightness", 0.9953051630261895, 0.3861962467326121]], [["Equalize", 0.2805270012472756, 0.17715406116880994], ["Rotate", 0.3111256593947474, 0.15824352183820073]], [["Brightness", 0.9888680802094193, 0.4856236485253163], ["ShearX", 0.022370252047332284, 0.9284975906226682]], [["ShearY", 0.4065719044318099, 0.7468528006921563], ["AutoContrast", 0.19494427109708126, 0.8613186475174786]], [ ["AutoContrast", 0.023296727279367765, 0.9170949567425306], ["AutoContrast", 0.11663051100921168, 0.7908646792175343], ], [["AutoContrast", 0.7335191671571732, 0.4958357308292425], ["Color", 0.7964964008349845, 0.4977687544324929]], [["ShearX", 0.19905221600021472, 0.3033081933150046], ["Equalize", 0.9383410219319321, 0.3224669877230161]], [["ShearX", 0.8265450331466404, 0.6509091423603757], ["Sharpness", 0.7134181178748723, 0.6472835976443643]], [["ShearY", 0.46962439525486044, 0.223433110541722], ["Rotate", 0.7749806946212373, 0.5337060376916906]], [ ["Posterize", 0.1652499695106796, 0.04860659068586126], ["Brightness", 0.6644577712782511, 0.4144528269429337], ], [["TranslateY", 0.6220449565731829, 0.4917495676722932], ["Posterize", 0.6255000355409635, 0.8374266890984867]], [ ["AutoContrast", 0.4887160797052227, 0.7106426020530529], ["Sharpness", 0.7684218571497236, 0.43678474722954763], ], [["Invert", 0.13178101535845366, 0.8301141976359813], ["Color", 0.002820877424219378, 0.49444413062487075]], [["TranslateX", 0.9920683666478188, 0.5862245842588877], ["Posterize", 0.5536357075855376, 0.5454300367281468]], [["Brightness", 0.8150181219663427, 0.1411060258870707], ["Sharpness", 0.8548823004164599, 0.77008691072314]], [["Brightness", 0.9580478020413399, 0.7198667636628974], ["ShearY", 0.8431585033377366, 0.38750016565010803]], [["Solarize", 0.2331505347152334, 0.25754361489084787], ["TranslateY", 0.447431373734262, 0.5782399531772253]], [ ["TranslateY", 0.8904927998691309, 0.25872872455072315], ["AutoContrast", 0.7129888139716263, 0.7161603231650524], ], [["ShearY", 0.6336216800247362, 0.5247508616674911], ["Cutout", 0.9167315119726633, 0.2060557387978919]], [["ShearX", 0.001661782345968199, 0.3682225725445044], ["Solarize", 0.12303352043754572, 0.5014989548584458]], [["Brightness", 0.9723625105116246, 0.6555444729681099], ["Contrast", 0.5539208721135375, 0.7819973409318487]], [ ["Equalize", 0.3262607499912611, 0.0006745572802121513], ["Contrast", 0.35341551623767103, 0.36814689398886347], ], [["ShearY", 0.7478539900243613, 0.37322078030129185], ["TranslateX", 0.41558847793529247, 0.7394615158544118]], [["Invert", 0.13735541232529067, 0.5536403864332143], ["Cutout", 0.5109718190377135, 0.0447509485253679]], [["AutoContrast", 0.09403602327274725, 0.5909250807862687], ["ShearY", 0.53234060616395, 0.5316981359469398]], [["ShearX", 0.5651922367876323, 0.6794110241313183], ["Posterize", 0.7431624856363638, 0.7896861463783287]], [ ["Brightness", 0.30949179379286806, 0.7650569096019195], ["Sharpness", 0.5461629122105034, 0.6814369444005866], ], [["Sharpness", 0.28459340191768434, 0.7802208350806028], ["Rotate", 0.15097973114238117, 0.5259683294104645]], [["ShearX", 0.6430803693700531, 0.9333735880102375], ["Contrast", 0.7522209520030653, 0.18831747966185058]], [["Contrast", 0.4219455937915647, 0.29949769435499646], ["Color", 0.6925322933509542, 0.8095523885795443]], [ ["ShearX", 0.23553236193043048, 0.17966207900468323], ["AutoContrast", 0.9039700567886262, 0.21983629944639108], ], [["ShearX", 0.19256223146671514, 0.31200739880443584], ["Sharpness", 0.31962196883294713, 0.6828107668550425]], [["Cutout", 0.5947690279080912, 0.21728220253899178], ["Rotate", 0.6757188879871141, 0.489460599679474]], [["ShearY", 0.18365897125470526, 0.3988571115918058], ["Brightness", 0.7727489489504, 0.4790369956329955]], [["Contrast", 0.7090301084131432, 0.5178303607560537], ["ShearX", 0.16749258277688506, 0.33061773301592356]], [ ["ShearX", 0.3706690885419934, 0.38510677124319415], ["AutoContrast", 0.8288356276501032, 0.16556487668770264], ], [ ["TranslateY", 0.16758043046445614, 0.30127092823893986], ["Brightness", 0.5194636577132354, 0.6225165310621702], ], [["Cutout", 0.6087289363049726, 0.10439287037803044], ["Rotate", 0.7503452083033819, 0.7425316019981433]], [["ShearY", 0.24347189588329932, 0.5554979486672325], ["Brightness", 0.9468115239174161, 0.6132449358023568]], [["Brightness", 0.7144508395807994, 0.4610594769966929], ["ShearX", 0.16466683833092968, 0.3382903812375781]], [["Sharpness", 0.27743648684265465, 0.17200038071656915], ["Color", 0.47404262107546236, 0.7868991675614725]], [["Sharpness", 0.8603993513633618, 0.324604728411791], ["TranslateX", 0.3331597130403763, 0.9369586812977804]], [["Color", 0.1535813630595832, 0.4700116846558207], ["Color", 0.5435647971896318, 0.7639291483525243]], [ ["Brightness", 0.21486188101947656, 0.039347277341450576], ["Cutout", 0.7069526940684954, 0.39273934115015696], ], [["ShearY", 0.7267130888840517, 0.6310800726389485], ["AutoContrast", 0.662163190824139, 0.31948540372237766]], [["ShearX", 0.5123132117185981, 0.1981015909438834], ["AutoContrast", 0.9009347363863067, 0.26790399126924036]], [["Brightness", 0.24245061453231648, 0.2673478678291436], ["ShearX", 0.31707976089283946, 0.6800582845544948]], [["Cutout", 0.9257780138367764, 0.03972673526848819], ["Rotate", 0.6807858944518548, 0.46974332280612097]], [["ShearY", 0.1543443071262312, 0.6051682587030671], ["Brightness", 0.9758203119828304, 0.4941406868162414]], [["Contrast", 0.07578049236491124, 0.38953819133407647], ["ShearX", 0.20194918288164293, 0.4141510791947318]], [["Color", 0.27826402243792286, 0.43517491081531157], ["AutoContrast", 0.6159269026143263, 0.2021846783488046]], [["AutoContrast", 0.5039377966534692, 0.19241507605941105], ["Invert", 0.5563931144385394, 0.7069728937319112]], [["Sharpness", 0.19031632433810566, 0.26310171056096743], ["Color", 0.4724537593175573, 0.6715201448387876]], [["ShearY", 0.2280910467786642, 0.33340559088059313], ["ShearY", 0.8858560034869303, 0.2598627441471076]], [["ShearY", 0.07291814128021593, 0.5819462692986321], ["Cutout", 0.27605696060512147, 0.9693427371868695]], [ ["Posterize", 0.4249871586563321, 0.8256952014328607], ["Posterize", 0.005907466926447169, 0.8081353382152597], ], [["Brightness", 0.9071305290601128, 0.4781196213717954], ["Posterize", 0.8996214311439275, 0.5540717376630279]], [ ["Brightness", 0.06560728936236392, 0.9920627849065685], ["TranslateX", 0.04530789794044952, 0.5318568944702607], ], [["TranslateX", 0.6800263601084814, 0.4611536772507228], ["Rotate", 0.7245888375283157, 0.0914772551375381]], [["Sharpness", 0.879556061897963, 0.42272481462067535], ["TranslateX", 0.4600350422524085, 0.5742175429334919]], [ ["AutoContrast", 0.5005776243176145, 0.22597121331684505], ["Invert", 0.10763286370369299, 0.6841782704962373], ], [ ["Sharpness", 0.7422908472000116, 0.6850324203882405], ["TranslateX", 0.3832914614128403, 0.34798646673324896], ], [["ShearY", 0.31939465302679326, 0.8792088167639516], ["Brightness", 0.4093604352811235, 0.21055483197261338]], [ ["AutoContrast", 0.7447595860998638, 0.19280222555998586], ["TranslateY", 0.317754779431227, 0.9983454520593591], ], [["Equalize", 0.27706973689750847, 0.6447455020660622], ["Contrast", 0.5626579126863761, 0.7920049962776781]], [["Rotate", 0.13064369451773816, 0.1495367590684905], ["Sharpness", 0.24893941981801215, 0.6295943894521504]], [["ShearX", 0.6856269993063254, 0.5167938584189854], ["Sharpness", 0.24835352574609537, 0.9990550493102627]], [["AutoContrast", 0.461654115871693, 0.43097388896245004], ["Cutout", 0.366359682416437, 0.08011826474215511]], [["AutoContrast", 0.993892672935951, 0.2403608711236933], ["ShearX", 0.6620817870694181, 0.1744814077869482]], [["ShearY", 0.6396747719986443, 0.15031017143644265], ["Brightness", 0.9451954879495629, 0.26490678840264714]], [["Color", 0.19311480787397262, 0.15712300697448575], ["Posterize", 0.05391448762015258, 0.6943963643155474]], [["Sharpness", 0.6199669674684085, 0.5412492335319072], ["Invert", 0.14086213450149815, 0.2611850277919339]], [["Posterize", 0.5533129268803405, 0.5332478159319912], ["ShearX", 0.48956244029096635, 0.09223930853562916]], [["ShearY", 0.05871590849449765, 0.19549715278943228], ["TranslateY", 0.7208521362741379, 0.36414003004659434]], [["ShearY", 0.7316263417917531, 0.0629747985768501], ["Contrast", 0.036359793501448245, 0.48658745414898386]], [["Rotate", 0.3301497610942963, 0.5686622043085637], ["ShearX", 0.40581487555676843, 0.5866127743850192]], [["ShearX", 0.6679039628249283, 0.5292270693200821], ["Sharpness", 0.25901391739310703, 0.9778360586541461]], [ ["AutoContrast", 0.27373222012596854, 0.14456771405730712], ["Contrast", 0.3877220783523938, 0.7965158941894336], ], [["Solarize", 0.29440905483979096, 0.06071633809388455], ["Equalize", 0.5246736285116214, 0.37575084834661976]], [ ["TranslateY", 0.2191269464520395, 0.7444942293988484], ["Posterize", 0.3840878524812771, 0.31812671711741247], ], [ ["Solarize", 0.25159267140731356, 0.5833264622559661], ["Brightness", 0.07552262572348738, 0.33210648549288435], ], [ ["AutoContrast", 0.9770099298399954, 0.46421915310428197], ["AutoContrast", 0.04707358934642503, 0.24922048012183493], ], [["Cutout", 0.5379685806621965, 0.02038212605928355], ["Brightness", 0.5900728303717965, 0.28807872931416956]], [ ["Sharpness", 0.11596624872886108, 0.6086947716949325], ["AutoContrast", 0.34876470059667525, 0.22707897759730578], ], [["Contrast", 0.276545513135698, 0.8822580384226156], ["Rotate", 0.04874027684061846, 0.6722214281612163]], [["ShearY", 0.595839851757025, 0.4389866852785822], ["Equalize", 0.5225492356128832, 0.2735290854063459]], [["Sharpness", 0.9918029636732927, 0.9919926583216121], ["Sharpness", 0.03672376137997366, 0.5563865980047012]], [ ["AutoContrast", 0.34169589759999847, 0.16419911552645738], ["Invert", 0.32995953043129234, 0.15073174739720568], ], [ ["Posterize", 0.04600255098477292, 0.2632612790075844], ["TranslateY", 0.7852153329831825, 0.6990722310191976], ], [ ["AutoContrast", 0.4414653815356372, 0.2657468780017082], ["Posterize", 0.30647061536763337, 0.3688222724948656], ], [["Contrast", 0.4239361091421837, 0.6076562806342001], ["Cutout", 0.5780707784165284, 0.05361325256745192]], [["Sharpness", 0.7657895907855394, 0.9842407321667671], ["Sharpness", 0.5416352696151596, 0.6773681575200902]], [ ["AutoContrast", 0.13967381098331305, 0.10787258006315015], ["Posterize", 0.5019536507897069, 0.9881978222469807], ], [ ["Brightness", 0.030528346448984903, 0.31562058762552847], ["TranslateY", 0.0843808140595676, 0.21019213305350526], ], [ ["AutoContrast", 0.6934579165006736, 0.2530484168209199], ["Rotate", 0.0005751408130693636, 0.43790043943210005], ], [ ["TranslateX", 0.611258547664328, 0.25465240215894935], ["Sharpness", 0.5001446909868196, 0.36102204109889413], ], [["Contrast", 0.8995127327150193, 0.5493190695343996], ["Brightness", 0.242708780669213, 0.5461116653329015]], [ ["AutoContrast", 0.3751825351022747, 0.16845985803896962], ["Cutout", 0.25201103287363663, 0.0005893331783358435], ], [["ShearX", 0.1518985779435941, 0.14768180777304504], ["Color", 0.85133530274324, 0.4006641163378305]], [["TranslateX", 0.5489668255504668, 0.4694591826554948], ["Rotate", 0.1917354490155893, 0.39993269385802177]], [["ShearY", 0.6689267479532809, 0.34304285013663577], ["Equalize", 0.24133154048883143, 0.279324043138247]], [["Contrast", 0.3412544002099494, 0.20217358823930232], ["Color", 0.8606984790510235, 0.14305503544676373]], [["Cutout", 0.21656155695311988, 0.5240101349572595], ["Brightness", 0.14109877717636352, 0.2016827341210295]], [ ["Sharpness", 0.24764371218833872, 0.19655480259925423], ["Posterize", 0.19460398862039913, 0.4975414350200679], ], [["Brightness", 0.6071850094982323, 0.7270716448607151], ["Solarize", 0.111786402398499, 0.6325641684614275]], [ ["Contrast", 0.44772949532200856, 0.44267502710695955], ["AutoContrast", 0.360117506402693, 0.2623958228760273], ], [["Sharpness", 0.8888131688583053, 0.936897400764746], ["Sharpness", 0.16080674198274894, 0.5681119841445879]], [ ["AutoContrast", 0.8004456226590612, 0.1788600469525269], ["Brightness", 0.24832285390647374, 0.02755350284841604], ], [["ShearY", 0.06910320102646594, 0.26076407321544054], ["Contrast", 0.8633703022354964, 0.38968514704043056]], [ ["AutoContrast", 0.42306251382780613, 0.6883260271268138], ["Rotate", 0.3938724346852023, 0.16740881249086037], ], [["Contrast", 0.2725343884286728, 0.6468194318074759], ["Sharpness", 0.32238942646494745, 0.6721149242783824]], [ ["AutoContrast", 0.942093919956842, 0.14675331481712853], ["Posterize", 0.5406276708262192, 0.683901182218153], ], [["Cutout", 0.5386811894643584, 0.04498833938429728], ["Posterize", 0.17007257321724775, 0.45761177118620633]], [["Contrast", 0.13599408935104654, 0.53282738083886], ["Solarize", 0.26941667995081114, 0.20958261079465895]], [["Color", 0.6600788518606634, 0.9522228302165842], ["Invert", 0.0542722262516899, 0.5152431169321683]], [["Contrast", 0.5328934819727553, 0.2376220512388278], ["Posterize", 0.04890422575781711, 0.3182233123739474]], [["AutoContrast", 0.9289628064340965, 0.2976678437448435], ["Color", 0.20936893798507963, 0.9649612821434217]], [ ["Cutout", 0.9019423698575457, 0.24002036989728096], ["Brightness", 0.48734445615892974, 0.047660899809176316], ], [ ["Sharpness", 0.09347824275711591, 0.01358686275590612], ["Posterize", 0.9248539660538934, 0.4064232632650468], ], [["Brightness", 0.46575675383704634, 0.6280194775484345], ["Invert", 0.17276207634499413, 0.21263495428839635]], [["Brightness", 0.7238014711679732, 0.6178946027258592], ["Equalize", 0.3815496086340364, 0.07301281068847276]], [["Contrast", 0.754557393588416, 0.895332753570098], ["Color", 0.32709957750707447, 0.8425486003491515]], [ ["Rotate", 0.43406698081696576, 0.28628263254953723], ["TranslateY", 0.43949548709125374, 0.15927082198238685], ], [ ["Brightness", 0.0015838339831640708, 0.09341692553352654], ["AutoContrast", 0.9113966907329718, 0.8345900469751112], ], [["ShearY", 0.46698796308585017, 0.6150701348176804], ["Invert", 0.14894062704815722, 0.2778388046184728]], [["Color", 0.30360499169455957, 0.995713092016834], ["Contrast", 0.2597016288524961, 0.8654420870658932]], [ ["Brightness", 0.9661642031891435, 0.7322006407169436], ["TranslateY", 0.4393502786333408, 0.33934762664274265], ], [["Color", 0.9323638351992302, 0.912776309755293], ["Brightness", 0.1618274755371618, 0.23485741708056307]], [["Color", 0.2216470771158821, 0.3359240197334976], ["Sharpness", 0.6328691811471494, 0.6298393874452548]], [["Solarize", 0.4772769142265505, 0.7073470698713035], ["ShearY", 0.2656114148206966, 0.31343097010487253]], [["Solarize", 0.3839017339304234, 0.5985505779429036], ["Equalize", 0.002412059429196589, 0.06637506181196245]], [["Contrast", 0.12751196553017863, 0.46980311434237976], ["Sharpness", 0.3467487455865491, 0.4054907610444406]], [ ["AutoContrast", 0.9321813669127206, 0.31328471589533274], ["Rotate", 0.05801738717432747, 0.36035756254444273], ], [["TranslateX", 0.52092390458353, 0.5261722561643886], ["Contrast", 0.17836804476171306, 0.39354333443158535]], [ ["Posterize", 0.5458100909925713, 0.49447244994482603], ["Brightness", 0.7372536822363605, 0.5303409097463796], ], [["Solarize", 0.1913974941725724, 0.5582966653986761], ["Equalize", 0.020733669175727026, 0.9377467166472878]], [["Equalize", 0.16265732137763889, 0.5206282340874929], ["Sharpness", 0.2421533133595281, 0.506389065871883]], [["AutoContrast", 0.9787324801448523, 0.24815051941486466], ["Rotate", 0.2423487151245957, 0.6456493129745148]], [["TranslateX", 0.6809867726670327, 0.6949687002397612], ["Contrast", 0.16125673359747458, 0.7582679978218987]], [["Posterize", 0.8212000950994955, 0.5225012157831872], ["Brightness", 0.8824891856626245, 0.4499216779709508]], [["Solarize", 0.12061313332505218, 0.5319371283368052], ["Equalize", 0.04120865969945108, 0.8179402157299602]], [["Rotate", 0.11278256686005855, 0.4022686554165438], ["ShearX", 0.2983451019112792, 0.42782525461812604]], [["ShearY", 0.8847385513289983, 0.5429227024179573], ["Rotate", 0.21316428726607445, 0.6712120087528564]], [ ["TranslateX", 0.46448081241068717, 0.4746090648963252], ["Brightness", 0.19973580961271142, 0.49252862676553605], ], [ ["Posterize", 0.49664100539481526, 0.4460713166484651], ["Brightness", 0.6629559985581529, 0.35192346529003693], ], [["Color", 0.22710733249173676, 0.37943185764616194], ["ShearX", 0.015809774971472595, 0.8472080190835669]], [ ["Contrast", 0.4187366322381491, 0.21621979869256666], ["AutoContrast", 0.7631045030367304, 0.44965231251615134], ], [["Sharpness", 0.47240637876720515, 0.8080091811749525], ["Cutout", 0.2853425420104144, 0.6669811510150936]], [["Posterize", 0.7830320527127324, 0.2727062685529881], ["Solarize", 0.527834000867504, 0.20098218845222998]], [["Contrast", 0.366380535288225, 0.39766001659663075], ["Cutout", 0.8708808878088891, 0.20669525734273086]], [["ShearX", 0.6815427281122932, 0.6146858582671569], ["AutoContrast", 0.28330622372053493, 0.931352024154997]], [ ["AutoContrast", 0.8668174463154519, 0.39961453880632863], ["AutoContrast", 0.5718557712359253, 0.6337062930797239], ], [["ShearY", 0.8923152519411871, 0.02480062504737446], ["Cutout", 0.14954159341231515, 0.1422219808492364]], [["Rotate", 0.3733718175355636, 0.3861928572224287], ["Sharpness", 0.5651126520194574, 0.6091103847442831]], [ ["Posterize", 0.8891714191922857, 0.29600154265251016], ["TranslateY", 0.7865351723963945, 0.5664998548985523], ], [ ["TranslateX", 0.9298214806998273, 0.729856565052017], ["AutoContrast", 0.26349082482341846, 0.9638882609038888], ], [ ["Sharpness", 0.8387378377527128, 0.42146721129032494], ["AutoContrast", 0.9860522000876452, 0.4200699464169384], ], [["ShearY", 0.019609159303115145, 0.37197835936879514], ["Cutout", 0.22199340461754258, 0.015932573201085848]], [["Rotate", 0.43871085583928443, 0.3283504258860078], ["Sharpness", 0.6077702068037776, 0.6830305349618742]], [["Contrast", 0.6160211756538094, 0.32029451083389626], ["Cutout", 0.8037631428427006, 0.4025688837399259]], [ ["TranslateY", 0.051637820936985435, 0.6908417834391846], ["Sharpness", 0.7602756948473368, 0.4927111506643095], ], [["Rotate", 0.4973618638052235, 0.45931479729281227], ["TranslateY", 0.04701789716427618, 0.9408779705948676]], [["Rotate", 0.5214194592768602, 0.8371249272013652], ["Solarize", 0.17734812472813338, 0.045020798970228315]], [["ShearX", 0.7457999920079351, 0.19025612553075893], ["Sharpness", 0.5994846101703786, 0.5665094068864229]], [["Contrast", 0.6172655452900769, 0.7811432139704904], ["Cutout", 0.09915620454670282, 0.3963692287596121]], [ ["TranslateX", 0.2650112299235817, 0.7377261946165307], ["AutoContrast", 0.5019539734059677, 0.26905046992024506], ], [["Contrast", 0.6646299821370135, 0.41667784809592945], ["Cutout", 0.9698457154992128, 0.15429001887703997]], [["Sharpness", 0.9467079029475773, 0.44906457469098204], ["Cutout", 0.30036908747917396, 0.4766149689663106]], [["Equalize", 0.6667517691051055, 0.5014839828447363], ["Solarize", 0.4127890336820831, 0.9578274770236529]], [["Cutout", 0.6447384874120834, 0.2868806107728985], ["Cutout", 0.4800990488106021, 0.4757538246206956]], [["Solarize", 0.12560195032363236, 0.5557473475801568], ["Equalize", 0.019957161871490228, 0.5556797187823773]], [["Contrast", 0.12607637375759484, 0.4300633627435161], ["Sharpness", 0.3437273670109087, 0.40493203127714417]], [["AutoContrast", 0.884353334807183, 0.5880138314357569], ["Rotate", 0.9846032404597116, 0.3591877296622974]], [["TranslateX", 0.6862295865975581, 0.5307482119690076], ["Contrast", 0.19439251187251982, 0.3999195825722808]], [["Posterize", 0.4187641835025246, 0.5008988942651585], ["Brightness", 0.6665805605402482, 0.3853288204214253]], [ ["Posterize", 0.4507470690013903, 0.4232437206624681], ["TranslateX", 0.6054107416317659, 0.38123828040922203], ], [ ["AutoContrast", 0.29562338573283276, 0.35608605102687474], ["TranslateX", 0.909954785390274, 0.20098894888066549], ], [["Contrast", 0.6015278411777212, 0.6049140992035096], ["Cutout", 0.47178713636517855, 0.5333747244651914]], [["TranslateX", 0.490851976691112, 0.3829593925141144], ["Sharpness", 0.2716675173824095, 0.5131696240367152]], [["Posterize", 0.4190558294646337, 0.39316689077269873], ["Rotate", 0.5018526072725914, 0.295712490156129]], [ ["AutoContrast", 0.29624715560691617, 0.10937329832409388], ["Posterize", 0.8770505275992637, 0.43117765012206943], ], [["Rotate", 0.6649970092751698, 0.47767131373391974], ["ShearX", 0.6257923540490786, 0.6643337040198358]], [["Sharpness", 0.5553620705849509, 0.8467799429696928], ["Cutout", 0.9006185811918932, 0.3537270716262]], [["ShearY", 0.0007619678283789788, 0.9494591850536303], ["Invert", 0.24267733654007673, 0.7851608409575828]], [["Contrast", 0.9730916198112872, 0.404670123321921], ["Sharpness", 0.5923587793251186, 0.7405792404430281]], [["Cutout", 0.07393909593373034, 0.44569630026328344], ["TranslateX", 0.2460593252211425, 0.4817527814541055]], [["Brightness", 0.31058654119340867, 0.7043749950260936], ["ShearX", 0.7632161538947713, 0.8043681264908555]], [["AutoContrast", 0.4352334371415373, 0.6377550087204297], ["Rotate", 0.2892714673415678, 0.49521052050510556]], [["Equalize", 0.509071051375276, 0.7352913414974414], ["ShearX", 0.5099959429711828, 0.7071566714593619]], [["Posterize", 0.9540506532512889, 0.8498853304461906], ["ShearY", 0.28199061357155397, 0.3161715627214629]], [["Posterize", 0.6740855359097433, 0.684004694936616], ["Posterize", 0.6816720350737863, 0.9654766942980918]], [["Solarize", 0.7149344531717328, 0.42212789795181643], ["Brightness", 0.686601460864528, 0.4263050070610551]], [["Cutout", 0.49577164991501, 0.08394890892056037], ["Rotate", 0.5810369852730606, 0.3320732965776973]], [ ["TranslateY", 0.1793755480490623, 0.6006520265468684], ["Brightness", 0.3769016576438939, 0.7190746300828186], ], [ ["TranslateX", 0.7226363597757153, 0.3847027238123509], ["Brightness", 0.7641713191794035, 0.36234003077512544], ], [ ["TranslateY", 0.1211227055347106, 0.6693523474608023], ["Brightness", 0.13011180247738063, 0.5126647617294864], ], [ ["Equalize", 0.1501070550869129, 0.0038548909451806557], ["Posterize", 0.8266535939653881, 0.5502199643499207], ], [["Sharpness", 0.550624117428359, 0.2023044586648523], ["Brightness", 0.06291556314780017, 0.7832635398703937]], [["Color", 0.3701578205508141, 0.9051537973590863], ["Contrast", 0.5763972727739397, 0.4905511239739898]], [["Rotate", 0.7678527224046323, 0.6723066265307555], ["Solarize", 0.31458533097383207, 0.38329324335154524]], [["Brightness", 0.292050127929522, 0.7047582807953063], ["ShearX", 0.040541891910333805, 0.06639328601282746]], [["TranslateY", 0.4293891393238555, 0.6608516902234284], ["Sharpness", 0.7794685477624004, 0.5168044063408147]], [["Color", 0.3682450402286552, 0.17274523597220048], ["ShearY", 0.3936056470397763, 0.5702597289866161]], [["Equalize", 0.43436990310624657, 0.9207072627823626], ["Contrast", 0.7608688260846083, 0.4759023148841439]], [["Brightness", 0.7926088966143935, 0.8270093925674497], ["ShearY", 0.4924174064969461, 0.47424347505831244]], [["Contrast", 0.043917555279430476, 0.15861903591675125], ["ShearX", 0.30439480405505853, 0.1682659341098064]], [["TranslateY", 0.5598255583454538, 0.721352536005039], ["Posterize", 0.9700921973303752, 0.6882015184440126]], [ ["AutoContrast", 0.3620887415037668, 0.5958176322317132], ["TranslateX", 0.14213781552733287, 0.6230799786459947], ], [["Color", 0.490366889723972, 0.9863152892045195], ["Color", 0.817792262022319, 0.6755656429452775]], [["Brightness", 0.7030707021937771, 0.254633187122679], ["Color", 0.13977318232688843, 0.16378180123959793]], [["AutoContrast", 0.2933247831326118, 0.6283663376211102], ["Sharpness", 0.85430478154147, 0.9753613184208796]], [["Rotate", 0.6674299955457268, 0.48571208708018976], ["Contrast", 0.47491370175907016, 0.6401079552479657]], [ ["Sharpness", 0.37589579644127863, 0.8475131989077025], ["TranslateY", 0.9985149867598191, 0.057815729375099975], ], [["Equalize", 0.0017194373841596389, 0.7888361311461602], ["Contrast", 0.6779293670669408, 0.796851411454113]], [ ["TranslateY", 0.3296782119072306, 0.39765117357271834], ["Sharpness", 0.5890554357001884, 0.6318339473765834], ], [["Posterize", 0.25423810893163856, 0.5400430289894207], ["Sharpness", 0.9273643918988342, 0.6480913470982622]], [["Cutout", 0.850219975768305, 0.4169812455601289], ["Solarize", 0.5418755745870089, 0.5679666650495466]], [ ["Brightness", 0.008881361977310959, 0.9282562314720516], ["TranslateY", 0.7736066471553994, 0.20041167606029642], ], [ ["Brightness", 0.05382537581401925, 0.6405265501035952], ["Contrast", 0.30484329473639593, 0.5449338155734242], ], [["Color", 0.613257119787967, 0.4541503912724138], ["Brightness", 0.9061572524724674, 0.4030159294447347]], [ ["Brightness", 0.02739111568942537, 0.006028056532326534], ["ShearX", 0.17276751958646486, 0.05967365780621859], ], [["TranslateY", 0.4376298213047888, 0.7691816164456199], ["Sharpness", 0.8162292718857824, 0.6054926462265117]], [["Color", 0.37963069679121214, 0.5946919433483344], ["Posterize", 0.08485417284005387, 0.5663580913231766]], [["Equalize", 0.49785780226818316, 0.9999137109183761], ["Sharpness", 0.7685879484682496, 0.6260846154212211]], [ ["AutoContrast", 0.4190931409670763, 0.2374852525139795], ["Posterize", 0.8797422264608563, 0.3184738541692057], ], [["Rotate", 0.7307269024632872, 0.41523609600701106], ["ShearX", 0.6166685870692289, 0.647133807748274]], [["Sharpness", 0.5633713231039904, 0.8276694754755876], ["Cutout", 0.8329340776895764, 0.42656043027424073]], [["ShearY", 0.14934828370884312, 0.8622510773680372], ["Invert", 0.25925989086863277, 0.8813283584888576]], [["Contrast", 0.9457071292265932, 0.43228655518614034], ["Sharpness", 0.8485316947644338, 0.7590298998732413]], [["AutoContrast", 0.8386103589399184, 0.5859583131318076], ["Solarize", 0.466758711343543, 0.9956215363818983]], [["Rotate", 0.9387133710926467, 0.19180564509396503], ["Rotate", 0.5558247609706255, 0.04321698692007105]], [["ShearX", 0.3608716600695567, 0.15206159451532864], ["TranslateX", 0.47295292905710146, 0.5290760596129888]], [ ["TranslateX", 0.8357685981547495, 0.5991305115727084], ["Posterize", 0.5362929404188211, 0.34398525441943373], ], [["ShearY", 0.6751984031632811, 0.6066293622133011], ["Contrast", 0.4122723990263818, 0.4062467515095566]], [["Color", 0.7515349936021702, 0.5122124665429213], ["Contrast", 0.03190514292904123, 0.22903520154660545]], [ ["Contrast", 0.5448962625054385, 0.38655673938910545], ["AutoContrast", 0.4867400684894492, 0.3433111101096984], ], [["Rotate", 0.0008372434310827959, 0.28599951781141714], ["Equalize", 0.37113686925530087, 0.5243929348114981]], [["Color", 0.720054993488857, 0.2010177651701808], ["TranslateX", 0.23036196506059398, 0.11152764304368781]], [["Cutout", 0.859134208332423, 0.6727345740185254], ["ShearY", 0.02159833505865088, 0.46390076266538544]], [["Sharpness", 0.3428232157391428, 0.4067874527486514], ["Brightness", 0.5409415136577347, 0.3698432231874003]], [["Solarize", 0.27303978936454776, 0.9832186173589548], ["ShearY", 0.08831127213044043, 0.4681870331149774]], [ ["TranslateY", 0.2909309268736869, 0.4059460811623174], ["Sharpness", 0.6425125139803729, 0.20275737203293587], ], [["Contrast", 0.32167626214661627, 0.28636162794046977], ["Invert", 0.4712405253509603, 0.7934644799163176]], [["Color", 0.867993060896951, 0.96574321666213], ["Color", 0.02233897320328512, 0.44478933557303063]], [["AutoContrast", 0.1841254751814967, 0.2779992148017741], ["Color", 0.3586283093530607, 0.3696246850445087]], [["Posterize", 0.2052935984046965, 0.16796913860308244], ["ShearX", 0.4807226832843722, 0.11296747254563266]], [["Cutout", 0.2016411266364791, 0.2765295444084803], ["Brightness", 0.3054112810424313, 0.695924264931216]], [["Rotate", 0.8405872184910479, 0.5434142541450815], ["Cutout", 0.4493615138203356, 0.893453735250007]], [["Contrast", 0.8433310507685494, 0.4915423577963278], ["ShearX", 0.22567799557913246, 0.20129892537008834]], [["Contrast", 0.045954277103674224, 0.5043900167190442], ["Cutout", 0.5552992473054611, 0.14436447810888237]], [ ["AutoContrast", 0.7719296115130478, 0.4440417544621306], ["Sharpness", 0.13992809206158283, 0.7988278670709781], ], [["Color", 0.7838574233513952, 0.5971351401625151], ["TranslateY", 0.13562290583925385, 0.2253039635819158]], [["Cutout", 0.24870301109385806, 0.6937886690381568], ["TranslateY", 0.4033400068952813, 0.06253378991880915]], [ ["TranslateX", 0.0036059390486775644, 0.5234723884081843], ["Solarize", 0.42724862530733526, 0.8697702564187633], ], [["Equalize", 0.5446026737834311, 0.9367992979112202], ["ShearY", 0.5943478903735789, 0.42345889214100046]], [["ShearX", 0.18611885697957506, 0.7320849092947314], ["ShearX", 0.3796416430900566, 0.03817761920009881]], [ ["Posterize", 0.37636778506979124, 0.26807924785236537], ["Brightness", 0.4317372554383255, 0.5473346211870932], ], [ ["Brightness", 0.8100436240916665, 0.3817612088285007], ["Brightness", 0.4193974619003253, 0.9685902764026623], ], [["Contrast", 0.701776402197012, 0.6612786008858009], ["Color", 0.19882787177960912, 0.17275597188875483]], [["Color", 0.9538303302832989, 0.48362384535228686], ["ShearY", 0.2179980837345602, 0.37027290936457313]], [["TranslateY", 0.6068028691503798, 0.3919346523454841], ["Cutout", 0.8228303342563138, 0.18372280287814613]], [["Equalize", 0.016416758802906828, 0.642838949194916], ["Cutout", 0.5761717838655257, 0.7600661153497648]], [["Color", 0.9417761826818639, 0.9916074035986558], ["Equalize", 0.2524209308597042, 0.6373703468715077]], [["Brightness", 0.75512589439513, 0.6155072321007569], ["Contrast", 0.32413476940254515, 0.4194739830159837]], [ ["Sharpness", 0.3339450765586968, 0.9973297539194967], ["AutoContrast", 0.6523930242124429, 0.1053482471037186], ], [["ShearX", 0.2961391955838801, 0.9870036064904368], ["ShearY", 0.18705025965909403, 0.4550895821154484]], [ ["TranslateY", 0.36956447983807883, 0.36371471767143543], ["Sharpness", 0.6860051967688487, 0.2850190720087796], ], [["Cutout", 0.13017742151902967, 0.47316674150067195], ["Invert", 0.28923829959551883, 0.9295585654924601]], [["Contrast", 0.7302368472279086, 0.7178974949876642], ["TranslateY", 0.12589674152030433, 0.7485392909494947]], [["Color", 0.6474693117772619, 0.5518269515590674], ["Contrast", 0.24643004970708016, 0.3435581358079418]], [["Contrast", 0.5650327855750835, 0.4843031798040887], ["Brightness", 0.3526684005761239, 0.3005305004600969]], [["Rotate", 0.09822284968122225, 0.13172798244520356], ["Equalize", 0.38135066977857157, 0.5135129123554154]], [["Contrast", 0.5902590645585712, 0.2196062383730596], ["ShearY", 0.14188379126120954, 0.1582612142182743]], [["Cutout", 0.8529913814417812, 0.89734031211874], ["Color", 0.07293767043078672, 0.32577659205278897]], [["Equalize", 0.21401668971453247, 0.040015259500028266], ["ShearY", 0.5126400895338797, 0.4726484828276388]], [["Brightness", 0.8269430025954498, 0.9678362841865166], ["ShearY", 0.17142069814830432, 0.4726727848289514]], [["Brightness", 0.699707089334018, 0.2795501395789335], ["ShearX", 0.5308818178242845, 0.10581814221896294]], [ ["Equalize", 0.32519644258946145, 0.15763390340309183], ["TranslateX", 0.6149090364414208, 0.7454832565718259], ], [ ["AutoContrast", 0.5404508567155423, 0.7472387762067986], ["Equalize", 0.05649876539221024, 0.5628180219887216], ], ] return p def fa_reduced_svhn(): p = [ [["TranslateX", 0.001576965129744562, 0.43180488809874773], ["Invert", 0.7395307279252639, 0.7538444307982558]], [ ["Contrast", 0.5762062225409211, 0.7532431872873473], ["TranslateX", 0.45212523461624615, 0.02451684483019846], ], [["Contrast", 0.18962433143225088, 0.29481185671147325], ["Contrast", 0.9998112218299271, 0.813015355163255]], [ ["Posterize", 0.9633391295905683, 0.4136786222304747], ["TranslateY", 0.8011655496664203, 0.44102126789970797], ], [["Color", 0.8231185187716968, 0.4171602946893402], ["TranslateX", 0.8684965619113907, 0.36514568324909674]], [["Color", 0.904075230324581, 0.46319140331093767], ["Contrast", 0.4115196534764559, 0.7773329158740563]], [["Sharpness", 0.6600262774093967, 0.8045637700026345], ["TranslateY", 0.5917663766021198, 0.6844241908520602]], [ ["AutoContrast", 0.16223989311434306, 0.48169653554195924], ["ShearX", 0.5433173232860344, 0.7460278151912152], ], [["ShearX", 0.4913604762760715, 0.83391837859561], ["Color", 0.5580367056511908, 0.2961512691312932]], [["Color", 0.18567091721211237, 0.9296983204905286], ["Cutout", 0.6074026199060156, 0.03303273406448193]], [["Invert", 0.8049054771963224, 0.1340792344927909], ["Color", 0.4208839940504979, 0.7096454840962345]], [["ShearX", 0.7997786664546294, 0.6492629575700173], ["AutoContrast", 0.3142777134084793, 0.6526010594925064]], [["TranslateX", 0.2581027144644976, 0.6997433332894101], ["Rotate", 0.45490480973606834, 0.238620570022944]], [["Solarize", 0.837397161027719, 0.9311141273136286], ["Contrast", 0.640364826293148, 0.6299761518677469]], [ ["Brightness", 0.3782457347141744, 0.7085036717054278], ["Brightness", 0.5346150083208507, 0.5858930737867671], ], [["Invert", 0.48780391510474086, 0.610086407879722], ["Color", 0.5601999247616932, 0.5393836220423195]], [ ["Brightness", 0.00250086643283564, 0.5003355864896979], ["Brightness", 0.003922153283353616, 0.41107110154584925], ], [["TranslateX", 0.4073069009685957, 0.9843435292693372], ["Invert", 0.38837085318721926, 0.9298542033875989]], [["ShearY", 0.05479740443795811, 0.9113983424872698], ["AutoContrast", 0.2181108114232728, 0.713996037012164]], [["Brightness", 0.27747508429413903, 0.3217467607288693], ["ShearX", 0.02715239061946995, 0.5430731635396449]], [ ["Sharpness", 0.08994432959374538, 0.004706443546453831], ["Posterize", 0.10768206853226996, 0.39020299239900236], ], [["Cutout", 0.37498679037853905, 0.20784809761469553], ["Color", 0.9825516352194511, 0.7654155662756019]], [["Color", 0.8899349124453552, 0.7797700766409008], ["Rotate", 0.1370222187174981, 0.2622119295138398]], [["Cutout", 0.7088223332663685, 0.7884456023190028], ["Solarize", 0.5362257505160836, 0.6426837537811545]], [["Invert", 0.15686225694987552, 0.5500563899117913], ["Rotate", 0.16315224193260078, 0.4246854030170752]], [["Rotate", 0.005266247922433631, 0.06612026206223394], ["Contrast", 0.06494357829209037, 0.2738420319474947]], [["Cutout", 0.30200619566806275, 0.06558008068236942], ["Rotate", 0.2168576483823022, 0.878645566986328]], [["Color", 0.6358930679444622, 0.613404714161498], ["Rotate", 0.08733206733004326, 0.4348276574435751]], [["Cutout", 0.8834634887239585, 0.0006853845293474659], ["Solarize", 0.38132051231951847, 0.42558752668491195]], [["ShearY", 0.08830136548479937, 0.5522438878371283], ["Brightness", 0.23816560427834074, 0.3033709051157141]], [["Solarize", 0.9015331490756151, 0.9108788708847556], ["Contrast", 0.2057898014670072, 0.03260096030427456]], [["Equalize", 0.9455978685121174, 0.14850077333434056], ["TranslateY", 0.6888705996522545, 0.5300565492007543]], [["Cutout", 0.16942673959343585, 0.7294197201361826], ["TranslateX", 0.41184830642301534, 0.7060207449376135]], [["Color", 0.30133344118702166, 0.24384417956342314], ["Sharpness", 0.4640904544421743, 0.32431840288061864]], [["Sharpness", 0.5195055033472676, 0.9386677467005835], ["Color", 0.9536519432978372, 0.9624043444556467]], [["Rotate", 0.8689597230556101, 0.23955490826730633], ["Contrast", 0.050071600927462656, 0.1309891556004179]], [["Cutout", 0.5349421090878962, 0.08239510727779054], ["Rotate", 0.46064964710717216, 0.9037689320897339]], [ ["AutoContrast", 0.5625256909986802, 0.5358003783186498], ["Equalize", 0.09204330691163354, 0.4386906784850649], ], [ ["ShearX", 0.0011061172864470226, 0.07150284682189278], ["AutoContrast", 0.6015956946553209, 0.4375362295530898], ], [["ShearY", 0.25294276499800983, 0.7937560397859562], ["Brightness", 0.30834103299704474, 0.21960258701547009]], [["Posterize", 0.7423948904688074, 0.4598609935109695], ["Rotate", 0.5510348811675979, 0.26763724868985933]], [["TranslateY", 0.3208729319318745, 0.945513054853888], ["ShearX", 0.4916473963030882, 0.8743840560039451]], [["ShearY", 0.7557718687011286, 0.3125397104722828], ["Cutout", 0.5565359791865849, 0.5151359251135629]], [ ["AutoContrast", 0.16652786355571275, 0.1101575800958632], ["Rotate", 0.05108851703032641, 0.2612966401802814], ], [["Brightness", 0.380296489835016, 0.0428162454174662], ["ShearX", 0.3911934083168285, 0.18933607362790178]], [["Color", 0.002476250465397678, 0.07795275305347571], ["Posterize", 0.08131841266654188, 0.14843363184306413]], [["Cutout", 0.36664558716104434, 0.20904484995063996], ["Cutout", 0.07986452057223141, 0.9287747671053432]], [["Color", 0.9296812469919231, 0.6634239915141935], ["Rotate", 0.07632463573240006, 0.408624029443747]], [["Cutout", 0.7594470171961278, 0.9834672124229463], ["Solarize", 0.4471371303745053, 0.5751101102286562]], [ ["Posterize", 0.051186719734032285, 0.5110941294710823], ["Sharpness", 0.040432522797391596, 0.42652298706992164], ], [ ["Sharpness", 0.2645335264327221, 0.8844553189835457], ["Brightness", 0.7229600357932696, 0.16660749270785696], ], [["Sharpness", 0.6296376086802589, 0.15564989758083458], ["Sharpness", 0.7913410481400365, 0.7022615408082826]], [["Cutout", 0.5517247347343883, 0.43794888517764674], ["ShearX", 0.6951051782530201, 0.6230992857867065]], [["ShearX", 0.9015708556331022, 0.6322135168527783], ["Contrast", 0.4285629283441831, 0.18158321019502988]], [["Brightness", 0.9014292329524769, 0.3660463325457713], ["Invert", 0.6700729097206592, 0.16502732071917703]], [["AutoContrast", 0.6432764477303431, 0.9998909112400834], ["Invert", 0.8124063975545761, 0.8149683327882365]], [["Cutout", 0.6023944009428617, 0.9630976951918225], ["ShearX", 0.2734723568803071, 0.3080911542121765]], [ ["Sharpness", 0.048949115014412806, 0.44497866256845164], ["Brightness", 0.5611832867244329, 0.12994217480426257], ], [["TranslateY", 0.4619112333002525, 0.47317728091588396], ["Solarize", 0.618638784910472, 0.9508297099190338]], [["Sharpness", 0.9656274391147018, 0.3402622993963962], ["Cutout", 0.8452511174508919, 0.3094717093312621]], [["ShearX", 0.04942201651478659, 0.6910568465705691], ["AutoContrast", 0.7155342517619936, 0.8565418847743523]], [ ["Brightness", 0.5222290590721783, 0.6462675303633422], ["Sharpness", 0.7756317511341633, 0.05010730683866704], ], [["Contrast", 0.17098396012942796, 0.9128908626236187], ["TranslateY", 0.1523815376677518, 0.4269909829886339]], [["Cutout", 0.7679024720089866, 0.22229116396644455], ["Sharpness", 0.47714827844878843, 0.8242815864830401]], [["Brightness", 0.9321772357292445, 0.11339758604001371], ["Invert", 0.7021078495093375, 0.27507749184928154]], [["ShearY", 0.7069449324510433, 0.07262757954730437], ["Cutout", 0.6298690227159313, 0.8866813664859028]], [["ShearX", 0.8153137620199989, 0.8478194179953927], ["ShearX", 0.7519451353411938, 0.3914579556959725]], [["Cutout", 0.07152574469472753, 0.2629935229222503], ["TranslateX", 0.43728405510089485, 0.2610201002449789]], [["AutoContrast", 0.5824529633013098, 0.5619551536261955], ["Rotate", 0.45434137552116965, 0.7567169855140041]], [["TranslateY", 0.9338431187142137, 0.14230481341042783], ["Cutout", 0.744797723251028, 0.4346601666787713]], [["ShearX", 0.3197252560289169, 0.8770408070016171], ["Color", 0.7657013088540465, 0.2685586719812284]], [["ShearY", 0.6542181749801549, 0.8148188744344297], ["Sharpness", 0.5108985661436543, 0.9926016115463769]], [["ShearY", 0.39218730620135694, 0.857769946478945], ["Color", 0.39588355914920886, 0.9910530523789284]], [["Invert", 0.4993610396803735, 0.08449723470758526], ["TranslateX", 0.46267456928508305, 0.46691125646493964]], [["Equalize", 0.8640576819821256, 0.3973808869887604], ["ShearY", 0.5491163877063172, 0.422429328786161]], [["Contrast", 0.6146206387722841, 0.8453559854684094], ["TranslateX", 0.7974333014574718, 0.47395476786951773]], [["Contrast", 0.6828704722015236, 0.6952755697785722], ["Brightness", 0.7903069452567497, 0.8350915035109574]], [["Rotate", 0.1211091761531299, 0.9667702562228727], ["Color", 0.47888534537103344, 0.8298620028065332]], [["Equalize", 0.20009722872711086, 0.21851235854853018], ["Invert", 0.4433641154198673, 0.41902203581091935]], [ ["AutoContrast", 0.6333190204577053, 0.23965630032835372], ["Color", 0.38651217030044804, 0.06447323778198723], ], [["Brightness", 0.378274337541471, 0.5482593116308322], ["Cutout", 0.4856574442608347, 0.8889688535495244]], [["Rotate", 0.8201259323479384, 0.7404525573938633], ["Color", 0.28371236449364595, 0.7866003515933161]], [ ["Brightness", 0.10053196350009105, 0.18814037089411267], ["Sharpness", 0.5572102497672569, 0.04458217557977126], ], [ ["AutoContrast", 0.6445330112376135, 0.48082049184921843], ["TranslateY", 0.378898917914949, 0.9338102625289362], ], [ ["AutoContrast", 0.08482623401924708, 0.25199930695784384], ["Solarize", 0.5981823550521426, 0.19626357596662092], ], [ ["Solarize", 0.4373030803918095, 0.22907881245285625], ["AutoContrast", 0.6383084635487905, 0.29517603235993883], ], [ ["AutoContrast", 0.922112624726991, 0.29398098144910145], ["AutoContrast", 0.8550184811514672, 0.8030331582292343], ], [["ShearX", 0.38761582800913896, 0.06304125015084923], ["Contrast", 0.3225758804984975, 0.7089696696094797]], [["TranslateY", 0.27499498563849206, 0.1917583097241206], ["Color", 0.5845853711746438, 0.5353520071667661]], [["ShearY", 0.530881951424285, 0.47961248148116453], ["ShearX", 0.04666387744533289, 0.275772822690165]], [ ["Solarize", 0.5727309318844802, 0.02889734544563341], ["AutoContrast", 0.638852434854615, 0.9819440776921611], ], [ ["AutoContrast", 0.9766868312173507, 0.9651796447738792], ["AutoContrast", 0.3489760216898085, 0.3082182741354106], ], [ ["Sharpness", 0.13693510871346704, 0.08297205456926067], ["Contrast", 0.3155812019005854, 0.031402991638917896], ], [["TranslateY", 0.2664707540547008, 0.4838091910041236], ["ShearX", 0.5935665395229432, 0.7813088248538167]], [["ShearY", 0.7578577752251343, 0.5116014090216161], ["ShearX", 0.8332831240873545, 0.26781876290841017]], [["TranslateY", 0.473254381651761, 0.4203181582821155], ["ShearY", 0.732848696900726, 0.47895514793728433]], [["Solarize", 0.6922689176672292, 0.36403255869823725], ["AutoContrast", 0.910654040826914, 0.888651414068326]], [["ShearX", 0.37326536936166244, 0.47830923320699525], ["Equalize", 0.4724702976076929, 0.8176108279939023]], [["Contrast", 0.3839906424759326, 0.09109695563933692], ["Invert", 0.36305435543972325, 0.5701589223795499]], [["Invert", 0.5175591137387999, 0.38815675919253867], ["TranslateY", 0.1354848160153554, 0.41734106283245065]], [["Color", 0.829616006981199, 0.18631472346156963], ["Color", 0.2465115448326214, 0.9439365672808333]], [["Contrast", 0.18207939197942158, 0.39841173152850873], ["ShearX", 0.16723588254695632, 0.2868649619006758]], [["Posterize", 0.1941909136988733, 0.6322499882557473], ["Contrast", 0.6109060391509794, 0.27329598688783296]], [ ["AutoContrast", 0.9148775146158022, 0.09129288311923844], ["Sharpness", 0.4222442287436423, 0.847961820057229], ], [["Color", 0.21084007475489852, 0.008218056412554131], ["Contrast", 0.43996934555301637, 0.500680146508504]], [["ShearY", 0.6745287915240038, 0.6120305524405164], ["Equalize", 0.467403794543269, 0.2207148995882467]], [["Color", 0.7712823974371379, 0.2839161885566902], ["Color", 0.8725368489709752, 0.3349470222415115]], [["Solarize", 0.5563976601161562, 0.540446614847802], ["Invert", 0.14228071175107454, 0.2242332811481905]], [["Contrast", 0.34596757983998383, 0.9158971503395041], ["Cutout", 0.6823724203724072, 0.5221518922863516]], [["Posterize", 0.3275475232882672, 0.6520033254468702], ["Color", 0.7434224109271398, 0.0824308188060544]], [["Cutout", 0.7295122229650082, 0.277887573018184], ["Brightness", 0.5303655506515258, 0.28628046739964497]], [["Color", 0.8533293996815943, 0.24909788223027743], ["Color", 0.6915962825167857, 0.33592561040195834]], [["TranslateX", 0.0761441550001345, 0.7043906245420134], ["Equalize", 0.670845297717783, 0.30986063097084215]], [["Contrast", 0.30592723366237995, 0.7365013059287382], ["Color", 0.6173835128817455, 0.6417028717640598]], [["Rotate", 0.05558240682703821, 0.7284722849011761], ["Color", 0.7814801133853666, 0.13335113981884217]], [["ShearY", 0.6521743070190724, 0.6272195913574455], ["Rotate", 0.36278432239870423, 0.2335623679787695]], [["Color", 0.6799351102482663, 0.3850250771244986], ["Brightness", 0.613901077818094, 0.2374900558949702]], [["Color", 0.551451255148252, 0.7284757153447965], ["Solarize", 0.4863815212982878, 0.3857941567681324]], [["Contrast", 0.32516343965159267, 0.689921852601276], ["Cutout", 0.5922142001124506, 0.7709605594115009]], [ ["Brightness", 0.23760063764495856, 0.6392077018854179], ["Brightness", 0.7288124083714078, 0.4487520490201095], ], [["Sharpness", 0.5631112298553713, 0.6803534985114782], ["ShearX", 0.6743791169050775, 0.34039227245151127]], [["AutoContrast", 0.8260911840078349, 0.7705607269534767], ["Rotate", 0.8880749478363638, 0.8182460047684648]], [["ShearY", 0.7037620764408412, 0.5219573160970589], ["Posterize", 0.7186150466761102, 0.6187857686944253]], [ ["TranslateY", 0.2140494926702246, 0.9104233882669488], ["TranslateX", 0.4096039512896902, 0.9692703030784571], ], [ ["Equalize", 0.5404313549028165, 0.04094078980738014], ["AutoContrast", 0.07870278300673744, 0.841020779977939], ], [["ShearY", 0.2684638876128488, 0.5599793678740521], ["Cutout", 0.19537995362704022, 0.2400995206366768]], [ ["AutoContrast", 0.19366394417090382, 0.4130755503251951], ["Sharpness", 0.11735660606190662, 0.39276612830651914], ], [["Cutout", 0.8313266945081518, 0.37171822186374703], ["Contrast", 0.5088549187459019, 0.2956405118511817]], [["Cutout", 0.28375485371479847, 0.37020183949342683], ["Posterize", 0.718761436947423, 0.2278804627251678]], [["ShearY", 0.6625840735667625, 0.5045065697748213], ["Rotate", 0.5175257698523389, 0.39496923901188824]], [["Color", 0.6498154010188212, 0.38674158604408604], ["Brightness", 0.8157804892728057, 0.05660118670560971]], [["Color", 0.5512855420254102, 0.7812054820692542], ["Solarize", 0.8851292984174468, 0.2808951606943277]], [["Contrast", 0.35258433539074363, 0.8085377169629859], ["Cutout", 0.5197965849563265, 0.8657111726930974]], [["Cutout", 0.23650925054419358, 0.746860862983295], ["Brightness", 0.8842190203336139, 0.4389347348156118]], [["Rotate", 0.8651460526861932, 0.0031372441327392753], ["Equalize", 0.3909498933963822, 0.6221687914603954]], [["TranslateX", 0.5793690303540427, 0.37939687327382987], ["Invert", 0.846172545690258, 0.36950442052945853]], [["Invert", 0.5151721602607067, 0.5860134277259832], ["Contrast", 0.6868708526377458, 0.2188104093363727]], [["Contrast", 0.28019632529718025, 0.8403553410328943], ["Cutout", 0.5238340355491738, 0.6948434115725599]], [["Rotate", 0.1592592617684533, 0.5212044951482974], ["Color", 0.42404215473874546, 0.45894052919059103]], [ ["AutoContrast", 0.21780978427851283, 0.11813011387113281], ["Contrast", 0.14557770349869537, 0.5468616480449002], ], [["Cutout", 0.03573873600256905, 0.8747186430368771], ["AutoContrast", 0.4804465018567564, 0.3968185812087325]], [ ["ShearY", 0.027192162947493492, 0.35923750027515866], ["Sharpness", 0.03207302705814674, 0.25868625346023777], ], [ ["AutoContrast", 0.9111793886013045, 0.33534571661592005], ["ShearY", 0.31365410004768934, 0.37055495208177025], ], [["Color", 0.5119732811716222, 0.10635303813092001], ["Solarize", 0.9828759703639677, 0.33302532900783466]], [["Contrast", 0.9652840964645487, 0.9550826002089741], ["ShearY", 0.16934262075572262, 0.35893022906919625]], [["Invert", 0.21526903298837538, 0.5491812432380025], ["TranslateX", 0.27691575128765095, 0.9916365493500338]], [ ["AutoContrast", 0.7223428288831728, 0.3001506080569529], ["Posterize", 0.28280773693692957, 0.5630226986948541], ], [ ["TranslateY", 0.5334698670580152, 0.4329627064903895], ["Solarize", 0.11621274404555687, 0.38564564358937725], ], [["Brightness", 0.9001900081991266, 0.15453762529292236], ["Equalize", 0.6749827304986464, 0.2174408558291521]], [["TranslateY", 0.703293071780793, 0.20371204513522137], ["Invert", 0.7921926919880306, 0.2647654009616249]], [["AutoContrast", 0.32650519442680254, 0.5567514700913352], ["ShearY", 0.7627653627354407, 0.5363510886152073]], [["Rotate", 0.364293676091047, 0.4262321334071656], ["Posterize", 0.7284189361001443, 0.6052618047275847]], [["Contrast", 0.004679138490284229, 0.6985327823420937], ["Posterize", 0.25412559986607497, 0.969098825421215]], [["ShearY", 0.6831738973100172, 0.6916463366962687], ["TranslateY", 0.8744153159733203, 0.3667879549647143]], [ ["Posterize", 0.39138456188265913, 0.8617909225610128], ["TranslateX", 0.5198303654364824, 0.5518823068009463], ], [["Invert", 0.6471155996761706, 0.4793957129423701], ["ShearX", 0.8046274258703997, 0.9711394307595065]], [["Solarize", 0.2442520851809611, 0.5518114414771629], ["Sharpness", 0.02324109511463257, 0.18216585433541427]], [["Cutout", 0.7004457278387007, 0.4904439660213413], ["Contrast", 0.6516622044646659, 0.7324290164242575]], [["Brightness", 0.594212018801632, 0.5624822682300464], ["ShearX", 0.47929863548325596, 0.5610640338380719]], [["TranslateX", 0.20863492063218445, 0.23761872077836552], ["Color", 0.9374148559524687, 0.06390809573246009]], [ ["AutoContrast", 0.5548946725094693, 0.40547561665765874], ["Equalize", 0.26341425401933344, 0.2763692089379619], ], [["Invert", 0.8224614398122034, 0.15547159819315676], ["Rotate", 0.4915912924663281, 0.6995695827608112]], [["Equalize", 0.05752620481520809, 0.80230125774557], ["Rotate", 0.16338857010673558, 0.8066738989167762]], [["ShearY", 0.5437502855505825, 0.252101665309144], ["Contrast", 0.9268450172095902, 0.13437399256747992]], [ ["TranslateY", 0.6946438457089812, 0.35376889837139813], ["Sharpness", 0.15438234648960253, 0.2668696344562673], ], [["Invert", 0.24506516252953542, 0.1939315433476327], ["Sharpness", 0.8921986990130818, 0.21478051316241717]], [["TranslateY", 0.5292829065905086, 0.6896826369723732], ["Invert", 0.4461047865540309, 0.9854416526561315]], [ ["Posterize", 0.8085062334285464, 0.4538963572040656], ["Brightness", 0.2623572045603854, 0.16723779221170698], ], [["Solarize", 0.1618752496191097, 0.6007634864056693], ["TranslateY", 0.07808851801433346, 0.3951252736249746]], [ ["TranslateX", 0.35426056783145843, 0.8875451782909476], ["Brightness", 0.5537927990151869, 0.3042790536918476], ], [["Cutout", 0.9051584028783342, 0.6050507821593669], ["ShearX", 0.31185875057627255, 0.39145181108334876]], [["Brightness", 0.43157388465566776, 0.45511767545129933], ["ShearY", 0.626464342187273, 0.5251031991594401]], [["Contrast", 0.7978520212540166, 0.45088491126800995], ["ShearY", 0.20415027867560143, 0.24369493783350643]], [["ShearX", 0.48152242363853065, 0.001652619381325604], ["Sharpness", 0.6154899720956758, 0.22465778944283568]], [ ["Posterize", 0.0008092255557418104, 0.8624848793450179], ["Solarize", 0.7580784903978838, 0.4141187863855049], ], [["TranslateY", 0.4829597846471378, 0.6077028815706373], ["ShearX", 0.43316420981872894, 0.007119694447608018]], [["Equalize", 0.2914045973615852, 0.6298874433109889], ["Cutout", 0.18663096101056076, 0.20634383363149222]], [["TranslateX", 0.6909947340830737, 0.40843889682671003], ["ShearX", 0.3693105697811625, 0.070573833710386]], [["Rotate", 0.6184027722396339, 0.6483359499288176], ["AutoContrast", 0.8658233903089285, 0.31462524418660626]], [ ["Brightness", 0.8165837262133947, 0.38138221738335765], ["Contrast", 0.01566790570443702, 0.1250581265407818], ], [["Equalize", 0.16745169701901802, 0.9239433721204139], ["ShearY", 0.5535908803004554, 0.35879199699526654]], [["Color", 0.9675880875486578, 0.19745998576077994], ["Posterize", 0.641736196661405, 0.5702363593336868]], [["ShearY", 0.27730895136251943, 0.4730273890919014], ["Posterize", 0.35829530316120517, 0.9040968539551122]], [["Cutout", 0.9989158254302966, 0.3210048366589035], ["Equalize", 0.9226385492886618, 0.21132010337062]], [["Posterize", 0.32861829410989934, 0.7608163668499222], ["TranslateY", 0.528381246453454, 0.6837459631017135]], [["ShearY", 0.6786278797045173, 0.49006792710382946], ["ShearX", 0.7860409944610941, 0.7960317025665418]], [["Solarize", 0.4420731874598513, 0.7163961196254427], ["Sharpness", 0.11927615232343353, 0.3649599343067734]], [["Cutout", 0.4606157449857542, 0.4682141505042986], ["Contrast", 0.8955528913735222, 0.8468556570983498]], [["Brightness", 0.5742349576881501, 0.5633914487991978], ["ShearX", 0.8288987143597276, 0.5937556836469728]], [["Posterize", 0.05362153577922808, 0.40072961361335696], ["Rotate", 0.6681795049585278, 0.5348470042353504]], [["TranslateY", 0.6190833866612555, 0.7338431624993972], ["Color", 0.5352400737236565, 0.1598194251940268]], [ ["Brightness", 0.9942846465176832, 0.11918348505217388], ["Brightness", 0.0659098729688602, 0.6558077481794591], ], [["Equalize", 0.34089122700685126, 0.048940774058585546], ["ShearX", 0.5472987107071652, 0.2965222509150173]], [["Sharpness", 0.3660728361470086, 0.37607120931207433], ["Sharpness", 0.9974987257291261, 0.2483317486035219]], [["Posterize", 0.931283270966942, 0.7525022430475327], ["Cutout", 0.6299208568533524, 0.3313382622423058]], [["Invert", 0.5074998650080915, 0.9722820836624784], ["Solarize", 0.13997049847474802, 0.19340041815763026]], [ ["AutoContrast", 0.6804950477263457, 0.31675149536227815], ["Solarize", 0.800632422196852, 0.09054278636377117], ], [["TranslateY", 0.6886579465517867, 0.549118383513461], ["Brightness", 0.7298771973550124, 0.59421647759784]], [ ["Equalize", 0.8117050130827859, 0.22494316766261946], ["AutoContrast", 0.5217061631918504, 0.6106946809838144], ], [["Equalize", 0.4734718117645248, 0.7746036952254298], ["Posterize", 0.032049205574512685, 0.9681402692267316]], [["Brightness", 0.4724177066851541, 0.7969700024018729], ["Solarize", 0.6930049134926459, 0.3880086567038069]], [["TranslateX", 0.2833979092130342, 0.6873833799104118], ["Rotate", 0.37167767436617366, 0.03249352593350204]], [ ["Posterize", 0.7080588381354884, 0.03014586990329654], ["Posterize", 0.20883930954891392, 0.1328596635826556], ], [["Cutout", 0.1992050307454733, 0.8079881690617468], ["ShearY", 0.3057279570820446, 0.34868823290010564]], [["TranslateY", 0.6204358851346782, 0.24978856155434062], ["ShearX", 0.2403059671388028, 0.6706906799258086]], [["Contrast", 0.5527380063918701, 0.27504242043334765], ["Rotate", 0.37361791978638376, 0.17818567121454373]], [["Cutout", 0.3368229687890997, 0.013512329226772313], ["Contrast", 0.18480406673028238, 0.21653280083721013]], [ ["AutoContrast", 0.13634047961070397, 0.5322441057075571], ["Posterize", 0.3409948654529233, 0.2562132228604077], ], [["Invert", 0.3375636037272626, 0.5417577242453775], ["Sharpness", 0.10271458969925179, 0.5125859420868099]], [ ["Invert", 0.26465503753231256, 0.7386494688407392], ["AutoContrast", 0.5310106090963371, 0.14699248759273964], ], [["Sharpness", 0.8494538270706318, 0.9524607358113082], ["Solarize", 0.21142978953773187, 0.10711867917080763]], [["Equalize", 0.5185117903942263, 0.06342404369282638], ["ShearY", 0.26812877371366156, 0.32386585917978056]], [ ["TranslateY", 0.42724471339053904, 0.5218262942425845], ["Brightness", 0.7618037699290332, 0.5773256674209075], ], [ ["Solarize", 0.5683461491921462, 0.7988018975591509], ["AutoContrast", 0.21826664523938988, 0.4395073407383595], ], [["Posterize", 0.2564295537162734, 0.6778150727248975], ["Equalize", 0.7571361164411801, 0.4281744623444925]], [["Invert", 0.5171620125994946, 0.8719074953677988], ["ShearX", 0.10216776728552601, 0.20888013515457593]], [["Equalize", 0.934033636879294, 0.7724470445507672], ["ShearX", 0.14671590364536757, 0.06500753170863127]], [["Cutout", 0.48433709681747783, 0.8989915985203363], ["ShearY", 0.5161346572684965, 0.3154078452465332]], [ ["AutoContrast", 0.4337913490682531, 0.8651407398083308], ["AutoContrast", 0.31402168607643444, 0.5001710653814162], ], [["Brightness", 0.4805460794016203, 0.8182812769485313], ["Equalize", 0.6811585495672738, 0.25172380097389147]], [["TranslateX", 0.05384872718386273, 0.7854623644701991], ["Color", 0.12583336502656287, 0.08656304042059215]], [["TranslateX", 0.3949348949001942, 0.0668909826131569], ["ShearX", 0.2895255694762277, 0.23998090792480392]], [["TranslateY", 0.3183346601371876, 0.5869865305603826], ["Cutout", 0.38601500458347904, 0.37785641359408184]], [["Sharpness", 0.3676509660134142, 0.6370727445512337], ["Rotate", 0.17589815946040205, 0.912442427082365]], [["Equalize", 0.46427003979798154, 0.7771177715171392], ["Cutout", 0.6622980582423883, 0.47780927252115374]], [["TranslateX", 0.4535588156726688, 0.9548833090146791], ["ShearY", 0.18609208838268262, 0.034329918652624025]], [["Rotate", 0.4896172340987028, 0.4842683413051553], ["Brightness", 0.08416972178617699, 0.2946109607041465]], [["TranslateY", 0.1443363248914217, 0.7352253161146544], ["ShearX", 0.025210952382823004, 0.6249971039957651]], [["Brightness", 0.08771030702840285, 0.5926338109828604], ["Contrast", 0.629121304110493, 0.36114268164347396]], [["Cutout", 0.003318169533990778, 0.984234627407162], ["Color", 0.5656264894233379, 0.9913705503959709]], [["Cutout", 0.17582168928005226, 0.5163176285036686], ["Sharpness", 0.42976684239235224, 0.9936723374147685]], [["Rotate", 0.13343297511611085, 0.730719022391835], ["Cutout", 0.43419793455016154, 0.9802436121876401]], [["ShearX", 0.8761482122895571, 0.11688364945899332], ["Solarize", 0.6071032746712549, 0.9972373138154098]], [["Contrast", 0.2721995133325574, 0.9467839388553563], ["AutoContrast", 0.357368427575824, 0.6530359095247653]], [["Equalize", 0.5334298945812708, 0.7157629957411794], ["Brightness", 0.8885107405370157, 0.2909013041171791]], [["Equalize", 0.4907081744271751, 0.9999203497290372], ["ShearX", 0.0055186544890628575, 0.20501406304441697]], [["Color", 0.4865852751351166, 0.14717278223914915], ["TranslateX", 0.0492335566831905, 0.01654291587484527]], [["Contrast", 0.3753662301521211, 0.866484274102244], ["Color", 0.21148416029328898, 0.37861792266657684]], [ ["TranslateY", 0.03960047686663052, 0.9948086048192006], ["TranslateX", 0.5802633545422445, 0.7696464344779717], ], [["Contrast", 0.6456791961464718, 0.6304663998505495], ["Sharpness", 0.594774521429873, 0.8024138008893688]], [["Equalize", 0.5326123709954759, 0.7361990154971826], ["Invert", 0.5337609996065145, 0.06826577456972233]], [["ShearY", 0.7177596430755101, 0.16672206074906565], ["Equalize", 0.1847132768987843, 0.16186121936769876]], [["ShearY", 0.037342495065949534, 0.7762322168034441], ["Rotate", 0.28731231550023495, 0.4605573565280328]], [["Contrast", 0.6815742688289678, 0.04073638022156048], ["Cutout", 0.20201133153964437, 0.048429819360450654]], [["Color", 0.5295323372448824, 0.8591352159356821], ["Posterize", 0.7743900815037675, 0.8308865010050488]], [["Solarize", 0.9325362059095493, 0.4070769736318192], ["Contrast", 0.09359008071252661, 0.2808191171337515]], [["Sharpness", 0.6413241263332543, 0.5493867784897841], ["Solarize", 0.021951790397463734, 0.1045868634597023]], [["Color", 0.006027943433085061, 0.698043169126901], ["TranslateX", 0.06672167045857719, 0.6096719632236709]], [["TranslateX", 0.42167004878865333, 0.8844171486107537], ["Color", 0.12383835252312375, 0.9559595374068695]], [["Posterize", 0.5382560989047361, 0.6014252438301297], ["Color", 0.26197040526014054, 0.3423981550778665]], [ ["Cutout", 0.33150268513579584, 0.40828564490879615], ["AutoContrast", 0.6907753092981255, 0.05779246756831708], ], [ ["Equalize", 0.31608006376116865, 0.9958870759781376], ["TranslateY", 0.15842255624921547, 0.5764254535539765], ], [ ["Contrast", 0.19859706438565994, 0.12680764238281503], ["TranslateY", 0.4694115475285127, 0.45831161348904836], ], [["TranslateX", 0.18768081492494126, 0.7718605539481094], ["Cutout", 0.2340834739291012, 0.3290460999084155]], [ ["Posterize", 0.17300123510877463, 0.5276823821218432], ["AutoContrast", 0.5861008799330297, 0.31557924295308126], ], [ ["TranslateX", 0.36140745478517367, 0.4172762477431993], ["Sharpness", 0.6518477061748665, 0.9033991248207786], ], [ ["AutoContrast", 0.1757278990984992, 0.9562490311064124], ["Invert", 0.43712652497757065, 0.26925880337078234], ], [ ["TranslateX", 0.38113274849599377, 0.35742156735271613], ["TranslateY", 0.47708889990018216, 0.7975974044609476], ], [["Brightness", 0.39538470887490523, 0.09692156164771923], ["Equalize", 0.876825166573471, 0.0979346217138612]], [["Solarize", 0.07679586061933875, 0.45996163577975313], ["Invert", 0.039726680682847904, 0.23574574397443826]], [["ShearX", 0.9739648414905278, 0.5217986621319772], ["TranslateY", 0.21653455086845896, 0.30415852174016683]], [ ["TranslateY", 0.26965366633030263, 0.4355259497820251], ["Sharpness", 0.6343493801543757, 0.9337027079656623], ], [ ["Rotate", 0.42301232492240126, 0.07813015342326983], ["AutoContrast", 0.28524730310382906, 0.24127293503900557], ], [["Color", 0.826300213905907, 0.008451115447607682], ["Equalize", 0.6770124607838715, 0.2889698349030014]], [["Cutout", 0.3461911530045792, 0.7481322146924341], ["Brightness", 0.1831459184570124, 0.5487074846857195]], [["Brightness", 0.8455429603962046, 0.4838335496721761], ["Cutout", 0.5778222397066808, 0.7789798279724414]], [ ["Brightness", 0.7859388330361665, 0.5907006126719181], ["Brightness", 0.5299842953874527, 0.008670514958094622], ], [["Rotate", 0.9584331504536162, 0.7242692977964363], ["TranslateY", 0.46941406313257866, 0.748911298847083]], [ ["AutoContrast", 0.5878130357161462, 0.25218818797390996], ["Solarize", 0.815466142337258, 0.20231731395730107], ], [["ShearX", 0.15594838773787617, 0.9764784874102524], ["TranslateY", 0.5805369037495945, 0.1412009058745196]], [["Sharpness", 0.7936370935749524, 0.5142489498674206], ["Sharpness", 0.1544307510097193, 0.3678451501088748]], [ ["TranslateY", 0.29391437860633873, 0.3520843012638746], ["Brightness", 0.5885278199370352, 0.04915265122854349], ], [ ["AutoContrast", 0.3329771519033218, 0.2459852352278583], ["Equalize", 0.8674782697650298, 0.2900192232303214], ], [["Cutout", 0.58997726901359, 0.9910393463442352], ["Contrast", 0.09792234559792412, 0.23341828880112486]], [["Cutout", 0.4643317809492098, 0.3224299097542076], ["TranslateY", 0.7998033586490294, 0.27086436352896565]], [ ["AutoContrast", 0.13138317155414905, 0.3419742927322439], ["TranslateY", 0.05413070060788905, 0.5504283113763994], ], [["Posterize", 0.3645493423712921, 0.10684861674653627], ["Color", 0.6343589365592908, 0.9712261380583729]], [["Color", 0.06539862123316142, 0.34370535435837324], ["Equalize", 0.8098077629435421, 0.1272416658849032]], [["Invert", 0.3600258964493429, 0.7455698641930473], ["Color", 0.4118102215241555, 0.4489347750419333]], [ ["Sharpness", 0.2230673636976691, 0.2240713255305713], ["AutoContrast", 0.5039292091174429, 0.033700713206763835], ], [["ShearX", 0.10611028325684749, 0.4235430688519599], ["Brightness", 0.354597328722803, 0.6835155193055997]], [["ShearX", 0.101313662029975, 0.3048854771395032], ["ShearX", 0.39832929626318425, 0.5569152062399838]], [["ShearX", 0.46033087857932264, 0.5976525683159943], ["Color", 0.8117411866929898, 0.22950658046373415]], [["Cutout", 0.04125062306390376, 0.5021647863925347], ["TranslateY", 0.4949139091550513, 0.40234738545601595]], [["TranslateX", 0.9982425877241792, 0.3912268450702254], ["Cutout", 0.8094853705295444, 0.4628037417520003]], [["Contrast", 0.47154787535001147, 0.5116549800625204], ["Invert", 0.4929108509901112, 0.713690694626014]], [["ShearX", 0.3073913369156325, 0.5912409524756753], ["Equalize", 0.5603975982699875, 0.12046838435247365]], [["TranslateY", 0.8622939212850868, 0.057802109037417344], ["Invert", 0.7577173459800602, 0.33727019024447835]], [["Cutout", 0.3646694663986778, 0.6285264075514656], ["Color", 0.5589259087346165, 0.6650676195317845]], [["Invert", 0.8563008117600374, 0.6216056385231019], ["AutoContrast", 0.7575002303510038, 0.6906934785154547]], [["ShearX", 0.4415411885102101, 0.301535484182858], ["TranslateY", 0.779716145113622, 0.5792057745092073]], [["Invert", 0.10736083594024397, 0.10640910911300788], ["Posterize", 0.5923391813408784, 0.5437447559328059]], [["Color", 0.4745215286268124, 0.08046291318852558], ["Rotate", 0.1642897827127771, 0.20754337935267492]], [["Invert", 0.3141086213412405, 0.5865422721808763], ["AutoContrast", 0.7551954144793225, 0.5588044000850431]], [["Equalize", 0.979500405577596, 0.6846916489547885], ["Rotate", 0.11257616752512875, 0.8137724117751907]], [["Equalize", 0.6315666801659133, 0.71548254701219], ["Cutout", 0.38805635642306224, 0.29282906744304604]], [["Posterize", 0.022485702859896456, 0.2794994040845844], ["Color", 0.4554990465860552, 0.5842888808848151]], [["Invert", 0.15787502346886398, 0.5137397924063724], ["TranslateY", 0.487638703473969, 0.6428121360825987]], [["Rotate", 0.20473927977443407, 0.6090899892067203], ["Contrast", 0.3794752343740154, 0.8056548374185936]], [ ["AutoContrast", 0.35889225269685354, 0.7311496777471619], ["Sharpness", 0.10152796686794396, 0.34768639850633193], ], [["Rotate", 0.6298704242033275, 0.09649334401126405], ["Solarize", 0.24713244934163017, 0.4292117526982358]], [["Contrast", 0.9851015107131748, 0.30895068679118054], ["Sharpness", 0.7167845732283787, 0.36269175386392893]], [["Equalize", 0.49699932368219435, 0.21262924430159158], ["Contrast", 0.8497731498354579, 0.672321242252727]], [["ShearX", 0.18955591368056923, 0.47178691165954034], ["Sharpness", 0.17732805705271348, 0.5486957094984023]], [["ShearY", 0.5087926728214892, 0.8236809302978783], ["AutoContrast", 0.9661195881001936, 0.1309360428195535]], [["Rotate", 0.7825835251082691, 0.8292427086033229], ["TranslateX", 0.2034110174253454, 0.4073091408820304]], [["Cutout", 0.33457316681888716, 0.480098511703719], ["Sharpness", 0.8686004956803908, 0.21719357589897192]], [["ShearX", 0.30750577846813, 0.6349236735519613], ["Color", 0.5096781256213182, 0.5367289796478476]], [["Rotate", 0.7881847986981432, 0.846966895144323], ["Posterize", 0.33955649631388407, 0.9484449471562024]], [ ["Posterize", 0.5154127791998345, 0.8765287012129974], ["Posterize", 0.09621562708431097, 0.42108077474553995], ], [ ["ShearX", 0.5513772653411826, 0.27285892893658015], ["AutoContrast", 0.027608088485522986, 0.1738173285576814], ], [["Equalize", 0.7950881609822011, 0.05938388811616446], ["ShearX", 0.7864733097562856, 0.5928584864954718]], [["Equalize", 0.03401947599579436, 0.4936643525799874], ["Solarize", 0.8445332527647407, 0.4695434980914176]], [ ["AutoContrast", 0.9656295942383031, 0.6330670076537706], ["Brightness", 0.303859679517296, 0.8882002295195086], ], [["ShearY", 0.5242765280639856, 0.7977406809732712], ["Rotate", 0.24810823616083127, 0.41392557985700773]], [["Posterize", 0.6824268148168342, 0.21831492475831715], ["ShearY", 0.0008811906288737209, 0.1939566265644924]], [["ShearY", 0.8413370823124643, 0.7075999817793881], ["Brightness", 0.7942266192900009, 0.0384845738170444]], [["ShearY", 0.9003919463843213, 0.5068340457708402], ["AutoContrast", 0.9990937631537938, 0.35323621376481695]], [["Contrast", 0.3266913024108897, 0.5470774782762176], ["Contrast", 0.31235464476196995, 0.5723334696204473]], [ ["AutoContrast", 0.40137522654585955, 0.4274859892417776], ["Sharpness", 0.6173858127038773, 0.9629236289042568], ], [["Sharpness", 0.3728210261025356, 0.7873518787942092], ["Solarize", 0.4319848902062112, 0.799524274852396]], [["Sharpness", 0.009379857090624758, 0.3143858944787348], ["ShearY", 0.20273037650420184, 0.3501104740582885]], [["Color", 0.1837135820716444, 0.5709648984713641], ["Solarize", 0.36312838060628455, 0.3753448575775562]], [["Cutout", 0.3400431457353702, 0.6871688775988243], ["ShearX", 0.42524570507364123, 0.7108865889616602]], [["Sharpness", 0.30703348499729893, 0.885278643437672], ["Cutout", 0.04407034125935705, 0.6821013415071144]], [ ["Brightness", 0.7164362367177879, 0.3383891625406651], ["Posterize", 0.002136409392137939, 0.5744439712876557], ], [["Rotate", 0.757566991428807, 0.41351586654059386], ["TranslateY", 0.6716670812367449, 0.45381701497377025]], [["Color", 0.29554345831738604, 0.5747484938203239], ["Brightness", 0.6495565535422139, 0.38353714282675055]], [["Color", 0.6552239827844064, 0.6396684879350223], ["Rotate", 0.4078437959841622, 0.8229364582618871]], [["ShearX", 0.3325165311431108, 0.99875651917317], ["Cutout", 0.060614087173980605, 0.8655206968462149]], [["ShearY", 0.8591223614020521, 0.47375809606391645], ["ShearY", 0.09964216351993155, 0.7076762087109618]], [["Color", 0.9353968383925787, 0.5171703648813921], ["Cutout", 0.7542267059402566, 0.4591488152776885]], [["ShearX", 0.6832456179177027, 0.6798505733549863], ["Color", 0.7408439718746301, 0.5061967673457707]], [["Equalize", 0.4451729339243929, 0.9242958562575693], ["Posterize", 0.2426742903818478, 0.7914731845374992]], [["Posterize", 0.6241497285503436, 0.6800650930438693], ["Rotate", 0.8212761169895445, 0.42470879405266637]], [["Sharpness", 0.35467334577635123, 0.4150922293649909], ["Color", 0.38988011871489925, 0.08762395748275534]], [["Invert", 0.20231176261188386, 0.34300045056881756], ["Color", 0.6311643386438919, 0.4311911861691113]], [["Contrast", 0.2892223327756343, 0.533349670629816], ["ShearY", 0.6483243327679983, 0.37584367848303185]], [["Contrast", 0.6516401043089397, 0.3801387361685983], ["Contrast", 0.38470661862567795, 0.994720698440467]], [ ["Contrast", 0.44558087160644655, 0.4234506152228727], ["AutoContrast", 0.30132391715441104, 0.7758068064149011], ], [["ShearY", 0.8336612877669443, 0.6961881064757953], ["TranslateX", 0.111182606133131, 0.7138593872015647]], [["Brightness", 0.7252053408816349, 0.6883715819669095], ["Cutout", 0.6664014893052573, 0.5118622737562747]], [["TranslateX", 0.04294623433241698, 0.4737274091618545], ["Solarize", 0.15848056715239178, 0.436678451116009]], [["ShearX", 0.41843604414439584, 0.5571669083243844], ["Solarize", 0.31754187268874345, 0.643294796216908]], [["Cutout", 0.308644829376876, 0.9455913104658791], ["Cutout", 0.04221174396591258, 0.8004389485099825]], [["Invert", 0.7644819805649288, 0.393641460630097], ["Posterize", 0.20832144467525543, 0.6449709932505365]], [["ShearY", 0.60954354330238, 0.45193814135157406], ["Rotate", 0.07564178568434804, 0.5700158941616946]], [["Color", 0.47993653910354905, 0.18770437256254732], ["Equalize", 0.16540989366253533, 0.3295832145751728]], [["Sharpness", 0.773656112445468, 0.899183686347773], ["AutoContrast", 0.6225833171499476, 0.8375805811436356]], [["Brightness", 0.3119630413126101, 0.21694186245727698], ["Cutout", 0.08263220622864997, 0.9910421137289533]], [["TranslateY", 0.5200200210314198, 0.44467464167817444], ["Cutout", 0.3466375681433383, 0.22385957813397142]], [["ShearY", 0.4445374219718209, 0.23917745675733915], ["Equalize", 0.32094329607540717, 0.6286388268054685]], [["Invert", 0.6194633221674505, 0.6219326801360905], ["Color", 0.43219405413154555, 0.5463431710956901]], [["ShearX", 0.5491808798436206, 0.4485147269153593], ["ShearX", 0.9624243432991532, 0.581319457926692]], [["Cutout", 0.8486066390061917, 0.48538785811340557], ["Cutout", 0.15945182827781573, 0.4114259503742423]], [["TranslateX", 0.9845485123667319, 0.7590166645874611], ["Solarize", 0.9920857955871512, 0.33259831689209834]], [["Brightness", 0.3985764491687188, 0.3516086190155328], ["Cutout", 0.13907765098725244, 0.42430309616193995]], [["Color", 0.35877942890428727, 0.363294622757879], ["Equalize", 0.4997709941984466, 0.34475754120666147]], [ ["Sharpness", 0.5234916035905941, 0.8988480410886609], ["AutoContrast", 0.793554237802939, 0.2575758806963965], ], [["Brightness", 0.36998588693418133, 0.24144652775222428], ["Cutout", 0.06610767765334377, 0.9979246311006975]], [["TranslateY", 0.6132425595571164, 0.43952345951359123], ["Cutout", 0.361849532200793, 0.8462247954545264]], [["Posterize", 0.36953849915949677, 0.3144747463577223], ["Equalize", 0.3258985378881982, 0.6314053736452068]], [ ["TranslateY", 0.35835648104981205, 0.08075066564380576], ["TranslateX", 0.5242389109555177, 0.11959330395816647], ], [["ShearX", 0.32773751079554303, 0.9307864751586945], ["Sharpness", 0.006921805496030664, 0.8736511230672348]], [["TranslateY", 0.48202000226401526, 0.7058919195136056], ["ShearY", 0.6998308555145181, 0.21074360071080764]], [["AutoContrast", 0.7615852152325713, 0.24914859158079972], ["Cutout", 0.8270894478252626, 0.5804285538051077]], [ ["AutoContrast", 0.5391662421077847, 0.5233969710179517], ["Brightness", 0.04205906143049083, 0.382677139318253], ], [["Brightness", 0.6904817357054526, 0.9116378156160974], ["Invert", 0.24305250280628815, 0.2384731852843838]], [ ["TranslateX", 0.2661235046256291, 0.9705982948874188], ["Sharpness", 0.35821873293899625, 0.0030835471296858444], ], [ ["Posterize", 0.39029991982997647, 0.4286238191447004], ["TranslateX", 0.08954883207184736, 0.7263973533121859], ], [["Cutout", 0.040284118298638344, 0.0388330236482832], ["Posterize", 0.7807814946471116, 0.5238352731112299]], [["ShearY", 0.43556653451802413, 0.6924037743225071], ["Contrast", 0.001081515338562919, 0.7340363920548519]], [["Sharpness", 0.6966467544442373, 0.10202517317137291], ["Color", 0.18836344735972566, 0.31736252662501935]], [ ["Contrast", 0.6460000689193517, 0.16242196500430484], ["AutoContrast", 0.6003831047484897, 0.8612141912778188], ], [["Brightness", 0.9172874494072921, 0.292364504408795], ["Solarize", 0.344602582555059, 0.7054248176903991]], [["Brightness", 0.020940469451794064, 0.5051042440134866], ["Cutout", 0.569500058123745, 0.9091247933460598]], [["Invert", 0.7367715506799225, 0.636137024500329], ["TranslateY", 0.6186960283294023, 0.37626001619073624]], [["TranslateX", 0.2863246154089121, 0.7454318730628517], ["ShearY", 0.6649909124084395, 0.37639265910774133]], [["Equalize", 0.34603376919062656, 0.9324026002997775], ["Sharpness", 0.8481669261233902, 0.14545759197862507]], [ ["Contrast", 0.6184370038862784, 0.8074198580702933], ["TranslateX", 0.07036135693949985, 0.46222686847401306], ], [["Invert", 0.9304884364616345, 0.26298808050002387], ["Color", 0.8027813156985396, 0.7748486756116594]], [["Posterize", 0.2887993806199106, 0.9576118517235523], ["Contrast", 0.07498577510121784, 0.09131727137211232]], [["Contrast", 0.8110536569461197, 0.051038215841138386], ["Solarize", 0.8799018446258887, 0.25028365826721977]], [ ["Cutout", 0.006954733791187662, 0.030507696587206496], ["Brightness", 0.45329597160103124, 0.9623148451520953], ], [["TranslateX", 0.7436227980344521, 0.45996857241163086], ["Solarize", 0.9682234479355196, 0.70777684485634]], [ ["Brightness", 0.2080557865889058, 0.025557286020371328], ["AutoContrast", 0.4786039197123853, 0.9271157120589375], ], [["Solarize", 0.1822930503108656, 0.8448222682426465], ["ShearX", 0.6221001240196488, 0.207994745014715]], [["Color", 0.27879201870553094, 0.9112278219836276], ["Color", 0.7508664408516654, 0.14885798940641318]], [["ShearX", 0.5496326925552889, 0.7643918760952656], ["AutoContrast", 0.7887459433195374, 0.5993900500657054]], [["ShearY", 0.7182376017241904, 0.7470412126724141], ["Rotate", 0.7644845975844854, 0.38510752407409893]], [ ["Contrast", 0.7984591239416293, 0.054767400038152704], ["Posterize", 0.7324315466290486, 0.41749946919991243], ], [["Contrast", 0.596887781894766, 0.14832691232456097], ["Contrast", 0.05140651977459313, 0.14459348285712803]], [["TranslateX", 0.32766681876233766, 0.5291103977440215], ["Color", 0.6039423443931029, 0.6280077043167083]], [["Invert", 0.5267106136816635, 0.9429838545064784], ["Sharpness", 0.9999053422304087, 0.24764251340211074]], [["Contrast", 0.495767451313242, 0.6744720418896594], ["Brightness", 0.2220993631062378, 0.023842431692152832]], [["Invert", 0.7609399278201697, 0.38010826932678554], ["Color", 0.8454251931688355, 0.5876680099851194]], [["Posterize", 0.24967505238473384, 0.3801835337368412], ["Contrast", 0.15106121477353399, 0.6785384814310887]], [["Invert", 0.49594153211743874, 0.32307787492774986], ["Contrast", 0.46822075688054793, 0.7106858486805577]], [["Sharpness", 0.7204076261101202, 0.5928585438185809], ["Rotate", 0.2922878012111486, 0.2742491027179961]], [["Solarize", 0.2866813728691532, 0.2856363754608978], ["TranslateY", 0.7817609208793659, 0.17156048740523572]], [["Cutout", 0.03345540659323987, 0.30068271036485605], ["ShearY", 0.2556603044234358, 0.32397855468866993]], [["TranslateY", 0.20032231858163152, 0.4577561841994639], ["Cutout", 0.8063563515601337, 0.9224365467344459]], [["TranslateY", 0.27130034613023113, 0.7446375583249849], ["ShearX", 0.8254766023480402, 0.4187078898038131]], [["ShearX", 0.2937536068210411, 0.3864492533047109], ["Contrast", 0.7069611463424469, 0.686695922492015]], [["TranslateX", 0.5869084659063555, 0.7866008068031776], ["Invert", 0.289041613918004, 0.5774431720429087]], [["Posterize", 0.6199250263408456, 0.36010044446077893], ["Color", 0.7216853388297056, 0.18586684958836489]], [["Posterize", 0.16831615585406814, 0.08052519983493259], ["Cutout", 0.7325882891023244, 0.77416439921321]], [["Posterize", 0.3000961100422498, 0.5181759282337892], ["Contrast", 0.40376073196794304, 0.613724714153924]], [["ShearX", 0.32203193464136226, 0.037459860897434916], ["Solarize", 0.961542785512965, 0.5176575408248285]], [ ["Posterize", 0.8986732529036036, 0.7773257927223327], ["AutoContrast", 0.9765986969928243, 0.2092264330225745], ], [["Posterize", 0.7463386563644007, 0.7086671048242543], ["Posterize", 0.6433819807034994, 0.00541136425219968]], [["Contrast", 0.8810746688690078, 0.4821029611474963], ["Invert", 0.5121169325265204, 0.6360694878582249]], [["AutoContrast", 0.457606735372388, 0.6104794570624505], ["Color", 0.0020511991982608124, 0.6488142202778011]], [["Invert", 0.01744463899367027, 0.9799156424364703], ["ShearY", 0.3448213456605478, 0.04437356383800711]], [["Solarize", 0.28511589596283315, 0.283465265528744], ["Rotate", 0.6831807199089897, 0.0617176467316177]], [["Sharpness", 0.329148970281285, 0.398397318402924], ["Color", 0.9125837011914073, 0.4724426676489746]], [["Posterize", 0.05701522811381192, 0.17109014518445975], ["Cutout", 0.785885656821686, 0.39072624694455804]], [["TranslateY", 0.36644251447248277, 0.5818480868136134], ["Equalize", 0.06162286852923926, 0.710929848709861]], [["ShearY", 0.8667124241442813, 0.7556246528256454], ["ShearY", 0.505190335528531, 0.2935701441277698]], [["Brightness", 0.6369570015916268, 0.5131486964430919], ["Color", 0.4887119711633827, 0.9364572089679907]], [["Equalize", 0.06596702627228657, 0.42632445412423303], ["Equalize", 0.583434672187985, 0.045592788478947655]], [["ShearY", 0.12701084021549092, 0.501622939075192], ["Cutout", 0.7948319202684251, 0.5662618207034569]], [["Posterize", 0.24586808377061664, 0.5178008194277262], ["Contrast", 0.1647040530405073, 0.7459410952796975]], [["Solarize", 0.346601298126444, 0.02933266448415553], ["ShearY", 0.9571781647031095, 0.4992610484566735]], [ ["Brightness", 0.5174960605130408, 0.4387498174634591], ["AutoContrast", 0.6327403754086753, 0.8279630556620247], ], [["Posterize", 0.7591448754183128, 0.6265369743070788], ["Posterize", 0.5030300462943854, 0.00401699185532868]], [["Contrast", 0.02643254602183477, 0.44677741300429646], ["Invert", 0.2921779546234399, 0.732876182854368]], [ ["TranslateY", 0.3516821152310867, 0.7142224211142528], ["Brightness", 0.07382104862245475, 0.45368581543623165], ], [["Invert", 0.21382474908836685, 0.8413922690356168], ["Invert", 0.4082563426777157, 0.17018243778787834]], [["Brightness", 0.9533955059573749, 0.8279651051553477], ["Cutout", 0.6730769221406385, 0.07780554260470988]], [ ["Brightness", 0.6022173063382547, 0.6008500678386571], ["Sharpness", 0.5051909719558138, 0.002298383273851839], ], [["Contrast", 0.03373395758348563, 0.3343918835437655], ["Sharpness", 0.8933651164916847, 0.21738300404986516]], [ ["TranslateX", 0.7095755408419822, 0.26445508146225394], ["Equalize", 0.18255527363432034, 0.38857557766574147], ], [["Solarize", 0.4045911117686074, 0.009106925727519921], ["Posterize", 0.9380296936271705, 0.5485821516085955]], [ ["Posterize", 0.20361995432403968, 0.45378735898242406], ["AutoContrast", 0.9020357653982511, 0.7880592087609304], ], [["AutoContrast", 0.9921550787672145, 0.7396130723399785], ["Cutout", 0.4203609896071977, 0.13000504717682415]], [["Equalize", 0.1917806394805356, 0.5549114911941102], ["Posterize", 0.27636900597148506, 0.02953514963949344]], [["AutoContrast", 0.5427071893197213, 0.6650127340685553], ["Color", 0.011762461060904839, 0.3793508738225649]], [["Invert", 0.18495006059896424, 0.8561476625981166], ["ShearY", 0.6417068692813954, 0.9908751019535517]], [["Solarize", 0.2992385431633619, 0.33622162977907644], ["Rotate", 0.6070550252540432, 0.010205544695142064]], [["Sharpness", 0.33292787606841845, 0.549446566149951], ["Color", 0.9097665730481233, 0.9947658451503181]], [["Posterize", 0.11207465085954937, 0.23296263754645155], ["Cutout", 0.6159972426858633, 0.38289684517298556]], [["TranslateX", 0.7343689718523805, 0.16303049089087485], ["Equalize", 0.3138385390145809, 0.6096356352129273]], [["Solarize", 0.4807269891506887, 0.28116279654856363], ["Posterize", 0.9753467973380021, 0.6327025372916857]], [ ["Posterize", 0.837244997106023, 0.5586046483574153], ["AutoContrast", 0.9005775602024721, 0.7983389828641411], ], [["AutoContrast", 0.8347112949943837, 0.7321850307727004], ["Cutout", 0.3322676575657192, 0.14409873524237032]], [["Equalize", 0.12285967262649124, 0.5368519477089722], ["Posterize", 0.2693593445898034, 0.15098267759162076]], [["Invert", 0.331021587020619, 0.3140868578915853], ["Cutout", 0.48268387543799884, 0.7642598986625201]], [["Equalize", 0.47573794714622175, 0.8628185952549363], ["Solarize", 0.14860046214144496, 0.3739284346347912]], [ ["AutoContrast", 0.6747373196190459, 0.2912917979635714], ["Posterize", 0.27259573208358623, 0.9643671211873469], ], [["Sharpness", 0.15019788105901233, 0.7289238028242861], ["ShearY", 0.7998448015985137, 0.5924798900807636]], [["Brightness", 0.7874052186079156, 0.9446398428550358], ["Equalize", 0.5105557539139616, 0.6719808885741001]], [["ShearX", 0.783252331899515, 0.74960184771181], ["ShearX", 0.4327935527932927, 0.29980994764698565]], [["Rotate", 0.03892023906368644, 0.24868635699639904], ["Cutout", 0.6408903979315637, 0.32135851733523907]], [["Invert", 0.9972802027590713, 0.9374194642823106], ["ShearX", 0.20016463162924894, 0.0052278586143255645]], [ ["AutoContrast", 0.9328687102578992, 0.44280614999256235], ["Color", 0.05637751621265141, 0.26921974769786455], ], [["AutoContrast", 0.2798532308065416, 0.5283914274806746], ["Cutout", 0.12930089032151, 0.25624459046884057]], [["Invert", 0.2397428994839993, 0.31011715409282065], ["Cutout", 0.5875151915473042, 0.7454458580264322]], [["Equalize", 0.374815667651982, 0.9502053862625081], ["Solarize", 0.10100323698574426, 0.5124939317648691]], [ ["AutoContrast", 0.6009889057852652, 0.3080148907275367], ["Posterize", 0.6543352447742621, 0.17498668744492413], ], [["Sharpness", 0.14402909409016001, 0.9239239955843186], ["ShearY", 0.8959818090635513, 0.7258262803413784]], [["Brightness", 0.8672271320432974, 0.8241439816189235], ["Equalize", 0.4954433852960082, 0.6687050430971254]], [ ["Solarize", 0.47813402689782114, 0.9447222576804901], ["TranslateY", 0.32546974113401694, 0.8367777573080345], ], [["Sharpness", 0.48098022972519927, 0.2731904819197933], ["Rotate", 0.14601550238940067, 0.3955290089346866]], [ ["AutoContrast", 0.3777442613874327, 0.9991495158709968], ["TranslateY", 0.2951496731751222, 0.6276755696126608], ], [["Cutout", 0.487150344941835, 0.7976642551725155], ["Solarize", 0.643407733524025, 0.6313641977306543]], [["Rotate", 0.35017053741686033, 0.23960877779589906], ["Sharpness", 0.8741761196478873, 0.12362019972427862]], [["Invert", 0.8849459784626776, 0.48532144354199647], ["Invert", 0.702430443380318, 0.924655906426149]], [ ["Equalize", 0.6324140359298986, 0.9780539325897597], ["AutoContrast", 0.39105074227907843, 0.3636856607173081], ], [["AutoContrast", 0.8049993541952016, 0.3231157206314408], ["ShearY", 0.6675686366141409, 0.7345332792455934]], [["Sharpness", 0.12332351413693327, 0.9345179453120547], ["Solarize", 0.1594280186083361, 0.422049311332906]], [ ["Rotate", 0.38227253679386375, 0.7664364038099101], ["AutoContrast", 0.5725492572719726, 0.21049701651094446], ], [["Brightness", 0.6432891832524184, 0.8243948738979008], ["Equalize", 0.20355899618080098, 0.7983877568044979]], [["ShearY", 0.694393675204811, 0.3686964692262895], ["TranslateX", 0.5593122846101599, 0.3378904046390629]], [["Invert", 0.9139730140623171, 0.7183505086140822], ["Posterize", 0.2675839177893596, 0.21399738931234905]], [ ["TranslateX", 0.05309461965184896, 0.032983777975422554], ["Sharpness", 0.412621944330688, 0.4752089612268503], ], [ ["Equalize", 0.06901149860261116, 0.27405796188385945], ["AutoContrast", 0.7710451977604326, 0.20474249114426807], ], [["ShearX", 0.47416427531072325, 0.2738614239087857], ["Cutout", 0.2820106413231565, 0.6295219975308107]], [["Cutout", 0.19984489885141582, 0.7019895950299546], ["ShearX", 0.4264722378410729, 0.8483962467724536]], [["ShearY", 0.42111446850243256, 0.1837626718066795], ["Brightness", 0.9187856196205942, 0.07478292286531767]], [["Solarize", 0.2832036589192868, 0.8253473638854684], ["Cutout", 0.7279303826662196, 0.615420010694839]], [["ShearX", 0.963251873356884, 0.5625577053738846], ["Color", 0.9637046840298858, 0.9992644813427337]], [["Invert", 0.7976502716811696, 0.43330238739921956], ["ShearY", 0.9113181667853614, 0.9066729024232627]], [["Posterize", 0.5750620807485399, 0.7729691927432935], ["Contrast", 0.4527879467651071, 0.9647739595774402]], [["Posterize", 0.5918751472569104, 0.26467375535556653], ["Posterize", 0.6347402742279589, 0.7476940787143674]], [["Invert", 0.16552404612306285, 0.9829939598708993], ["Solarize", 0.29886553921638087, 0.22487098773064948]], [["Cutout", 0.24209211313246753, 0.5522928952260516], ["AutoContrast", 0.6212831649673523, 0.4191071063984261]], [["ShearX", 0.4726406722647257, 0.26783614257572447], ["TranslateY", 0.251078162624763, 0.26103450676044304]], [["Cutout", 0.8721775527314426, 0.6284108541347894], ["ShearX", 0.7063325779145683, 0.8467168866724094]], [["ShearY", 0.42226987564279606, 0.18012694533480308], ["Brightness", 0.858499853702629, 0.4738929353785444]], [["Solarize", 0.30039851082582764, 0.8151511479162529], ["Cutout", 0.7228873804059033, 0.6174351379837011]], [["ShearX", 0.4921198221896609, 0.5678998037958154], ["Color", 0.7865298825314806, 0.9309020966406338]], [["Invert", 0.8077821007916464, 0.7375015762124386], ["Cutout", 0.032464574567796195, 0.25405044477004846]], [["Color", 0.6061325441870133, 0.2813794250571565], ["TranslateY", 0.5882949270385848, 0.33262043078220227]], [["ShearX", 0.7877331864215293, 0.8001131937448647], ["Cutout", 0.19828215489868783, 0.5949317580743655]], [["Contrast", 0.529508728421701, 0.36477855845285007], ["Color", 0.7145481740509138, 0.2950794787786947]], [["Contrast", 0.9932891064746089, 0.46930062926732646], ["Posterize", 0.9033014136780437, 0.5745902253320527]], ] return p def policy_decoder(augment, num_policy, num_op): op_list = augment_list(False) policies = [] for i in range(num_policy): ops = [] for j in range(num_op): op_idx = augment["policy_%d_%d" % (i, j)] op_prob = augment["prob_%d_%d" % (i, j)] op_level = augment["level_%d_%d" % (i, j)] ops.append((op_list[op_idx][0].__name__, op_prob, op_level)) policies.append(ops) return policies
archai/scripts/supergraph/archive.py/0
{ "file_path": "archai/scripts/supergraph/archive.py", "repo_id": "archai", "token_count": 105447 }
336
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch from archai.common.common import common_init from archai.common.config import Config from archai.supergraph import models from archai.supergraph.datasets import data from archai.supergraph.utils.trainer import Trainer def train_test(conf_eval: Config): conf_loader = conf_eval["loader"] conf_trainer = conf_eval["trainer"] # create model Net = models.resnet34 model = Net().to(torch.device("cuda", 0)) # get data data_loaders = data.get_data(conf_loader) # train! trainer = Trainer(conf_trainer, model) trainer.fit(data_loaders) if __name__ == "__main__": conf = common_init(config_filepath="confs/algos/resnet.yaml") conf_eval = conf["nas"]["eval"] train_test(conf_eval)
archai/scripts/supergraph/models/train_archai.py/0
{ "file_path": "archai/scripts/supergraph/models/train_archai.py", "repo_id": "archai", "token_count": 289 }
337
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch from torch_testbed import cifar10_models from torch_testbed.timing import MeasureTime, print_all_timings from archai.common import utils utils.setup_cuda(42, local_rank=0) batch_size = 512 half = True model = cifar10_models.resnet18().cuda() lr, momentum, weight_decay = 0.025, 0.9, 3.0e-4 optim = torch.optim.SGD(model.parameters(), lr, momentum=momentum, weight_decay=weight_decay) crit = torch.nn.CrossEntropyLoss().cuda() if half: model = model.half() crit = crit.half() @MeasureTime def iter_dl(ts): i, d = 0, 0 for x, l in ts: y = model(x) loss = crit(y, l) optim.zero_grad() loss.backward() optim.step() i += 1 d += len(x) return i, d for _ in range(5): train_dl = [ ( torch.rand(batch_size, 3, 12, 12).cuda() if not half else torch.rand(batch_size, 3, 12, 12).cuda().half(), torch.LongTensor(batch_size).random_(0, 10).cuda(), ) for _ in range(round(50000 / batch_size)) ] i, d = iter_dl(train_dl) print_all_timings() print(i, d) exit(0)
archai/scripts/supergraph/performance/model_test.py/0
{ "file_path": "archai/scripts/supergraph/performance/model_test.py", "repo_id": "archai", "token_count": 527 }
338
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import os import sys from archai.common.store import ArchaiStore CONNECTION_NAME = 'MODEL_STORAGE_CONNECTION_STRING' def reset(con_str, experiment_name): parser = argparse.ArgumentParser( description='Reset the named entity.') parser.add_argument('name', help='The friendly name to reset or "*" to reset all rows', default=None) args = parser.parse_args() storage_account_name, storage_account_key = ArchaiStore.parse_connection_string(con_str) store = ArchaiStore(storage_account_name, storage_account_key, table_name=experiment_name) entities = [] if args.name == "*": entities = [e for e in store.get_all_status_entities()] else: e = store.get_existing_status(args.name) if e is None: print(f"Entity {args.name} not found") sys.exit(1) else: entities = [e] for e in entities: name = e['name'] store.reset(e['name'], ['benchmark_only', 'model_date']) store.delete_blobs(name, 'model.dlc') store.delete_blobs(name, 'model.quant.dlc') if __name__ == '__main__': experiment_name = os.getenv("EXPERIMENT_NAME", "facesynthetics") con_str = os.getenv(CONNECTION_NAME) if not con_str: print(f"Please specify your {CONNECTION_NAME} environment variable.") sys.exit(1) reset(con_str, experiment_name)
archai/tasks/face_segmentation/aml/azure/reset.py/0
{ "file_path": "archai/tasks/face_segmentation/aml/azure/reset.py", "repo_id": "archai", "token_count": 586 }
339
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import cv2 import numpy as np import glob import os import sys import tqdm from shutil import rmtree DEVICE_WORKING_DIR = "/data/local/tmp" TASK = os.path.basename(os.getcwd()) class DataGenerator(): def __init__(self, root, img_size, subset='quant', count=1000, transpose=None): self.img_size = img_size self.root = root self.subset = subset self.transpose = transpose all_seg_files = sorted(glob.glob(os.path.join(self.root, '*_seg.png'))) if len(all_seg_files) == 0: print("### no *_seg.png files found in {}".format(self.root)) sys.exit(1) # use first 10000 images for quantization and last 10000 images for test assert subset in ['quant', 'test'] if subset == 'quant': self.seg_files = all_seg_files[0:1000] elif subset == 'test': self.seg_files = all_seg_files[len(all_seg_files) - count:] self.img_files = [s.replace("_seg.png", ".png") for s in self.seg_files] def __len__(self): return len(self.img_files) def __call__(self): num_imgs = len(self.img_files) assert num_imgs > 0 indices = np.arange(num_imgs) for idx in indices: img_file = self.img_files[idx] img = cv2.imread(img_file)[..., ::-1] # BGR to RGB img = cv2.resize(img, self.img_size, interpolation=cv2.INTER_LINEAR) if self.transpose: img = img.transpose(self.transpose) yield os.path.basename(img_file), (img / 255).astype(np.float32) def create_dataset(src_root, subset, shape, count, trans=None): print(f"Creating {subset} dataset of {count} images with input shape {shape}...") image_size = (shape[0], shape[1]) device_working_dir = f'{DEVICE_WORKING_DIR}/{TASK}' dst_root = os.path.join(os.getcwd(), 'data', subset) if os.path.isdir(dst_root): rmtree(dst_root) os.makedirs(dst_root) data_gen = DataGenerator(src_root, image_size, subset, count, trans) file_list = [] with tqdm.tqdm(total=len(data_gen)) as pbar: for fname, img in data_gen(): filename = os.path.join(dst_root, fname.replace('.png', '.bin')) file_list.append(filename) img.tofile(filename) pbar.update(1) with open(os.path.join(dst_root, 'input_list.txt'), 'w') as f: for fname in file_list: f.write(fname) f.write('\n') with open(os.path.join(dst_root, 'input_list_for_device.txt'), 'w') as f: for fname in file_list: device_path = device_working_dir + '/data/test/' + os.path.basename(fname) f.write(device_path) f.write('\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create the quant and test datasets') parser.add_argument('--input', help='Location of the original input images ' + '(default INPUT_DATASET environment variable') parser.add_argument('--count', '-c', type=int, help='Number of images in the test dataset folder ' + '(default 1000)', default=1000) parser.add_argument('--dim', '-d', type=int, help='New dimension for the images ' + '(assumes square dimensions, default 256)', default=256) parser.add_argument('--transpose', '-t', help="Apply image transpose of '(2, 0 1)'", action="store_true") args = parser.parse_args() dataset = args.input if not dataset: dataset = os.getenv("INPUT_DATASET") if not dataset: print("please provide --input or set your INPUT_DATASET environment variable") sys.exit(1) count = args.count dim = args.dim transpose = args.transpose if transpose: transpose = (2, 0, 1) else: transpose = None create_dataset(dataset, 'quant', (dim, dim), count, transpose) create_dataset(dataset, 'test', (dim, dim), count, transpose)
archai/tasks/face_segmentation/aml/snpe/create_data.py/0
{ "file_path": "archai/tasks/face_segmentation/aml/snpe/create_data.py", "repo_id": "archai", "token_count": 1831 }
340
## Readme 1. **Visualize Mask R-CNN outputs** and verify if the model outputs are correct. Inside your experiment folder, run `collect_metrics.py --help` to see the command line args. The `--show` option visualizes the results, for example: ``` python collect_metrics.py --input d:\datasets\FaceSynthetics --output .\Results --show ``` You should see something like this: ![screenshot](screenshot.png) 1. **Compute metrics**. Inside your experiment folder, run `collect_metrics.py` again without the `--show` argument and you will get a .csv output file listing the F1 scores for each category and an overall score.
archai/tasks/face_segmentation/aml/vision/readme.md/0
{ "file_path": "archai/tasks/face_segmentation/aml/vision/readme.md", "repo_id": "archai", "token_count": 189 }
341
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import cv2 # pip install opencv-contrib-python import numpy as np import os import glob import onnxruntime as rt class ImageStream: def __init__(self): self.new_frame = False self.frame = None def load_next_image(self): """ advance to next image in the stream """ return None def get_next_frame(self): """ return the current image """ return np.copy(self.frame) class VideoStream(ImageStream): def __init__(self, camera): super(VideoStream, self).__init__() self.camera = camera self.capture_device = cv2.VideoCapture(self.camera) self.load_next_image() def get_next_frame(self): ret, self.frame = self.capture_device.read() if (not ret): raise Exception('your capture device is not returning images') return self.frame def load_next_image(self): # the video stream is live, no need to "advance" to the next frame pass class FileImageStream(ImageStream): def __init__(self, image_file_or_folder): super(FileImageStream, self).__init__() if os.path.isdir(image_file_or_folder): image_file_or_folder = os.path.join(image_file_or_folder, '*') self.images = glob.glob(image_file_or_folder) self.image_pos = 0 self.image_filename = None self.load_next_image() def load_next_image(self): frame = None while frame is None and self.image_pos < len(self.images): filename = self.images[self.image_pos] self.image_filename = filename frame = cv2.imread(filename) if frame is None: print("Error loading image: {}".format(filename)) else: self.new_frame = True self.frame = frame self.image_pos += 1 return frame class InferenceDisplay: def __init__(self, source: ImageStream): self.source = source def run(self, model): onnx_session = rt.InferenceSession(model) inputs = onnx_session.get_inputs() if len(inputs) > 1: raise Exception("This script only supports models with a single input") input_shape = inputs[0].shape # should be [1,3,256,256] image_size = tuple(input_shape[-2:]) input_name = inputs[0].name while True: input_image = self.source.get_next_frame() if input_image is None: break input_image = self.resize_image(input_image, image_size) # input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB) # onnx expects the rgb channel to come first frame = input_image.transpose(2, 0, 1) # onnx expects the batch size to be the first dimension frame = np.expand_dims(frame, axis=0) # onnx model expects float32, and scaled down to the range [0,1.0]. frame = frame.astype(np.float32) / 255 results = onnx_session.run(None, input_feed={input_name: frame}) frame = self.color_map_result(results[0]) # create side by side input image and result. new_image = np.hstack((input_image, frame)) cv2.imshow('frame', new_image) key = cv2.waitKey(1) & 0xFF if key == 32: self.source.load_next_image() elif key == ord('q') or key == ord('x') or key == 27: break def color_map_result(self, result : np.array): # The result should be type: float32 (1,18,255,255) so we have to transpose that to (255,255,18) # and also need to do an argmax while we are at it to find the "predicted category". # and we also need to normalize it to the range 0-255 which we can also do in one pass. # so we can do all of that in one line of code: num_classes = result.shape[1] result = result[0].transpose(1, 2, 0) predictions = np.argmax(result, axis=2) * (255.0 / num_classes) return cv2.applyColorMap(predictions.astype(np.uint8), cv2.COLORMAP_JET) def resize_image(self, image, newSize): """Center crop and resizes image to newSize. Returns image as numpy array.""" if image.shape[0] > image.shape[1]: # Tall (more rows than cols) rowStart = int((image.shape[0] - image.shape[1]) / 2) rowEnd = rowStart + image.shape[1] colStart = 0 colEnd = image.shape[1] else: # Wide (more cols than rows) rowStart = 0 rowEnd = image.shape[0] colStart = int((image.shape[1] - image.shape[0]) / 2) colEnd = colStart + image.shape[0] cropped = image[rowStart:rowEnd, colStart:colEnd] resized = cv2.resize(cropped, newSize, interpolation=cv2.INTER_LINEAR) return resized def main(): arg_parser = argparse.ArgumentParser( "This script will run inference on a given .onnx model using the onnx runtime\n" + "and show the results of that inference on a given camera or static image input." + "Press q, x, or ESC to exit. Press SPACE to advance to the next image." ) arg_parser.add_argument("--camera", type=int, help="the camera id of the webcam", default=0) arg_parser.add_argument("--images", help="path to image files (supports glob wild cards and folder names).") arg_parser.add_argument("--model", help="path to .onnx model.") args = arg_parser.parse_args() if args.images: image_stream = FileImageStream(args.images) else: image_stream = VideoStream(args.camera) display = InferenceDisplay(image_stream) display.run(args.model) if __name__ == "__main__": main()
archai/tasks/face_segmentation/test.py/0
{ "file_path": "archai/tasks/face_segmentation/test.py", "repo_id": "archai", "token_count": 2528 }
342
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import shutil from archai.datasets.nlp.hf_dataset_provider import ( HfDiskDatasetProvider, HfHubDatasetProvider, ) def test_hf_hub_dataset_provider(): dataset_provider = HfHubDatasetProvider("glue", dataset_config_name="sst2") # Assert that we can individually load training, validation and test datasets train_dataset = dataset_provider.get_train_dataset() assert len(train_dataset) == 67349 val_dataset = dataset_provider.get_val_dataset() assert len(val_dataset) == 872 test_dataset = dataset_provider.get_test_dataset() assert len(test_dataset) == 1821 def test_hf_disk_dataset_provider(): # ensure parallel tests do not clobber each other over the dataroot folder. unique_data_root = 'test_hf_disk_dataset_provider_dataroot' dataset_hub_provider = HfHubDatasetProvider("glue", dataset_config_name="sst2") train_dataset = dataset_hub_provider.get_train_dataset() train_dataset.save_to_disk(unique_data_root) # Assert that we can load the dataset from disk dataset_provider = HfDiskDatasetProvider(unique_data_root) train_dataset = dataset_provider.get_train_dataset() assert len(train_dataset) == 67349 # The HuggingFace dataset uses a datasets.table.MemoryMappedTable and this api provides no way # to explicitly close the memory mapped file here. On windows you cannot remove a directory # while a memory mapped file is still open in that directory, so we hope the python garbage # collector will close it when we clear these variables. train_dataset = None dataset_provider = None shutil.rmtree(unique_data_root) if __name__ == '__main__': test_hf_hub_dataset_provider() test_hf_disk_dataset_provider()
archai/tests/datasets/nlp/test_hf_dataset_provider.py/0
{ "file_path": "archai/tests/datasets/nlp/test_hf_dataset_provider.py", "repo_id": "archai", "token_count": 649 }
343
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from unittest.mock import MagicMock import numpy as np from overrides import overrides from archai.discrete_search.api.predictor import MeanVar, Predictor class MyPredictor(Predictor): def __init__(self) -> None: super().__init__() @overrides def fit(self, encoded_archs: np.ndarray, y: np.ndarray) -> None: return MagicMock() @overrides def predict(self, encoded_archs: np.ndarray) -> MeanVar: return MeanVar(mean=0.0, var=0.0) def test_predictor(): predictor = MyPredictor() encoded_archs = np.array([[1, 2, 3], [4, 5, 6]]) y = np.array([1, 2]) # Assert that mocked methods run and returns proper values assert predictor.fit(encoded_archs, y) preds = predictor.predict(encoded_archs) assert isinstance(preds, MeanVar) assert preds.mean == 0.0 assert preds.var == 0.0
archai/tests/discrete_search/api/test_predictor.py/0
{ "file_path": "archai/tests/discrete_search/api/test_predictor.py", "repo_id": "archai", "token_count": 358 }
344
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import pytest import torch from archai.discrete_search.search_spaces.nlp.transformer_flex.models.configuration_mem_transformer import ( MemTransformerConfig, ) from archai.discrete_search.search_spaces.nlp.transformer_flex.models.mem_transformer_utils.projected_adaptive_log_softmax import ( ProjectedAdaptiveLogSoftmax, ) from archai.discrete_search.search_spaces.nlp.transformer_flex.models.modeling_mem_transformer import ( MemTransformerLMHeadModel, MemTransformerModel, ) @pytest.fixture def config(): return MemTransformerConfig(vocab_size=128, d_embed=1024, d_model=1024, cutoffs=[32, 64], div_val=1) def test_mem_transformer_lm_head_model_init(config): model = MemTransformerLMHeadModel(config) # Assert that the model's transformer attribute has the correct type assert isinstance(model.transformer, MemTransformerModel) assert isinstance(model.crit, ProjectedAdaptiveLogSoftmax) assert model.crit.d_embed == config.d_embed assert model.crit.d_model == config.d_model assert model.crit.vocab_size == config.vocab_size def test_mem_transformer_lm_head_model_forward_pass(config): model = MemTransformerLMHeadModel(config) # Assert that the model is able to forward pass input_tensor = torch.randint(0, config.vocab_size, (1, 32)) output = model(input_tensor) assert output.prediction_scores.shape == (1, 32, config.vocab_size)
archai/tests/discrete_search/search_spaces/nlp/transformer_flex/models/test_modeling_mem_transformer.py/0
{ "file_path": "archai/tests/discrete_search/search_spaces/nlp/transformer_flex/models/test_modeling_mem_transformer.py", "repo_id": "archai", "token_count": 507 }
345
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import pytest import torch from archai.quantization.observers import OnnxDynamicObserver @pytest.fixture def onnx_dynamic_observer(): return OnnxDynamicObserver(dtype=torch.qint8) def test_onnx_dynamic_observer_init(onnx_dynamic_observer): # Assert that initialization parameters are set correctly assert onnx_dynamic_observer.dtype == torch.qint8 assert onnx_dynamic_observer.qmin == -128 assert onnx_dynamic_observer.qmax == 127 def test_onnx_dynamic_observer_call(onnx_dynamic_observer): x = torch.tensor([[-1.0, 0.0, 1.0]]) onnx_dynamic_observer(x) # Assert that `min_val` and `max_val` are set correctly assert onnx_dynamic_observer.min_val == -1.0 assert onnx_dynamic_observer.max_val == 1.0 def test_onnx_dynamic_observer_calculate_qparams(onnx_dynamic_observer): x = torch.tensor([[-1.0, 0.0, 1.0]]) onnx_dynamic_observer(x) # Assert that `scale` and `zero_pointer` are set correctly scale, zero_pointer = onnx_dynamic_observer.calculate_qparams() assert scale == pytest.approx(1.0 / 127) assert zero_pointer == 0
archai/tests/quantization/test_observers.py/0
{ "file_path": "archai/tests/quantization/test_observers.py", "repo_id": "archai", "token_count": 474 }
346
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from archai.trainers.nlp.nvidia_training_args import NvidiaTrainingArguments def test_nvidia_training_arguments(): # Assert that the default values are correct args = NvidiaTrainingArguments("tmp", no_cuda=True) assert args.experiment_name == "tmp" assert args.checkpoint_file_path == "" assert os.path.basename(os.path.dirname(args.output_dir)) == "logdir" assert args.seed == 42 assert args.no_cuda is True assert args.logging_steps == 10 assert args.do_eval is True assert args.eval_steps == 100 assert args.save_all_checkpoints is False assert args.dataset_name == "wt103" assert os.path.basename(os.path.normpath(args.dataset_dir)) == "wikitext-103" assert os.path.basename(os.path.normpath(args.dataset_cache_dir)) == "cache" assert args.dataset_refresh_cache is False assert args.vocab_type == "gpt2" assert args.vocab_size == 10000 assert args.iterator_roll is True assert args.global_batch_size == 256 assert args.per_device_global_batch_size is None assert args.seq_len == 192 assert args.strategy == "ddp" assert args.local_rank == 0 assert args.find_unused_parameters is False assert args.max_steps == 40000 assert args.gradient_accumulation_steps == 1 assert not args.fp16 assert args.optim == "jitlamb" assert args.learning_rate == 0.01 assert args.weight_decay == 0.0 assert args.momentum == 0.0 assert args.max_grad_norm == 0.25 assert args.lr_scheduler_type == "cosine" assert args.lr_qat_scheduler_type == "cosine" assert args.lr_scheduler_max_steps is None assert args.lr_scheduler_warmup_steps == 1000 assert args.lr_scheduler_patience == 0 assert args.lr_scheduler_min_lr == 0.001 assert args.lr_scheduler_decay_rate == 0.5 assert not args.qat assert not args.mixed_qat os.rmdir("tmp")
archai/tests/trainers/nlp/test_nvidia_training_args.py/0
{ "file_path": "archai/tests/trainers/nlp/test_nvidia_training_args.py", "repo_id": "archai", "token_count": 738 }
347
param ( [switch] $KeepPsReadLine = $false ) $tempFile = [IO.Path]::GetTempFileName() cmd.exe /C "$PSScriptRoot\init.cmd && set>$tempFile" $lines = [System.IO.File]::ReadAllLines("$tempFile") $curLoc = get-location $lines|ForEach-Object -Begin { set-location env: } -End { set-location $curLoc } -Process { $var = $_.Split('=') if ($var.length -gt 1 -and $var[0] -ne "") { set-item -path $var[0] -value $var[1] } } remove-item $tempFile # Set up aliases # On Windows 10, PSReadLine is installed by default and it breaks doskey macros. # Remove it from this particular PowerShell window before running doskey, unless # the user has explicitly told us to keep it active. if ((Get-Module PSReadLine) -and ($KeepPsReadLine -eq $false)) { # remove PSReadLine because it does not get along well with doskey Remove-Module PSReadLine # note: using doskey because Set-Alias is not as powerful # NOTE commands in macros.txt work in both Powershell and cmd. Keep it that way! # Only add macros to macros.ps.txt when the same macro cannot be used in both Powershell and cmd. # In that case, add equivalent macros to both macros.ps.txt and macros.cmd.txt, to ensure that # the Powershell and cmd development environments remain functionally identical. doskey /exename=powershell.exe /MACROFILE="$PSScriptRoot\macros.txt" doskey /exename=powershell.exe /MACROFILE="$PSScriptRoot\macros.ps.txt" }
azure-devops-python-api/scripts/windows/init.ps1/0
{ "file_path": "azure-devops-python-api/scripts/windows/init.ps1", "repo_id": "azure-devops-python-api", "token_count": 478 }
348
# coding=utf-8 # pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class BlobDetails(_serialization.Model): """Blob details. All required parameters must be populated in order to send to server. :ivar container_name: The container name. Required. :vartype container_name: str :ivar blob_name: The blob name. :vartype blob_name: str """ _validation = { "container_name": {"required": True}, } _attribute_map = { "container_name": {"key": "containerName", "type": "str"}, "blob_name": {"key": "blobName", "type": "str"}, } def __init__(self, *, container_name: str, blob_name: Optional[str] = None, **kwargs: Any) -> None: """ :keyword container_name: The container name. Required. :paramtype container_name: str :keyword blob_name: The blob name. :paramtype blob_name: str """ super().__init__(**kwargs) self.container_name = container_name self.blob_name = blob_name class CostEstimate(_serialization.Model): """The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :ivar currency_code: The currency code. :vartype currency_code: str :ivar events: List of usage events. :vartype events: list[~azure.quantum._client.models.UsageEvent] :ivar estimated_total: The estimated total. :vartype estimated_total: float """ _attribute_map = { "currency_code": {"key": "currencyCode", "type": "str"}, "events": {"key": "events", "type": "[UsageEvent]"}, "estimated_total": {"key": "estimatedTotal", "type": "float"}, } def __init__( self, *, currency_code: Optional[str] = None, events: Optional[List["_models.UsageEvent"]] = None, estimated_total: Optional[float] = None, **kwargs: Any ) -> None: """ :keyword currency_code: The currency code. :paramtype currency_code: str :keyword events: List of usage events. :paramtype events: list[~azure.quantum._client.models.UsageEvent] :keyword estimated_total: The estimated total. :paramtype estimated_total: float """ super().__init__(**kwargs) self.currency_code = currency_code self.events = events self.estimated_total = estimated_total class ErrorData(_serialization.Model): """An error response from Azure. All required parameters must be populated in order to send to server. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :vartype code: str :ivar message: A message describing the error, intended to be suitable for displaying in a user interface. Required. :vartype message: str """ _validation = { "code": {"required": True}, "message": {"required": True}, } _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, } def __init__(self, *, code: str, message: str, **kwargs: Any) -> None: """ :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed programmatically. Required. :paramtype code: str :keyword message: A message describing the error, intended to be suitable for displaying in a user interface. Required. :paramtype message: str """ super().__init__(**kwargs) self.code = code self.message = message class ItemDetails(_serialization.Model): """Item details. An item can be a job or a session. You probably want to use the sub-classes and not this class directly. Known sub-classes are: JobDetails, SessionDetails Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to server. :ivar id: The id of the item. Required. :vartype id: str :ivar name: The name of the item. It is not required for the name to be unique and it's only used for display purposes. Required. :vartype name: str :ivar provider_id: The unique identifier for the provider. Required. :vartype provider_id: str :ivar target: The target identifier to run the job. Required. :vartype target: str :ivar item_type: The type of item. Required. Known values are: "Job" and "Session". :vartype item_type: str or ~azure.quantum._client.models.ItemType :ivar creation_time: The creation time of the item. :vartype creation_time: ~datetime.datetime :ivar begin_execution_time: The time when the item began execution. :vartype begin_execution_time: ~datetime.datetime :ivar end_execution_time: The time when the item finished execution. :vartype end_execution_time: ~datetime.datetime :ivar cost_estimate: The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :vartype cost_estimate: ~azure.quantum._client.models.CostEstimate :ivar error_data: An error response from Azure. :vartype error_data: ~azure.quantum._client.models.ErrorData """ _validation = { "id": {"required": True}, "name": {"required": True}, "provider_id": {"required": True}, "target": {"required": True}, "item_type": {"required": True}, "creation_time": {"readonly": True}, "begin_execution_time": {"readonly": True}, "end_execution_time": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "provider_id": {"key": "providerId", "type": "str"}, "target": {"key": "target", "type": "str"}, "item_type": {"key": "itemType", "type": "str"}, "creation_time": {"key": "creationTime", "type": "iso-8601"}, "begin_execution_time": {"key": "beginExecutionTime", "type": "iso-8601"}, "end_execution_time": {"key": "endExecutionTime", "type": "iso-8601"}, "cost_estimate": {"key": "costEstimate", "type": "CostEstimate"}, "error_data": {"key": "errorData", "type": "ErrorData"}, } _subtype_map = {"item_type": {"Job": "JobDetails", "Session": "SessionDetails"}} def __init__( self, *, id: str, # pylint: disable=redefined-builtin name: str, provider_id: str, target: str, cost_estimate: Optional["_models.CostEstimate"] = None, error_data: Optional["_models.ErrorData"] = None, **kwargs: Any ) -> None: """ :keyword id: The id of the item. Required. :paramtype id: str :keyword name: The name of the item. It is not required for the name to be unique and it's only used for display purposes. Required. :paramtype name: str :keyword provider_id: The unique identifier for the provider. Required. :paramtype provider_id: str :keyword target: The target identifier to run the job. Required. :paramtype target: str :keyword cost_estimate: The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :paramtype cost_estimate: ~azure.quantum._client.models.CostEstimate :keyword error_data: An error response from Azure. :paramtype error_data: ~azure.quantum._client.models.ErrorData """ super().__init__(**kwargs) self.id = id self.name = name self.provider_id = provider_id self.target = target self.item_type: Optional[str] = None self.creation_time = None self.begin_execution_time = None self.end_execution_time = None self.cost_estimate = cost_estimate self.error_data = error_data class ItemDetailsList(_serialization.Model): """List of item details. All required parameters must be populated in order to send to server. :ivar value: Required. :vartype value: list[~azure.quantum._client.models.ItemDetails] :ivar next_link: Link to the next page of results. :vartype next_link: str """ _validation = { "value": {"required": True}, } _attribute_map = { "value": {"key": "value", "type": "[ItemDetails]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__(self, *, value: List["_models.ItemDetails"], next_link: Optional[str] = None, **kwargs: Any) -> None: """ :keyword value: Required. :paramtype value: list[~azure.quantum._client.models.ItemDetails] :keyword next_link: Link to the next page of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class JobDetails(ItemDetails): # pylint: disable=too-many-instance-attributes """Job details. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to server. :ivar id: The id of the item. Required. :vartype id: str :ivar name: The name of the item. It is not required for the name to be unique and it's only used for display purposes. Required. :vartype name: str :ivar provider_id: The unique identifier for the provider. Required. :vartype provider_id: str :ivar target: The target identifier to run the job. Required. :vartype target: str :ivar item_type: The type of item. Required. Known values are: "Job" and "Session". :vartype item_type: str or ~azure.quantum._client.models.ItemType :ivar creation_time: The creation time of the item. :vartype creation_time: ~datetime.datetime :ivar begin_execution_time: The time when the item began execution. :vartype begin_execution_time: ~datetime.datetime :ivar end_execution_time: The time when the item finished execution. :vartype end_execution_time: ~datetime.datetime :ivar cost_estimate: The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :vartype cost_estimate: ~azure.quantum._client.models.CostEstimate :ivar error_data: An error response from Azure. :vartype error_data: ~azure.quantum._client.models.ErrorData :ivar job_type: The type of job. Known values are: "Unknown", "QuantumComputing", and "Optimization". :vartype job_type: str or ~azure.quantum._client.models.JobType :ivar session_id: The ID of the session that the job is part of. :vartype session_id: str :ivar container_uri: The blob container SAS uri, the container is used to host job data. Required. :vartype container_uri: str :ivar input_data_uri: The input blob SAS uri, if specified, it will override the default input blob in the container. :vartype input_data_uri: str :ivar input_data_format: The format of the input data. Required. :vartype input_data_format: str :ivar input_params: The input parameters for the job. JSON object used by the target solver. It is expected that the size of this object is small and only used to specify parameters for the execution target, not the input data. :vartype input_params: JSON :ivar status: The status of the job. Known values are: "Waiting", "Executing", "Succeeded", "Failed", and "Cancelled". :vartype status: str or ~azure.quantum._client.models.JobStatus :ivar metadata: The job metadata. Metadata provides client the ability to store client-specific information. :vartype metadata: dict[str, str] :ivar output_data_uri: The output blob SAS uri. When a job finishes successfully, results will be uploaded to this blob. :vartype output_data_uri: str :ivar output_data_format: The format of the output data. :vartype output_data_format: str :ivar cancellation_time: The time when a job was successfully cancelled. :vartype cancellation_time: ~datetime.datetime :ivar quantum_computing_data: Quantum computing data. :vartype quantum_computing_data: ~azure.quantum._client.models.QuantumComputingData :ivar tags: List of user-supplied tags associated with the job. :vartype tags: list[str] """ _validation = { "id": {"required": True}, "name": {"required": True}, "provider_id": {"required": True}, "target": {"required": True}, "item_type": {"required": True}, "creation_time": {"readonly": True}, "begin_execution_time": {"readonly": True}, "end_execution_time": {"readonly": True}, "job_type": {"readonly": True}, "container_uri": {"required": True}, "input_data_format": {"required": True}, "status": {"readonly": True}, "cancellation_time": {"readonly": True}, "quantum_computing_data": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "provider_id": {"key": "providerId", "type": "str"}, "target": {"key": "target", "type": "str"}, "item_type": {"key": "itemType", "type": "str"}, "creation_time": {"key": "creationTime", "type": "iso-8601"}, "begin_execution_time": {"key": "beginExecutionTime", "type": "iso-8601"}, "end_execution_time": {"key": "endExecutionTime", "type": "iso-8601"}, "cost_estimate": {"key": "costEstimate", "type": "CostEstimate"}, "error_data": {"key": "errorData", "type": "ErrorData"}, "job_type": {"key": "jobType", "type": "str"}, "session_id": {"key": "sessionId", "type": "str"}, "container_uri": {"key": "containerUri", "type": "str"}, "input_data_uri": {"key": "inputDataUri", "type": "str"}, "input_data_format": {"key": "inputDataFormat", "type": "str"}, "input_params": {"key": "inputParams", "type": "object"}, "status": {"key": "status", "type": "str"}, "metadata": {"key": "metadata", "type": "{str}"}, "output_data_uri": {"key": "outputDataUri", "type": "str"}, "output_data_format": {"key": "outputDataFormat", "type": "str"}, "cancellation_time": {"key": "cancellationTime", "type": "iso-8601"}, "quantum_computing_data": {"key": "quantumComputingData", "type": "QuantumComputingData"}, "tags": {"key": "tags", "type": "[str]"}, } def __init__( self, *, id: str, # pylint: disable=redefined-builtin name: str, provider_id: str, target: str, container_uri: str, input_data_format: str, cost_estimate: Optional["_models.CostEstimate"] = None, error_data: Optional["_models.ErrorData"] = None, session_id: Optional[str] = None, input_data_uri: Optional[str] = None, input_params: Optional[JSON] = None, metadata: Optional[Dict[str, str]] = None, output_data_uri: Optional[str] = None, output_data_format: Optional[str] = None, tags: Optional[List[str]] = None, **kwargs: Any ) -> None: """ :keyword id: The id of the item. Required. :paramtype id: str :keyword name: The name of the item. It is not required for the name to be unique and it's only used for display purposes. Required. :paramtype name: str :keyword provider_id: The unique identifier for the provider. Required. :paramtype provider_id: str :keyword target: The target identifier to run the job. Required. :paramtype target: str :keyword cost_estimate: The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :paramtype cost_estimate: ~azure.quantum._client.models.CostEstimate :keyword error_data: An error response from Azure. :paramtype error_data: ~azure.quantum._client.models.ErrorData :keyword session_id: The ID of the session that the job is part of. :paramtype session_id: str :keyword container_uri: The blob container SAS uri, the container is used to host job data. Required. :paramtype container_uri: str :keyword input_data_uri: The input blob SAS uri, if specified, it will override the default input blob in the container. :paramtype input_data_uri: str :keyword input_data_format: The format of the input data. Required. :paramtype input_data_format: str :keyword input_params: The input parameters for the job. JSON object used by the target solver. It is expected that the size of this object is small and only used to specify parameters for the execution target, not the input data. :paramtype input_params: JSON :keyword metadata: The job metadata. Metadata provides client the ability to store client-specific information. :paramtype metadata: dict[str, str] :keyword output_data_uri: The output blob SAS uri. When a job finishes successfully, results will be uploaded to this blob. :paramtype output_data_uri: str :keyword output_data_format: The format of the output data. :paramtype output_data_format: str :keyword tags: List of user-supplied tags associated with the job. :paramtype tags: list[str] """ super().__init__( id=id, name=name, provider_id=provider_id, target=target, cost_estimate=cost_estimate, error_data=error_data, **kwargs ) self.item_type: str = "Job" self.job_type = None self.session_id = session_id self.container_uri = container_uri self.input_data_uri = input_data_uri self.input_data_format = input_data_format self.input_params = input_params self.status = None self.metadata = metadata self.output_data_uri = output_data_uri self.output_data_format = output_data_format self.cancellation_time = None self.quantum_computing_data = None self.tags = tags class JobDetailsList(_serialization.Model): """List of job details. :ivar value: :vartype value: list[~azure.quantum._client.models.JobDetails] :ivar next_link: Link to the next page of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[JobDetails]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.JobDetails"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: :paramtype value: list[~azure.quantum._client.models.JobDetails] :keyword next_link: Link to the next page of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class JsonPatchDocument(_serialization.Model): """A JSONPatch document as defined by RFC 6902. All required parameters must be populated in order to send to server. :ivar op: The operation to be performed. Required. Known values are: "add", "remove", "replace", "move", "copy", and "test". :vartype op: str or ~azure.quantum._client.models.JsonPatchOperation :ivar path: A JSON-Pointer. Required. :vartype path: str :ivar value: A value to be used in the operation on the path. :vartype value: JSON :ivar from_property: Optional field used in copy and move operations. :vartype from_property: str """ _validation = { "op": {"required": True}, "path": {"required": True}, } _attribute_map = { "op": {"key": "op", "type": "str"}, "path": {"key": "path", "type": "str"}, "value": {"key": "value", "type": "object"}, "from_property": {"key": "from", "type": "str"}, } def __init__( self, *, op: Union[str, "_models.JsonPatchOperation"], path: str, value: Optional[JSON] = None, from_property: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword op: The operation to be performed. Required. Known values are: "add", "remove", "replace", "move", "copy", and "test". :paramtype op: str or ~azure.quantum._client.models.JsonPatchOperation :keyword path: A JSON-Pointer. Required. :paramtype path: str :keyword value: A value to be used in the operation on the path. :paramtype value: JSON :keyword from_property: Optional field used in copy and move operations. :paramtype from_property: str """ super().__init__(**kwargs) self.op = op self.path = path self.value = value self.from_property = from_property class ProviderStatus(_serialization.Model): """Providers status. :ivar id: Provider id. :vartype id: str :ivar current_availability: Provider availability. Known values are: "Available", "Degraded", and "Unavailable". :vartype current_availability: str or ~azure.quantum._client.models.ProviderAvailability :ivar targets: :vartype targets: list[~azure.quantum._client.models.TargetStatus] """ _attribute_map = { "id": {"key": "id", "type": "str"}, "current_availability": {"key": "currentAvailability", "type": "str"}, "targets": {"key": "targets", "type": "[TargetStatus]"}, } def __init__( self, *, id: Optional[str] = None, # pylint: disable=redefined-builtin current_availability: Optional[Union[str, "_models.ProviderAvailability"]] = None, targets: Optional[List["_models.TargetStatus"]] = None, **kwargs: Any ) -> None: """ :keyword id: Provider id. :paramtype id: str :keyword current_availability: Provider availability. Known values are: "Available", "Degraded", and "Unavailable". :paramtype current_availability: str or ~azure.quantum._client.models.ProviderAvailability :keyword targets: :paramtype targets: list[~azure.quantum._client.models.TargetStatus] """ super().__init__(**kwargs) self.id = id self.current_availability = current_availability self.targets = targets class ProviderStatusList(_serialization.Model): """Providers status. :ivar value: :vartype value: list[~azure.quantum._client.models.ProviderStatus] :ivar next_link: Link to the next page of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[ProviderStatus]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.ProviderStatus"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: :paramtype value: list[~azure.quantum._client.models.ProviderStatus] :keyword next_link: Link to the next page of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class QuantumComputingData(_serialization.Model): """Quantum computing data. :ivar count: The number of quantum computing items in the job. :vartype count: int """ _attribute_map = { "count": {"key": "count", "type": "int"}, } def __init__(self, *, count: Optional[int] = None, **kwargs: Any) -> None: """ :keyword count: The number of quantum computing items in the job. :paramtype count: int """ super().__init__(**kwargs) self.count = count class Quota(_serialization.Model): """Quota information. :ivar dimension: The name of the dimension associated with the quota. :vartype dimension: str :ivar scope: The scope at which the quota is applied. Known values are: "Workspace" and "Subscription". :vartype scope: str or ~azure.quantum._client.models.DimensionScope :ivar provider_id: The unique identifier for the provider. :vartype provider_id: str :ivar utilization: The amount of the usage that has been applied for the current period. :vartype utilization: float :ivar holds: The amount of the usage that has been reserved but not applied for the current period. :vartype holds: float :ivar limit: The maximum amount of usage allowed for the current period. :vartype limit: float :ivar period: The time period in which the quota's underlying meter is accumulated. Based on calendar year. 'None' is used for concurrent quotas. Known values are: "None" and "Monthly". :vartype period: str or ~azure.quantum._client.models.MeterPeriod """ _attribute_map = { "dimension": {"key": "dimension", "type": "str"}, "scope": {"key": "scope", "type": "str"}, "provider_id": {"key": "providerId", "type": "str"}, "utilization": {"key": "utilization", "type": "float"}, "holds": {"key": "holds", "type": "float"}, "limit": {"key": "limit", "type": "float"}, "period": {"key": "period", "type": "str"}, } def __init__( self, *, dimension: Optional[str] = None, scope: Optional[Union[str, "_models.DimensionScope"]] = None, provider_id: Optional[str] = None, utilization: Optional[float] = None, holds: Optional[float] = None, limit: Optional[float] = None, period: Optional[Union[str, "_models.MeterPeriod"]] = None, **kwargs: Any ) -> None: """ :keyword dimension: The name of the dimension associated with the quota. :paramtype dimension: str :keyword scope: The scope at which the quota is applied. Known values are: "Workspace" and "Subscription". :paramtype scope: str or ~azure.quantum._client.models.DimensionScope :keyword provider_id: The unique identifier for the provider. :paramtype provider_id: str :keyword utilization: The amount of the usage that has been applied for the current period. :paramtype utilization: float :keyword holds: The amount of the usage that has been reserved but not applied for the current period. :paramtype holds: float :keyword limit: The maximum amount of usage allowed for the current period. :paramtype limit: float :keyword period: The time period in which the quota's underlying meter is accumulated. Based on calendar year. 'None' is used for concurrent quotas. Known values are: "None" and "Monthly". :paramtype period: str or ~azure.quantum._client.models.MeterPeriod """ super().__init__(**kwargs) self.dimension = dimension self.scope = scope self.provider_id = provider_id self.utilization = utilization self.holds = holds self.limit = limit self.period = period class QuotaList(_serialization.Model): """List of quotas. :ivar value: :vartype value: list[~azure.quantum._client.models.Quota] :ivar next_link: Link to the next page of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[Quota]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.Quota"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: :paramtype value: list[~azure.quantum._client.models.Quota] :keyword next_link: Link to the next page of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class RestError(_serialization.Model): """Error information returned by the API. All required parameters must be populated in order to send to server. :ivar error: An error response from Azure. Required. :vartype error: ~azure.quantum._client.models.ErrorData """ _validation = { "error": {"required": True}, } _attribute_map = { "error": {"key": "error", "type": "ErrorData"}, } def __init__(self, *, error: "_models.ErrorData", **kwargs: Any) -> None: """ :keyword error: An error response from Azure. Required. :paramtype error: ~azure.quantum._client.models.ErrorData """ super().__init__(**kwargs) self.error = error class SasUriResponse(_serialization.Model): """Get SAS URL operation response. :ivar sas_uri: A URL with a SAS token to upload a blob for execution in the given workspace. :vartype sas_uri: str """ _attribute_map = { "sas_uri": {"key": "sasUri", "type": "str"}, } def __init__(self, *, sas_uri: Optional[str] = None, **kwargs: Any) -> None: """ :keyword sas_uri: A URL with a SAS token to upload a blob for execution in the given workspace. :paramtype sas_uri: str """ super().__init__(**kwargs) self.sas_uri = sas_uri class SessionDetails(ItemDetails): # pylint: disable=too-many-instance-attributes """Session details. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to server. :ivar id: The id of the item. Required. :vartype id: str :ivar name: The name of the item. It is not required for the name to be unique and it's only used for display purposes. Required. :vartype name: str :ivar provider_id: The unique identifier for the provider. Required. :vartype provider_id: str :ivar target: The target identifier to run the job. Required. :vartype target: str :ivar item_type: The type of item. Required. Known values are: "Job" and "Session". :vartype item_type: str or ~azure.quantum._client.models.ItemType :ivar creation_time: The creation time of the item. :vartype creation_time: ~datetime.datetime :ivar begin_execution_time: The time when the item began execution. :vartype begin_execution_time: ~datetime.datetime :ivar end_execution_time: The time when the item finished execution. :vartype end_execution_time: ~datetime.datetime :ivar cost_estimate: The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :vartype cost_estimate: ~azure.quantum._client.models.CostEstimate :ivar error_data: An error response from Azure. :vartype error_data: ~azure.quantum._client.models.ErrorData :ivar job_failure_policy: Policy controlling the behavior of the Session when a job in the session fails. Known values are: "Abort" and "Continue". :vartype job_failure_policy: str or ~azure.quantum._client.models.SessionJobFailurePolicy :ivar status: The status of the session. Known values are: "Waiting", "Executing", "Succeeded", "Failed", "Failure(s)", and "TimedOut". :vartype status: str or ~azure.quantum._client.models.SessionStatus """ _validation = { "id": {"required": True}, "name": {"required": True}, "provider_id": {"required": True}, "target": {"required": True}, "item_type": {"required": True}, "creation_time": {"readonly": True}, "begin_execution_time": {"readonly": True}, "end_execution_time": {"readonly": True}, "status": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "provider_id": {"key": "providerId", "type": "str"}, "target": {"key": "target", "type": "str"}, "item_type": {"key": "itemType", "type": "str"}, "creation_time": {"key": "creationTime", "type": "iso-8601"}, "begin_execution_time": {"key": "beginExecutionTime", "type": "iso-8601"}, "end_execution_time": {"key": "endExecutionTime", "type": "iso-8601"}, "cost_estimate": {"key": "costEstimate", "type": "CostEstimate"}, "error_data": {"key": "errorData", "type": "ErrorData"}, "job_failure_policy": {"key": "jobFailurePolicy", "type": "str"}, "status": {"key": "status", "type": "str"}, } def __init__( self, *, id: str, # pylint: disable=redefined-builtin name: str, provider_id: str, target: str, cost_estimate: Optional["_models.CostEstimate"] = None, error_data: Optional["_models.ErrorData"] = None, job_failure_policy: Union[str, "_models.SessionJobFailurePolicy"] = "Abort", **kwargs: Any ) -> None: """ :keyword id: The id of the item. Required. :paramtype id: str :keyword name: The name of the item. It is not required for the name to be unique and it's only used for display purposes. Required. :paramtype name: str :keyword provider_id: The unique identifier for the provider. Required. :paramtype provider_id: str :keyword target: The target identifier to run the job. Required. :paramtype target: str :keyword cost_estimate: The job cost billed by the provider. The final cost on your bill might be slightly different due to added taxes and currency conversion rates. :paramtype cost_estimate: ~azure.quantum._client.models.CostEstimate :keyword error_data: An error response from Azure. :paramtype error_data: ~azure.quantum._client.models.ErrorData :keyword job_failure_policy: Policy controlling the behavior of the Session when a job in the session fails. Known values are: "Abort" and "Continue". :paramtype job_failure_policy: str or ~azure.quantum._client.models.SessionJobFailurePolicy """ super().__init__( id=id, name=name, provider_id=provider_id, target=target, cost_estimate=cost_estimate, error_data=error_data, **kwargs ) self.item_type: str = "Session" self.job_failure_policy = job_failure_policy self.status = None class SessionDetailsList(_serialization.Model): """List of session details. :ivar value: :vartype value: list[~azure.quantum._client.models.SessionDetails] :ivar next_link: Link to the next page of results. :vartype next_link: str """ _attribute_map = { "value": {"key": "value", "type": "[SessionDetails]"}, "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, value: Optional[List["_models.SessionDetails"]] = None, next_link: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword value: :paramtype value: list[~azure.quantum._client.models.SessionDetails] :keyword next_link: Link to the next page of results. :paramtype next_link: str """ super().__init__(**kwargs) self.value = value self.next_link = next_link class TargetStatus(_serialization.Model): """Target status. :ivar id: Target id. :vartype id: str :ivar current_availability: Target availability. Known values are: "Available", "Degraded", and "Unavailable". :vartype current_availability: str or ~azure.quantum._client.models.TargetAvailability :ivar average_queue_time: Average queue time in seconds. :vartype average_queue_time: int :ivar status_page: A page with detailed status of the provider. :vartype status_page: str """ _attribute_map = { "id": {"key": "id", "type": "str"}, "current_availability": {"key": "currentAvailability", "type": "str"}, "average_queue_time": {"key": "averageQueueTime", "type": "int"}, "status_page": {"key": "statusPage", "type": "str"}, } def __init__( self, *, id: Optional[str] = None, # pylint: disable=redefined-builtin current_availability: Optional[Union[str, "_models.TargetAvailability"]] = None, average_queue_time: Optional[int] = None, status_page: Optional[str] = None, **kwargs: Any ) -> None: """ :keyword id: Target id. :paramtype id: str :keyword current_availability: Target availability. Known values are: "Available", "Degraded", and "Unavailable". :paramtype current_availability: str or ~azure.quantum._client.models.TargetAvailability :keyword average_queue_time: Average queue time in seconds. :paramtype average_queue_time: int :keyword status_page: A page with detailed status of the provider. :paramtype status_page: str """ super().__init__(**kwargs) self.id = id self.current_availability = current_availability self.average_queue_time = average_queue_time self.status_page = status_page class UsageEvent(_serialization.Model): """Usage event details. :ivar dimension_id: The dimension id. :vartype dimension_id: str :ivar dimension_name: The dimension name. :vartype dimension_name: str :ivar measure_unit: The unit of measure. :vartype measure_unit: str :ivar amount_billed: The amount billed. :vartype amount_billed: float :ivar amount_consumed: The amount consumed. :vartype amount_consumed: float :ivar unit_price: The unit price. :vartype unit_price: float """ _attribute_map = { "dimension_id": {"key": "dimensionId", "type": "str"}, "dimension_name": {"key": "dimensionName", "type": "str"}, "measure_unit": {"key": "measureUnit", "type": "str"}, "amount_billed": {"key": "amountBilled", "type": "float"}, "amount_consumed": {"key": "amountConsumed", "type": "float"}, "unit_price": {"key": "unitPrice", "type": "float"}, } def __init__( self, *, dimension_id: Optional[str] = None, dimension_name: Optional[str] = None, measure_unit: Optional[str] = None, amount_billed: Optional[float] = None, amount_consumed: Optional[float] = None, unit_price: Optional[float] = None, **kwargs: Any ) -> None: """ :keyword dimension_id: The dimension id. :paramtype dimension_id: str :keyword dimension_name: The dimension name. :paramtype dimension_name: str :keyword measure_unit: The unit of measure. :paramtype measure_unit: str :keyword amount_billed: The amount billed. :paramtype amount_billed: float :keyword amount_consumed: The amount consumed. :paramtype amount_consumed: float :keyword unit_price: The unit price. :paramtype unit_price: float """ super().__init__(**kwargs) self.dimension_id = dimension_id self.dimension_name = dimension_name self.measure_unit = measure_unit self.amount_billed = amount_billed self.amount_consumed = amount_consumed self.unit_price = unit_price
azure-quantum-python/azure-quantum/azure/quantum/_client/models/_models.py/0
{ "file_path": "azure-quantum-python/azure-quantum/azure/quantum/_client/models/_models.py", "repo_id": "azure-quantum-python", "token_count": 15839 }
349
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## import numpy as np from typing import TYPE_CHECKING, Any, Dict, Sequence from azure.quantum.cirq.targets.target import Target as CirqTarget from azure.quantum.cirq.job import Job as CirqJob from azure.quantum.target.quantinuum import Quantinuum if TYPE_CHECKING: import cirq from azure.quantum import Workspace from azure.quantum import Job as AzureJob class QuantinuumTarget(Quantinuum, CirqTarget): """Base class for interfacing with an Quantinuum backend in Azure Quantum""" def __init__( self, workspace: "Workspace", name: str, input_data_format: str = "honeywell.openqasm.v1", output_data_format: str = "honeywell.quantum-results.v1", provider_id: str = "quantinuum", content_type: str = "application/qasm", encoding: str = "", **kwargs ): super().__init__( workspace=workspace, name=name, input_data_format=input_data_format, output_data_format=output_data_format, provider_id=provider_id, content_type=content_type, encoding=encoding, **kwargs ) @staticmethod def _translate_cirq_circuit(circuit) -> str: """Translate `cirq` circuit to OpenQASM 2.0.""" return circuit.to_qasm() @staticmethod def _to_cirq_result(result: Dict[str, Any], param_resolver, **kwargs): from cirq import ResultDict measurements = { key.lstrip("m_"): np.array([[int(_v)] for _v in value]) for key, value in result.items() if key.startswith("m_") } return ResultDict(params=param_resolver, measurements=measurements) def _to_cirq_job(self, azure_job: "AzureJob", program: "cirq.Circuit" = None): """Convert Azure job to Cirq job""" if "measurement_dict" not in azure_job.details.metadata and program is None: raise ValueError("Parameter 'measurement_dict' not found in job metadata.") measurement_dict = azure_job.details.metadata.get("measurement_dict") return CirqJob(azure_job=azure_job, program=program, measurement_dict=measurement_dict) @staticmethod def _measurement_dict(program) -> Dict[str, Sequence[int]]: """Returns a dictionary of measurement keys to target qubit index.""" from cirq import MeasurementGate measurements = [ op for op in program.all_operations() if isinstance(op.gate, MeasurementGate) ] return { meas.gate.key: [q.x for q in meas.qubits] for meas in measurements } def estimate_cost( self, program: str, repetitions: int ) -> float: """Estimate cost for running this program :param program: Cirq quantum program :type program: str, optional :param repetitions: Number of repetitions :type repetitions: int, optional :return: Price estimate in HQC :rtype: float """ serialized_program = self._translate_circuit(program) return super().estimate_cost( circuit=serialized_program, shots=repetitions ) def submit( self, program: "cirq.Circuit", name: str = "cirq-job", repetitions: int = 500, **kwargs ) -> "CirqJob": """Submit a Cirq quantum circuit :param program: Quantum program :type program: cirq.Circuit :param name: Job name :type name: str :param repetitions: Number of shots, defaults to provider default value :type repetitions: int :return: Azure Quantum job :rtype: Job """ serialized_program = self._translate_circuit(program) metadata = { "qubits": len(program.all_qubits()), "repetitions": repetitions, "measurement_dict": self._measurement_dict(program) } # Override metadata with value from kwargs metadata.update(kwargs.get("metadata", {})) azure_job = super().submit( circuit=serialized_program, name=name, num_shots=repetitions, metadata=metadata, **kwargs ) return self._to_cirq_job(azure_job=azure_job)
azure-quantum-python/azure-quantum/azure/quantum/cirq/targets/quantinuum.py/0
{ "file_path": "azure-quantum-python/azure-quantum/azure/quantum/cirq/targets/quantinuum.py", "repo_id": "azure-quantum-python", "token_count": 1942 }
350
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## from typing import Dict, List, Union from azure.quantum.qiskit.job import AzureQuantumJob from azure.quantum.version import __version__ import warnings from .backend import AzureBackend, AzureQirBackend from abc import abstractmethod from qiskit import QuantumCircuit from qiskit.providers.models import BackendConfiguration from qiskit.providers import Options from qiskit.providers import Provider from qiskit.qasm2 import dumps import logging logger = logging.getLogger(__name__) __all__ = [ "QuantinuumSyntaxCheckerBackend", "QuantinuumEmulatorBackend", "QuantinuumQPUBackend", "QuantinuumEmulatorQirBackend", "QuantinuumSyntaxCheckerQirBackend", "QuantinuumQPUQirBackend", ] QUANTINUUM_BASIS_GATES = [ "x", "y", "z", "rx", "ry", "rz", "h", "cx", "cz", "s", "sdg", "t", "tdg", "v", "vdg", "zz", "measure", "reset", ] QUANTINUUM_PROVIDER_ID = "quantinuum" QUANTINUUM_PROVIDER_NAME = "Quantinuum" def _get_n_qubits(name): name = name.lower() if ".h1-" in name or "hqs-lt" in name: return 20 if ".h2-" in name: return 32 warnings.warn( UserWarning(f"Number of qubits not known for target {name}. Defaulting to 20.")) return 20 _QUANTINUUM_COUNT_INPUT_PARAM_NAME = "count" _DEFAULT_SHOTS_COUNT = 500 class QuantinuumQirBackendBase(AzureQirBackend): _SHOTS_PARAM_NAME = _QUANTINUUM_COUNT_INPUT_PARAM_NAME @abstractmethod def __init__( self, configuration: BackendConfiguration, provider: Provider = None, **fields ): super().__init__(configuration, provider, **fields) @classmethod def _default_options(cls) -> Options: return Options( **{ cls._SHOTS_PARAM_NAME: _DEFAULT_SHOTS_COUNT }, targetCapability="BasicExecution", ) def _azure_config(self) -> Dict[str, str]: config = super()._azure_config() config.update( { "provider_id": QUANTINUUM_PROVIDER_ID, } ) return config def _get_n_qubits(self, name): return _get_n_qubits(name) class QuantinuumSyntaxCheckerQirBackend(QuantinuumQirBackendBase): backend_names = ( # Note: Target names on the same line are equivalent. "quantinuum.sim.h1-1sc", "quantinuum.sim.h2-1sc", ) def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs): self._provider_id = QUANTINUUM_PROVIDER_ID self._provider_name = QUANTINUUM_PROVIDER_NAME default_config = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": __version__, "simulator": True, "local": False, "coupling_map": None, "description": f"Quantinuum Syntax Checker on Azure Quantum", "basis_gates": QUANTINUUM_BASIS_GATES, "memory": False, "n_qubits": self._get_n_qubits(name), "conditional": False, "max_shots": None, "max_experiments": 1, "open_pulse": False, "gates": [{"name": "TODO", "parameters": [], "qasm_def": "TODO"}], "azure": self._azure_config(), } ) configuration: BackendConfiguration = kwargs.pop( "configuration", default_config ) logger.info(f"Initializing {self._provider_name}SyntaxCheckerQirBackend") super().__init__(configuration=configuration, provider=provider, **kwargs) class QuantinuumEmulatorQirBackend(QuantinuumQirBackendBase): backend_names = ( # Note: Target names on the same line are equivalent. "quantinuum.sim.h1-1e", "quantinuum.sim.h2-1e", ) def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs): self._provider_id = QUANTINUUM_PROVIDER_ID self._provider_name = QUANTINUUM_PROVIDER_NAME default_config = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": __version__, "simulator": True, "local": False, "coupling_map": None, "description": f"Quantinuum emulator on Azure Quantum", "basis_gates": QUANTINUUM_BASIS_GATES, "memory": False, "n_qubits": self._get_n_qubits(name), "conditional": False, "max_shots": None, "max_experiments": 1, "open_pulse": False, "gates": [{"name": "TODO", "parameters": [], "qasm_def": "TODO"}], "azure": self._azure_config(), } ) configuration: BackendConfiguration = kwargs.pop( "configuration", default_config ) logger.info(f"Initializing {self._provider_name}EmulatorQirBackend") super().__init__(configuration=configuration, provider=provider, **kwargs) class QuantinuumQPUQirBackend(QuantinuumQirBackendBase): backend_names = ( # Note: Target names on the same line are equivalent. "quantinuum.qpu.h1-1", "quantinuum.qpu.h2-1", ) def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs): self._provider_id = QUANTINUUM_PROVIDER_ID self._provider_name = QUANTINUUM_PROVIDER_NAME default_config = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": __version__, "simulator": False, "local": False, "coupling_map": None, "description": f"Quantinuum QPU on Azure Quantum", "basis_gates": QUANTINUUM_BASIS_GATES, "memory": False, "n_qubits": self._get_n_qubits(name), "conditional": False, "max_shots": 10000, "max_experiments": 1, "open_pulse": False, "gates": [{"name": "TODO", "parameters": [], "qasm_def": "TODO"}], "azure": self._azure_config(), } ) configuration: BackendConfiguration = kwargs.pop( "configuration", default_config ) logger.info(f"Initializing {self._provider_name}QPUQirBackend") super().__init__(configuration=configuration, provider=provider, **kwargs) class QuantinuumBackend(AzureBackend): """Base class for interfacing with a Quantinuum (formerly Honeywell) backend in Azure Quantum""" _SHOTS_PARAM_NAME = _QUANTINUUM_COUNT_INPUT_PARAM_NAME @abstractmethod def __init__( self, configuration: BackendConfiguration, provider: Provider = None, **fields ): super().__init__(configuration, provider, **fields) @classmethod def _default_options(cls): return Options( **{ cls._SHOTS_PARAM_NAME: _DEFAULT_SHOTS_COUNT, }, ) def _azure_config(self) -> Dict[str, str]: return { "blob_name": "inputData", "content_type": "application/qasm", "provider_id": self._provider_id, "input_data_format": "honeywell.openqasm.v1", "output_data_format": "honeywell.quantum-results.v1", "is_default": True, } def _translate_input(self, circuit): """Translates the input values to the format expected by the AzureBackend.""" return dumps(circuit) def estimate_cost( self, circuit: QuantumCircuit, shots: int = None, count: int = None ): """Estimate cost for running this circuit :param circuit: Qiskit quantum circuit :type circuit: QuantumCircuit :param shots: Shot count :type shots: int :param count: Shot count (alternative to 'shots') :type count: int """ if count is not None: warnings.warn( "The 'count' parameter will be deprecated. Please, use 'shots' parameter instead.", category=DeprecationWarning, ) shots = count if shots is None: raise ValueError("Missing input argument 'shots'.") input_data = dumps(circuit) workspace = self.provider().get_workspace() target = workspace.get_targets(self.name()) return target.estimate_cost(input_data, shots=shots) def _get_n_qubits(self, name): return _get_n_qubits(name) class QuantinuumSyntaxCheckerBackend(QuantinuumBackend): backend_names = ( # Note: Target names on the same line are equivalent. "quantinuum.sim.h1-1sc", "quantinuum.sim.h2-1sc", ) def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs): self._provider_id = QUANTINUUM_PROVIDER_ID self._provider_name = QUANTINUUM_PROVIDER_NAME default_config = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": __version__, "simulator": True, "local": False, "coupling_map": None, "description": f"Quantinuum Syntax Checker on Azure Quantum", "basis_gates": QUANTINUUM_BASIS_GATES, "memory": False, "n_qubits": self._get_n_qubits(name), "conditional": False, "max_shots": None, "max_experiments": 1, "open_pulse": False, "gates": [{"name": "TODO", "parameters": [], "qasm_def": "TODO"}], "azure": self._azure_config(), } ) configuration: BackendConfiguration = kwargs.pop( "configuration", default_config ) logger.info(f"Initializing {self._provider_name}SyntaxCheckerBackend") super().__init__(configuration=configuration, provider=provider, **kwargs) class QuantinuumEmulatorBackend(QuantinuumBackend): backend_names = ( # Note: Target names on the same line are equivalent. "quantinuum.sim.h1-1e", "quantinuum.sim.h2-1e", ) def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs): self._provider_id = QUANTINUUM_PROVIDER_ID self._provider_name = QUANTINUUM_PROVIDER_NAME default_config = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": __version__, "simulator": True, "local": False, "coupling_map": None, "description": f"Quantinuum emulator on Azure Quantum", "basis_gates": QUANTINUUM_BASIS_GATES, "memory": False, "n_qubits": self._get_n_qubits(name), "conditional": False, "max_shots": None, "max_experiments": 1, "open_pulse": False, "gates": [{"name": "TODO", "parameters": [], "qasm_def": "TODO"}], "azure": self._azure_config(), } ) configuration: BackendConfiguration = kwargs.pop( "configuration", default_config ) logger.info(f"Initializing {self._provider_name}EmulatorBackend") super().__init__(configuration=configuration, provider=provider, **kwargs) class QuantinuumQPUBackend(QuantinuumBackend): backend_names = ( # Note: Target names on the same line are equivalent. "quantinuum.qpu.h1-1", "quantinuum.qpu.h2-1", ) def __init__(self, name: str, provider: "AzureQuantumProvider", **kwargs): self._provider_id = QUANTINUUM_PROVIDER_ID self._provider_name = QUANTINUUM_PROVIDER_NAME default_config = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": __version__, "simulator": False, "local": False, "coupling_map": None, "description": f"Quantinuum QPU on Azure Quantum", "basis_gates": QUANTINUUM_BASIS_GATES, "memory": False, "n_qubits": self._get_n_qubits(name), "conditional": False, "max_shots": 10000, "max_experiments": 1, "open_pulse": False, "gates": [{"name": "TODO", "parameters": [], "qasm_def": "TODO"}], "azure": self._azure_config(), } ) configuration: BackendConfiguration = kwargs.pop( "configuration", default_config ) logger.info(f"Initializing {self._provider_name}QPUBackend") super().__init__(configuration=configuration, provider=provider, **kwargs)
azure-quantum-python/azure-quantum/azure/quantum/qiskit/backends/quantinuum.py/0
{ "file_path": "azure-quantum-python/azure-quantum/azure/quantum/qiskit/backends/quantinuum.py", "repo_id": "azure-quantum-python", "token_count": 6378 }
351
## # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. ## import re import warnings from dataclasses import dataclass, field from typing import Any, Dict, Optional, Type, Union, List from ...job import Job from ...job.base_job import ContentType from ...workspace import Workspace from ..params import InputParams, InputParamsItem, AutoValidatingParams, \ validating_field from ..target import Target from . import MicrosoftEstimatorJob class QubitParams: """ Resource estimator Qubit parameters. """ GATE_US_E3 = "qubit_gate_us_e3" GATE_US_E4 = "qubit_gate_us_e4" GATE_NS_E3 = "qubit_gate_ns_e3" GATE_NS_E4 = "qubit_gate_ns_e4" MAJ_NS_E4 = "qubit_maj_ns_e4" MAJ_NS_E6 = "qubit_maj_ns_e6" class QECScheme: """ Resource estimator QEC Scheme. """ SURFACE_CODE = "surface_code" FLOQUET_CODE = "floquet_code" def _check_error_rate(name, value): if value <= 0.0 or value >= 1.0: raise ValueError(f"{name} must be between 0 and 1") def _check_error_rate_or_process_and_readout(name, value): if value is None: return if isinstance(value, float): _check_error_rate(name, value) return if not isinstance(value, MeasurementErrorRate): raise ValueError(f"{name} must be either a float or " "MeasurementErrorRate with two fields: 'process' and 'readout'") def check_time(name, value): pat = r"^(\+?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s*(s|ms|ΞΌs|Β΅s|us|ns)$" if re.match(pat, value) is None: raise ValueError(f"{name} is not a valid time string; use a " "suffix s, ms, us, or ns") @dataclass class MeasurementErrorRate(AutoValidatingParams): process: float = field(metadata={"validate": _check_error_rate}) readout: float = field(metadata={"validate": _check_error_rate}) @dataclass class MicrosoftEstimatorQubitParams(AutoValidatingParams): @staticmethod def check_instruction_set(name, value): if value not in ["gate-based", "gate_based", "GateBased", "gateBased", "Majorana", "majorana"]: raise ValueError(f"{name} must be GateBased or Majorana") name: Optional[str] = None instruction_set: Optional[str] = validating_field(check_instruction_set) one_qubit_measurement_time: Optional[str] = validating_field(check_time) two_qubit_joint_measurement_time: Optional[str] = \ validating_field(check_time) one_qubit_gate_time: Optional[str] = validating_field(check_time) two_qubit_gate_time: Optional[str] = validating_field(check_time) t_gate_time: Optional[str] = validating_field(check_time) one_qubit_measurement_error_rate: Union[None, float, MeasurementErrorRate] = \ validating_field(_check_error_rate_or_process_and_readout) two_qubit_joint_measurement_error_rate: Union[None, float, MeasurementErrorRate] = \ validating_field(_check_error_rate_or_process_and_readout) one_qubit_gate_error_rate: Optional[float] = \ validating_field(_check_error_rate) two_qubit_gate_error_rate: Optional[float] = \ validating_field(_check_error_rate) t_gate_error_rate: Optional[float] = validating_field(_check_error_rate) idle_error_rate: Optional[float] = validating_field(_check_error_rate) _default_models = [QubitParams.GATE_US_E3, QubitParams.GATE_US_E4, QubitParams.GATE_NS_E3, QubitParams.GATE_NS_E4, QubitParams.MAJ_NS_E4, QubitParams.MAJ_NS_E6] _gate_based = ["gate-based", "gate_based", "GateBased", "gateBased"] _maj_based = ["Majorana", "majorana"] def post_validation(self, result): # check whether all fields have been specified in case a custom qubit # model is specified custom = result != {} and \ (self.name is None or self.name not in self._default_models) # no further validation needed for non-custom models if not custom: return # instruction set must be set if self.instruction_set is None: raise LookupError("instruction_set must be set for custom qubit " "parameters") # NOTE at this point, we know that instruction set must have valid # value if self.one_qubit_measurement_time is None: raise LookupError("one_qubit_measurement_time must be set") if self.one_qubit_measurement_error_rate is None: raise LookupError("one_qubit_measurement_error_rate must be set") # this only needs to be checked for gate based qubits if self.instruction_set in self._gate_based: if self.one_qubit_gate_time is None: raise LookupError("one_qubit_gate_time must be set") def as_dict(self, validate=True) -> Dict[str, Any]: qubit_params = super().as_dict(validate) if len(qubit_params) != 0: if isinstance(self.one_qubit_measurement_error_rate, MeasurementErrorRate): qubit_params["oneQubitMeasurementErrorRate"] = \ self.one_qubit_measurement_error_rate.as_dict(validate) if isinstance(self.two_qubit_joint_measurement_error_rate, MeasurementErrorRate): qubit_params["twoQubitJointMeasurementErrorRate"] = \ self.two_qubit_joint_measurement_error_rate.as_dict(validate) return qubit_params @dataclass class MicrosoftEstimatorQecScheme(AutoValidatingParams): name: Optional[str] = None error_correction_threshold: Optional[float] = \ validating_field(_check_error_rate) crossing_prefactor: Optional[float] = None logical_cycle_time: Optional[str] = None physical_qubits_per_logical_qubit: Optional[str] = None @dataclass class ProtocolSpecificDistillationUnitSpecification(AutoValidatingParams): num_unit_qubits: Optional[int] = None duration_in_qubit_cycle_time: Optional[int] = None def post_validation(self, result): if self.num_unit_qubits is None: raise LookupError("num_unit_qubits must be set") if self.duration_in_qubit_cycle_time is None: raise LookupError("duration_in_qubit_cycle_time must be set") @dataclass class DistillationUnitSpecification(AutoValidatingParams): name: Optional[str] = None display_name: Optional[str] = None num_input_ts: Optional[int] = None num_output_ts: Optional[int] = None failure_probability_formula: Optional[str] = None output_error_rate_formula: Optional[str] = None physical_qubit_specification: Optional[ProtocolSpecificDistillationUnitSpecification] = None logical_qubit_specification: Optional[ProtocolSpecificDistillationUnitSpecification] = None logical_qubit_specification_first_round_override: \ Optional[ProtocolSpecificDistillationUnitSpecification] = None def has_custom_specification(self): return \ self.display_name is not None \ or self.num_input_ts is not None \ or self.num_output_ts is not None \ or self.failure_probability_formula is not None \ or self.output_error_rate_formula is not None \ or self.physical_qubit_specification is not None \ or self.logical_qubit_specification is not None \ or self.logical_qubit_specification_first_round_override is not None def has_predefined_name(self): return self.name is not None def post_validation(self, result): if not self.has_custom_specification() and not self.has_predefined_name(): raise LookupError("name must be set or custom specification must be provided") if self.has_custom_specification() and self.has_predefined_name(): raise LookupError("If predefined name is provided, " "custom specification is not allowed. " "Either remove name or remove all other " "specification of the distillation unit") if self.has_predefined_name(): return # all other validation is on the server side if self.num_input_ts is None: raise LookupError("num_input_ts must be set") if self.num_output_ts is None: raise LookupError("num_output_ts must be set") if self.failure_probability_formula is None: raise LookupError("failure_probability_formula must be set") if self.output_error_rate_formula is None: raise LookupError("output_error_rate_formula must be set") if self.physical_qubit_specification is not None: self.physical_qubit_specification.post_validation(result) if self.logical_qubit_specification is not None: self.logical_qubit_specification.post_validation(result) if self.logical_qubit_specification_first_round_override is not None: self.logical_qubit_specification_first_round_override.post_validation(result) def as_dict(self, validate=True) -> Dict[str, Any]: specification_dict = super().as_dict(validate) if len(specification_dict) != 0: if self.physical_qubit_specification is not None: physical_qubit_specification_dict = \ self.physical_qubit_specification.as_dict(validate) if len(physical_qubit_specification_dict) != 0: specification_dict["physicalQubitSpecification"] = \ physical_qubit_specification_dict if self.logical_qubit_specification is not None: logical_qubit_specification_dict = \ self.logical_qubit_specification.as_dict(validate) if len(logical_qubit_specification_dict) != 0: specification_dict["logicalQubitSpecification"] = \ logical_qubit_specification_dict if self.logical_qubit_specification_first_round_override is not None: logical_qubit_specification_first_round_override_dict = \ self.logical_qubit_specification_first_round_override.as_dict(validate) if len(logical_qubit_specification_first_round_override_dict) != 0: specification_dict["logicalQubitSpecificationFirstRoundOverride"] = \ logical_qubit_specification_first_round_override_dict return specification_dict @dataclass class ErrorBudgetPartition(AutoValidatingParams): """ Resource estimator error budget partition parameters. """ logical: float = 0.001 / 3 t_states: float = 0.001 / 3 rotations: float = 0.001 / 3 @dataclass class MicrosoftEstimatorConstraints(AutoValidatingParams): """ Resource estimator constraints. """ @staticmethod def at_least_one(name, value): if value < 1: raise ValueError(f"{name} must be at least 1") logical_depth_factor: Optional[float] = validating_field(at_least_one) max_t_factories: Optional[int] = validating_field(at_least_one) max_duration: Optional[int] = validating_field(check_time) max_physical_qubits: Optional[int] = validating_field(at_least_one) def post_validation(self, result): if self.max_duration is not None and self.max_physical_qubits is not None: raise LookupError("Both duration and number of physical qubits constraints are provided, but only one is allowe at a time.") @dataclass class MicrosoftEstimatorProfiling(AutoValidatingParams): @staticmethod def at_most_30(name, value): if value < 0 or value > 30: raise ValueError(f"{name} must be nonnegative and at most 30") call_stack_depth: Optional[int] = validating_field(at_most_30) inline_functions: Optional[bool] = None class MicrosoftEstimatorInputParamsItem(InputParamsItem): """ Input params for microsoft.estimator target :ivar error_budget Total error budget for execution of the algorithm """ def __init__(self): super().__init__() self.qubit_params: MicrosoftEstimatorQubitParams = \ MicrosoftEstimatorQubitParams() self.qec_scheme: MicrosoftEstimatorQecScheme = \ MicrosoftEstimatorQecScheme() self.distillation_unit_specifications = [] # type: List[DistillationUnitSpecification] self.constraints: MicrosoftEstimatorConstraints = \ MicrosoftEstimatorConstraints() self.profiling: MicrosoftEstimatorProfiling = \ MicrosoftEstimatorProfiling() self.error_budget: Optional[Union[float, ErrorBudgetPartition]] = None def as_dict(self, validate=True) -> Dict[str, Any]: result = super().as_dict(validate) qubit_params = self.qubit_params.as_dict(validate) if len(qubit_params) != 0: result["qubitParams"] = qubit_params qec_scheme = self.qec_scheme.as_dict(validate) if len(qec_scheme) != 0: result["qecScheme"] = qec_scheme for specification in self.distillation_unit_specifications: specification_dict = specification.as_dict(validate) if len(specification_dict) != 0: if result.get("distillationUnitSpecifications") is None: result["distillationUnitSpecifications"] = [] result["distillationUnitSpecifications"].append(specification_dict) constraints = self.constraints.as_dict(validate) if len(constraints) != 0: result["constraints"] = constraints profiling = self.profiling.as_dict(validate) if len(profiling) != 0: result["profiling"] = profiling if self.error_budget is not None: if isinstance(self.error_budget, float) or \ isinstance(self.error_budget, int): if validate and \ (self.error_budget <= 0 or self.error_budget >= 1): message = "error_budget must be value between 0 and 1" raise ValueError(message) result["errorBudget"] = self.error_budget elif isinstance(self.error_budget, ErrorBudgetPartition): result["errorBudget"] = self.error_budget.as_dict(validate) return result class MicrosoftEstimatorParams(InputParams, MicrosoftEstimatorInputParamsItem): """ Resource estimator input parameters. """ def __init__(self, num_items: Optional[int] = None): InputParams.__init__( self, num_items=num_items, item_type=MicrosoftEstimatorInputParamsItem) class MicrosoftEstimator(Target): """ Resource estimator target from the microsoft-qc provider. """ target_names = [ "microsoft.estimator" ] def __init__( self, workspace: "Workspace", name: str = "microsoft.estimator", **kwargs ): # There is only a single target name for this target assert name == self.target_names[0] # make sure to not pass argument twice kwargs.pop("provider_id", None) super().__init__( workspace=workspace, name=name, input_data_format="qir.v1", output_data_format="microsoft.resource-estimates.v1", provider_id="microsoft-qc", content_type=ContentType.json, **kwargs ) def submit( self, input_data: Any, name: str = "azure-quantum-job", shots: int = None, input_params: Union[Dict[str, Any], InputParams, None] = None, **kwargs, ) -> Job: """ Submit an estimation job. :param input_data: Input data :type input_data: Any :param name: Job name :type name: str :param shots: Number of shots. Ignored in estimation. Defaults to None :type shots: int :param input_params: Input parameters :type input_params: Dict[str, Any] :return: Azure Quantum job :rtype: Job """ if shots is not None: warnings.warn("The 'shots' parameter is ignored in resource estimation job.") try: from qiskit import QuantumCircuit, transpile from qiskit_qir import to_qir_module from qiskit_qir.visitor import SUPPORTED_INSTRUCTIONS if isinstance(input_data, QuantumCircuit): input_data = transpile(input_data, basis_gates=SUPPORTED_INSTRUCTIONS, optimization_level=0) (module, _) = to_qir_module(input_data, record_output=False) input_data = module.bitcode finally: return super().submit( input_data=input_data, name=name, shots=shots, input_params=input_params, **kwargs ) @classmethod def _get_job_class(cls) -> Type[Job]: return MicrosoftEstimatorJob def _qir_output_data_format(self) -> str: """"Fallback output data format in case of QIR job submission.""" return "microsoft.resource-estimates.v1" def make_params(self, num_items: Optional[int] = None): return MicrosoftEstimatorParams(num_items=num_items)
azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/target.py/0
{ "file_path": "azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/target.py", "repo_id": "azure-quantum-python", "token_count": 7448 }
352
name: azurequantum channels: - quantum-engineering - conda-forge dependencies: - python=3.9 - pip>=22.3.1 - pytest>=7.1.2 - pip: - -e .[all]
azure-quantum-python/azure-quantum/environment.yml/0
{ "file_path": "azure-quantum-python/azure-quantum/environment.yml", "repo_id": "azure-quantum-python", "token_count": 75 }
353
#!/bin/env python # -*- coding: utf-8 -*- ## # setup.py: Installs Python host functionality for azure-quantum. ## # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. ## # IMPORTS # import setuptools import os import glob import re # VERSION INFORMATION # # Our build process sets the PYTHON_VERSION environment variable to a version # string that is compatible with PEP 440, and so we inherit that version number # here and propagate that to qsharp/version.py. # # To make sure that local builds still work without the same environment # variables, we'll default to 0.0.1 as a development version. version = os.environ.get("PYTHON_VERSION", "0.0.1") with open("./azure/quantum/version.py", "w") as f: f.write( f"""# Auto-generated file, do not edit. ## # version.py: Specifies the version of the azure.quantum package. ## # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. ## __version__ = "{version}" """ ) with open("./azure/quantum/_client/_version.py", "w") as f: f.write( f"""# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- VERSION = "{version}" """ ) # DESCRIPTION # # The long description metadata passed to setuptools is used to populate the # PyPI page for this package. Thus, we'll generate the description by using the # same README.md file that we use in the GitHub repo. with open("./README.md", "r") as fh: long_description = fh.read() # LIST OF REQUIREMENTS # def read_requirements(requirement_file: str) -> list[str]: with open(requirement_file, "r") as fh: requirements = fh.readlines() requirements = [v.strip(' \n\r') for v in requirements] requirements = list(filter(None, requirements)) return requirements requirements = read_requirements("requirements.txt") # LIST OF EXTRA/OPTIONAL REQUIREMENTS # # # All `requirements-option.txt` are extra/optional requirements # Identified by the `option`. # # To be used with `pip install azurequantum[option1, option2, ...]` # Example: `pip install azurequantum[qsharp,qiskit]` # # Instead of listing the individual options, you can pass `all` # Example, `pip install azurequantum[all]` extras_require = {} all_requirements = [] for extra_requirement_file in glob.glob("requirements-*.txt"): extra_option = re.match(r"requirements-(\w+)\.txt", extra_requirement_file).group(1) extra_requirements = read_requirements(extra_requirement_file) extras_require[extra_option] = extra_requirements all_requirements.extend(extra_requirements) extras_require["all"] = all_requirements # SETUPTOOLS INVOCATION # setuptools.setup( name="azure-quantum", version=version, author="Microsoft", description="Python client for Azure Quantum", license="MIT License", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/microsoft/azure-quantum-python", packages=setuptools.find_namespace_packages(include=["azure.*"]), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires=">=3.8", install_requires=requirements, extras_require=extras_require )
azure-quantum-python/azure-quantum/setup.py/0
{ "file_path": "azure-quantum-python/azure-quantum/setup.py", "repo_id": "azure-quantum-python", "token_count": 1176 }
354
## # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. ## import unittest from azure.quantum.workspace import Workspace import pytest import numpy as np from cirq import ParamResolver from azure.quantum.job.job import Job from azure.quantum.cirq import AzureQuantumService from azure.quantum.cirq.targets.target import Target from common import QuantumTestBase, ONE_UID, LOCATION, DEFAULT_TIMEOUT_SECS from test_workspace import SIMPLE_RESOURCE_ID class TestCirq(QuantumTestBase): mock_create_job_id_name = "create_job_id" def get_test_job_id(self): return ONE_UID if self.is_playback \ else Job.create_job_id() def _3_qubit_ghz_cirq(self): import cirq # Create qubits q0 = cirq.LineQubit(0) q1 = cirq.LineQubit(1) q2 = cirq.LineQubit(2) # Create a circuit circuit = cirq.Circuit( cirq.H(q0), # H gate cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1'), cirq.measure(q2, key='q2'), ) return circuit def test_plugins_cirq_user_agent(self): # VCR is incompatible with parametrized tests for app_id in [ "test-user-agent", "test-very-very-very-very-very-very-very-very-long-user-agent" ]: workspace = self.create_workspace(user_agent_app_id=app_id) service = AzureQuantumService(workspace=workspace) # pylint: disable=protected-access self.assertIn(app_id, service._workspace.user_agent) self.assertIn("-azure-quantum-cirq", service._workspace.user_agent) def test_cirq_service_init_with_workspace_not_raises_deprecation(self): # testing warning according to https://docs.python.org/3/library/warnings.html#testing-warnings import warnings with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Try to trigger a warning. workspace = Workspace( resource_id=SIMPLE_RESOURCE_ID, location=LOCATION) AzureQuantumService(workspace) # Verify assert len(w) == 0 def test_cirq_service_init_without_workspace_raises_deprecation(self): # testing warning according to https://docs.python.org/3/library/warnings.html#testing-warnings import warnings with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Try to trigger a warning. AzureQuantumService( resource_id=SIMPLE_RESOURCE_ID, location=LOCATION) # Verify assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "Consider passing \"workspace\" argument explicitly" in str(w[-1].message) # Validate rising deprecation warning even if workspace is passed, but other parameters are also passed with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Try to trigger a warning. workspace = Workspace( resource_id=SIMPLE_RESOURCE_ID, location=LOCATION) AzureQuantumService( workspace=workspace, resource_id=SIMPLE_RESOURCE_ID, location=LOCATION) # Verify assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "Consider passing \"workspace\" argument explicitly" in str(w[-1].message) @pytest.mark.quantinuum @pytest.mark.ionq @pytest.mark.live_test def test_plugins_cirq_get_targets(self): workspace = self.create_workspace() service = AzureQuantumService(workspace=workspace) # pylint: disable=protected-access self.assertIn("azure-quantum-cirq", service._workspace.user_agent) targets = service.targets() target_names = [t.name for t in targets] for t in targets: self.assertIsInstance(t, Target) self.assertIn("ionq.simulator", target_names) self.assertIn("quantinuum.sim.h1-1sc", target_names) def test_plugins_estimate_cost_cirq_ionq(self): workspace = self.create_workspace() service = AzureQuantumService(workspace=workspace) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=100e3, target="ionq.simulator" ) self.assertEqual(cost.estimated_total, 0.0) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=1024, target="ionq.qpu" ) self.assertEqual(np.round(cost.estimated_total), 1.0) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=100e3, target="ionq.qpu" ) self.assertEqual(np.round(cost.estimated_total), 63.0) @pytest.mark.live_test def test_plugins_cirq_nonexistent_target(self): workspace = self.create_workspace() service = AzureQuantumService(workspace=workspace) with pytest.raises(RuntimeError): service.run( program=self._3_qubit_ghz_cirq(), repetitions=500, target="provider.doesnotexist", timeout_seconds=60 ) @pytest.mark.ionq @pytest.mark.live_test def test_plugins_ionq_cirq(self): with unittest.mock.patch.object( Job, self.mock_create_job_id_name, return_value=self.get_test_job_id(), ): workspace = self.create_workspace() service = AzureQuantumService(workspace=workspace) run_result = service.run( program=self._3_qubit_ghz_cirq(), repetitions=500, target="ionq.simulator", timeout_seconds=60 ) job = service.get_job(self.get_test_job_id()) job_result = job.results(timeout_seconds=DEFAULT_TIMEOUT_SECS).to_cirq_result() for result in [run_result, job_result]: self.assertIn("q0", result.measurements) self.assertIn("q1", result.measurements) self.assertIn("q2", result.measurements) self.assertEqual(len(result.measurements["q0"]), 500) self.assertEqual(len(result.measurements["q1"]), 500) self.assertEqual(len(result.measurements["q2"]), 500) self.assertEqual(result.measurements["q0"].sum(), result.measurements["q1"].sum()) self.assertEqual(result.measurements["q1"].sum(), result.measurements["q2"].sum()) @pytest.mark.quantinuum def test_plugins_estimate_cost_cirq_quantinuum(self): workspace = self.create_workspace() service = AzureQuantumService(workspace=workspace) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=100e3, target="quantinuum.sim.h1-1sc" ) self.assertEqual(cost.estimated_total, 0.0) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=100e3, target="quantinuum.sim.h1-1sc" ) self.assertEqual(cost.estimated_total, 0.0) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=100e3, target="quantinuum.sim.h1-1e" ) self.assertEqual(np.round(cost.estimated_total), 725.0) cost = service.estimate_cost( program=self._3_qubit_ghz_cirq(), repetitions=100e3, target="quantinuum.qpu.h1-1" ) self.assertEqual(np.round(cost.estimated_total), 725.0) @pytest.mark.quantinuum @pytest.mark.live_test def test_plugins_quantinuum_cirq(self): with unittest.mock.patch.object( Job, self.mock_create_job_id_name, return_value=self.get_test_job_id(), ): workspace = self.create_workspace() service = AzureQuantumService(workspace=workspace) program = self._3_qubit_ghz_cirq() run_result = service.run( program=program, repetitions=500, target="quantinuum.sim.h1-1e", timeout_seconds=DEFAULT_TIMEOUT_SECS ) job_no_program = service.get_job(self.get_test_job_id()) job_with_program = service.get_job( self.get_test_job_id(), program=program) # pylint: disable=protected-access target = service._target_factory.create_target( provider_id="quantinuum", name="quantinuum.sim.h1-1e") job_result1 = target._to_cirq_result( result=job_no_program.results(timeout_seconds=DEFAULT_TIMEOUT_SECS), param_resolver=ParamResolver({})) job_result2 = target._to_cirq_result( result=job_with_program.results(timeout_seconds=DEFAULT_TIMEOUT_SECS), param_resolver=ParamResolver({})) for result in [run_result, job_result1, job_result2]: self.assertIn("q0", result.measurements) self.assertIn("q1", result.measurements) self.assertIn("q2", result.measurements) self.assertEqual(len(result.measurements["q0"]), 500) self.assertEqual(len(result.measurements["q1"]), 500) self.assertEqual(len(result.measurements["q2"]), 500) self.assertAlmostEqual(result.measurements["q0"].sum(), result.measurements["q1"].sum(), delta=10) self.assertAlmostEqual(result.measurements["q1"].sum(), result.measurements["q2"].sum(), delta=10)
azure-quantum-python/azure-quantum/tests/unit/test_cirq.py/0
{ "file_path": "azure-quantum-python/azure-quantum/tests/unit/test_cirq.py", "repo_id": "azure-quantum-python", "token_count": 5015 }
355
<jupyter_start><jupyter_text>πŸ‘‹πŸŒ Hello, world: Submit a Cirq job to IonQIn this notebook, we'll review the basics of Azure Quantum by submitting a simple *job*, or quantum program, to [IonQ](https://ionq.com/). We will use [Cirq](https://quantumai.google/cirq) to express the quantum job. Submit a simple job to IonQ using Azure QuantumAzure Quantum provides several ways to express quantum programs. In this example we are using Cirq, but note that Q and Qiskit are also supported. All code in this example will be written in Python.Let's begin. When you see a code block, hover over it and click the triangle play-button to execute it. To avoid any compilation issues, this should be done in order from top to bottom. 1. Connect to the Azure Quantum workspaceTo connect to the Azure Quantum service, construct an instance of the `AzureQuantumService`. Note that it's imported from `azure.quantum.cirq`.<jupyter_code>from azure.quantum import Workspace from azure.quantum.cirq import AzureQuantumService workspace = Workspace( resource_id = "", location = "", ) service = AzureQuantumService(workspace)<jupyter_output><empty_output><jupyter_text>Let's see what providers and targets are enabled in this workspace with the following command:<jupyter_code>print("This workspace's targets:") for target in service.targets(): print("-", target.name)<jupyter_output><empty_output><jupyter_text>❕ Do you see `ionq.simulator` in your list of targets? If so, you're ready to keep going.Don't see it? You may need to add IonQ to your workspace to run this sample. Navigate to the **Providers** page in the portal and click **+Add** to add the IonQ provider. Don't worry, there's a free credits plan available. IonQ: The quantum providerAzure Quantum partners with third-party companies to deliver solutions to quantum jobs. These company offerings are called *providers*. Each provider can offer multiple *targets* with different capabilities. See the table below for IonQ's targets.| Target name | Target ID | Number of qubits | Description || --- | --- | --- | --- || Quantum simulator | `ionq.simulator` | 29 qubits | IonQ's cloud-based idealized simulator. Free of cost. || Aria 1 | `ionq.qpu.aria-1` | 23 qubits | IonQ's Aria 1 trapped-ion quantum computer. This is real quantum hardware, not a simulation. || Quantum computer | `ionq.qpu` | 11 qubits | IonQ's trapped-ion quantum computer. This is real quantum hardware, not a simulation. |For this example, we will use `ionq.simulator`. To learn more about IonQ's targets, check out our [documentation](https://learn.microsoft.com/azure/quantum/provider-ionq). 2. Build the quantum programLet's create a simple Cirq circuit to run.<jupyter_code>import cirq q0 = cirq.LineQubit(0) circuit = cirq.Circuit( cirq.H(q0), # Apply an H-gate to q0 cirq.measure(q0) # Measure q0 ) circuit<jupyter_output><empty_output><jupyter_text>The circuit you built is a simple quantum random bit generator. With IonQ's idealized simulator, we will be able to calculate the probability of measuring a `1` or `0`. 3. Submit the quantum program to IonQ<jupyter_code># Using the IonQ simulator target, call "run" to submit the job. We'll # use 100 repetitions (simulated runs). job = service.targets("ionq.simulator").submit(circuit, name="hello world-cirq-ionq", repetitions=100) # Print the job ID. print("Job id:", job.job_id())<jupyter_output><empty_output><jupyter_text>The job ID can be used to retrieve the results later using the [get_job method](https://learn.microsoft.com/python/azure-quantum/azure.quantum.workspace?azure-quantum-workspace-get-job) or by viewing it under the **Job management** section of the portal. 4. Obtain the job resultsLet's await the job execution by calling `job.results()`. This may take a minute or so ⏳. Your job is being packaged and sent to IonQ, where it will wait its turn to be run.<jupyter_code># Await job results. print("Awaiting job results...") result = job.results() # To view the probabilities computed for each Qubit state, you can print the result. print("Job finished. State probabilities:") print(result)<jupyter_output><empty_output><jupyter_text>You can also view a histogram of the results which computes hypothetical states based on the result's computed probabilities. Try running the next code cell multiple times to see the value change in accordance with the probabilities that the simulation computed.<jupyter_code>from cirq.vis import plot_state_histogram # Convert the result to a cirq result by "measuring" the returned # qubits a number of times equal to the specified number of repetitions. measurement = result.to_cirq_result() # We can now use Cirq to plot the results of the "measurement." res = plot_state_histogram(measurement)<jupyter_output><empty_output><jupyter_text>**See the histogram above? Congratulations, you've submitted a job with Azure Quantum! πŸ‘** 5. Estimate costsTo estimate the costs of running this program on a simulator or hardware, you can use the `service.estimate_cost` method.<jupyter_code>cost = service.estimate_cost(circuit, repetitions=100, target="ionq.qpu") print(f"Estimated cost: {cost.estimated_total} {cost.currency_code}")<jupyter_output><empty_output>
azure-quantum-python/samples/hello-world/HW-ionq-cirq.ipynb/0
{ "file_path": "azure-quantum-python/samples/hello-world/HW-ionq-cirq.ipynb", "repo_id": "azure-quantum-python", "token_count": 1528 }
356
<jupyter_start><jupyter_text>Getting Started with Azure Quantum Resource Estimation using QiskitπŸ‘‹ Welcome to the Azure Quantum Resource Estimator. In this notebook we willguide you how to estimate and analyze the physical resource estimates of aquantum program targeted for execution based on the architecture design of afault-tolerant quantum computer. As a running example we are using a multiplier. Implementing the algorithm As a first step, we will create a sample application which will be used throughout this Resource Estimation notebook. To start, we'll import some Python packages from `azure.quantum` and `qiskit`.<jupyter_code># These are the Python imports that we use in this Qiskit-based example from azure.quantum.qiskit import AzureQuantumProvider from qiskit import QuantumCircuit, transpile from qiskit.circuit.library import RGQFTMultiplier<jupyter_output><empty_output><jupyter_text>We are creating a quantum circuit for a multiplier based on the construction presented in [arXiv:1411.5949](https://arxiv.org/abs/1411.5949) which uses the Quantum Fourier Transform to implement arithmetic. You can adjust the size of the multiplier by changing the `bitwidth` variable. The circuit generation is wrapped in a function that can be called with the bitwidth of the multiplier. The circuit will have two input registers with that bitwidth, and one output register with the size of twice the bitwidth. The function will also print some logical resource counts for the multiplier extracted directly from the quantum circuit.<jupyter_code>def create_algorithm(bitwidth, backend): print(f"[INFO] Create a QFT-based multiplier with bitwidth {bitwidth}") # Print a warning for large bitwidths that will require some time to generate and # transpile the circuit. if bitwidth > 18: print(f"[WARN] It will take more than one minute generate a quantum circuit with a bitwidth larger than 18") circ = RGQFTMultiplier(num_state_qubits=bitwidth, num_result_qubits=2 * bitwidth) # One could further reduce the resource estimates by increasing the optimization_level, # however, this will also increase the runtime to construct the algorithm. Note, that # it does not affect the runtime for resource estimation. print(f"[INFO] Decompose circuit into intrinsic quantum operations") # retrieve basis gates from backend basis_gates = backend.configuration().basis_gates circ = transpile(circ, basis_gates=basis_gates, optimization_level=0) # print some statistics print(f"[INFO] qubit count: {circ.num_qubits}") print("[INFO] gate counts") for gate, count in circ.count_ops().items(): print(f"[INFO] - {gate}: {count}") return circ<jupyter_output><empty_output><jupyter_text>Estimating the algorithmLet's connect to the Azure Quantum workspace and create a backend instance forthe Azure Quantum Resource Estimator. The backend acts as a target for ourquantum computing jobs. Examples for other backends include QPUs to executequantum programs on today's quantum computers, or simulators to simulate thefunctional behavior of a quantum program. You can find examples for suchbackends in other notebooks in the _Sample Gallery_.<jupyter_code>from azure.quantum import Workspace from azure.quantum.qiskit import AzureQuantumProvider workspace = Workspace( resource_id = "", location = "", ) provider = AzureQuantumProvider(workspace) backend = provider.get_backend('microsoft.estimator')<jupyter_output><empty_output><jupyter_text>Next we will create an instance of our algorithm using the `create_algorithm` function. You can adjust the size of the multiplier by changing the `bitwidth` variable.<jupyter_code>bitwidth = 4 circ = create_algorithm(bitwidth, backend)<jupyter_output><empty_output><jupyter_text>Let's now estimate the physical resources for this circuit using the default assumptions. We can submit the circuit to the Resource Estimation backend using its `run` method.<jupyter_code>job = backend.run(circ) result = job.result()<jupyter_output><empty_output><jupyter_text>The simplest way to inspect the results of the job is to output them to the notebook. This will output a table with the overall physical resource counts. You can further inspect more details about the resource estimates by collapsing various groups which have more information. For example, if you collapse the *Logical qubit parameters* group, you can see that the quantum error correction (QEC) code distance is 15. In the last group you can see the physical qubit properties that were assumed for this estimation. For example, we see that the time to perform a single-qubit measurement and a single-qubit gate are assumed to be 100 ns and 50 ns, respectively.<jupyter_code>result<jupyter_output><empty_output><jupyter_text>The distribution of physical qubits used for the execution of the algorithm instructions and the supporting T factories can provide us valuable information to guide us in applying space and time optimizations. We can visualize this distribution to better understand the estimated space requirements for our algorithm.<jupyter_code>result.diagram.space<jupyter_output><empty_output><jupyter_text>We can also visualize the time required to execute the algorithm as it relates to each T factory invocation runtime and the number of T factory invocations. >> *You cannot visualize the time and space diagrams in the same cell.*><jupyter_code>result.diagram.time<jupyter_output><empty_output><jupyter_text>If you prefer a more compact version of the table, in which the descriptions areprovided by means of tooltips, you can write:<jupyter_code>result.summary<jupyter_output><empty_output><jupyter_text>We can also programmatically access all the values that can be passed to the job execution and see which default values were assumed:<jupyter_code>result.data()["jobParams"]<jupyter_output><empty_output><jupyter_text>We see that there are three input parameters that can be customized: `qubitParams`, `qecScheme`, and `errorBudget`. Qubit parametersThe first parameter `qubitParams` is used to specify qubit parameters. Whenmodeling the physical qubit abstractions, we distinguish between two differentphysical instruction sets that are used to operate the qubits. The physicalinstruction set can be either *gate-based* or *Majorana*. A gate-basedinstruction set provides single-qubit measurement, single-qubit gates (incl. T gates), and two-qubit gates. A Majorana instruction set provides a physical T gate, single-qubit measurement and two-qubit joint measurement operations.Qubit parameters can be completely customized. Before we show this, we show hotto choose from six pre-defined qubit parameters, four of which have gate-basedinstruction sets and two with a Majorana instruction set. An overview of allpre-defined qubit parameters is provided by the following table:| Pre-defined qubit parameters | Instruction set | References ||------------------------------|-----------------|------------------------------------------------------------------------------------------------------------|| `"qubit_gate_ns_e3"` | gate-based | [arXiv:2003.00024](https://arxiv.org/abs/2003.00024), [arXiv:2111.11937](https://arxiv.org/abs/2111.11937) || `"qubit_gate_ns_e4"` | gate-based | [arXiv:2003.00024](https://arxiv.org/abs/2003.00024), [arXiv:2111.11937](https://arxiv.org/abs/2111.11937) || `"qubit_gate_us_e3"` | gate-based | [arXiv:1701.04195](https://arxiv.org/abs/1701.04195) || `"qubit_gate_us_e4"` | gate-based | [arXiv:1701.04195](https://arxiv.org/abs/1701.04195) || `"qubit_maj_ns_e4"` | Majorana | [arXiv:1610.05289](https://arxiv.org/abs/1610.05289) || `"qubit_maj_ns_e6"` | Majorana | [arXiv:1610.05289](https://arxiv.org/abs/1610.05289) |Pre-defined qubit parameters can be selected by specifying the `name` field inthe `qubitParams`. If no value is provided, `"qubit_gate_ns_e3"` is chosen asthe default qubit parameters.Let's re-run resource estimation for our running example on the Majorana-basedqubit parameters `"qubit_maj_ns_e6"`.<jupyter_code>job = backend.run(circ, qubitParams={ "name": "qubit_maj_ns_e6" }) result = job.result() result<jupyter_output><empty_output><jupyter_text>Let's inspect the physical counts programmatically. For example, we can show all physical resource estimates and their breakdown using the `physicalCounts` field in the result data. This will show the logical qubit error and logical T-state error rates required to match the error budget. By default runtimes are shown in nanoseconds.<jupyter_code>result.data()["physicalCounts"]<jupyter_output><empty_output><jupyter_text>We can also explore details about the T factory that was created to execute this algorithm.<jupyter_code>result.data()["tfactory"]<jupyter_output><empty_output><jupyter_text>Next, we are using this data to produce some explanations of how the T factories produce the required T states.<jupyter_code>data = result.data() tfactory = data["tfactory"] breakdown = data["physicalCounts"]["breakdown"] producedTstates = breakdown["numTfactories"] * breakdown["numTfactoryRuns"] * tfactory["numTstates"] print(f"""A single T factory produces {tfactory["logicalErrorRate"]:.2e} T states with an error rate of (required T state error rate is {breakdown["requiredLogicalTstateErrorRate"]:.2e}).""") print(f"""{breakdown["numTfactories"]} copie(s) of a T factory are executed {breakdown["numTfactoryRuns"]} time(s) to produce {producedTstates} T states ({breakdown["numTstates"]} are required by the algorithm).""") print(f"""A single T factory is composed of {tfactory["numRounds"]} rounds of distillation:""") for round in range(tfactory["numRounds"]): print(f"""- {tfactory["numUnitsPerRound"][round]} {tfactory["unitNamePerRound"][round]} unit(s)""")<jupyter_output><empty_output><jupyter_text>Custom qubit parameters must completely specify all required parameters. These are the values that areconsidered when the `instructionSet` is `"GateBased"`.| Field (*required) | Description ||---------------------------------|----------------------------------------------------------------------|| `name` | Some descriptive name for the parameters || `oneQubitMeasurementTime`* | Operation time for single-qubit measurement ($t_{\rm meas}$) in ns || `oneQubitGateTime`* | Operation time for single-qubit Clifford gate ($t_{\rm gate}$) in ns || `twoQubitGateTime` | Operation time for two-qubit Clifford gate in ns || `tGateTime` | Operation time for single-qubit non-Clifford gate in ns || `oneQubitMeasurementErrorRate`* | Error rate for single-qubit measurement || `oneQubitGateErrorRate`* | Error rate for single-qubit Clifford gate ($p$) || `twoQubitGateErrorRate` | Error rate for two-qubit Clifford gate || `tGateErrorRate` | Error rate to prepare single-qubit non-Clifford state ($p_T$) |The values for `twoQubitGateTime` and `tGateTime` default to `oneQubitGateTime`when not specified; the values for `twoQubitGateErrorRate` and `tGateErrorRate`default to `oneQubitGateErrorRate` when not specified.A minimum template for qubit parameters based on a gate-based instruction setwith all required values is:```json{ "qubitParams": { "instructionSet": "GateBased", "oneQubitMeasurementTime": , "oneQubitGateTime": , "oneQubitMeasurementErrorRate": , "oneQubitGateErrorRate": }}```For time units, you need to specify time strings which are double-precisionfloating point numbers followed by a space and a unit prefix which is `ns`, `Β΅s`(alternatively `us`), `ms`, or `s`.These are the values that are considered when the `instructionSet` is`"Majorana"`.| Field (*required) | Description ||-------------------------------------|---------------------------------------------------------------------|| `name` | Some descriptive name for the parameters || `oneQubitMeasurementTime`* | Operation time for single-qubit measurement ($t_{\rm meas}$) in ns || `twoQubitJointMeasurementTime` | Operation time for two-qubit joint measurement in ns || `tGateTime` | Operation time for single-qubit non-Clifford gate in ns || `oneQubitMeasurementErrorRate`* | Error rate for single-qubit measurement || `twoQubitJointMeasurementErrorRate` | Error rate for two-qubit joint measurement || `tGateErrorRate`* | Error rate to prepare single-qubit non-Clifford state ($p_T$) |The values for `twoQubitJointMeasurementTime` and `tGateTime` default to`oneQubitGateTime` when not specified; the value for`twoQubitJointMeasurementErrorRate` defaults to `oneQubitMeasurementErrorRate`when not specified.A minimum template for qubit parameters based on a Majorana instruction set withall required values is:```json{ "qubitParams": { "instructionSet": "Majorana", "oneQubitMeasurementTime": , "oneQubitMeasurementErrorRate": , "tGateErrorRate": }}``` QEC schemes To execute practical-scale quantum applications, we require operations with verylow error rates. These error rate targets are typically beyond the capabilitiesof raw physical qubits. To overcome this limitation, quantum error correction(QEC) and fault-tolerant computation are two crucial techniques that form thebuilding blocks of large-scale quantum computers. First, QEC allows us tocompose multiple error-prone physical qubits and build a more reliable logicalqubit that preserves quantum information better than the underlying physicalqubits. Several QEC schemes have been developed since the last three decades,including popular schemes such as the Shor-code, surface code, color codes andothers, and recently the [Hastings-Haah code](https://arxiv.org/abs/2107.02194).These schemes vary based on the number of physical qubits they require, theconnectivity among qubits and other factors. By using QEC techniques, we canachieve a fault-tolerant quantum computation, enabling reliable storing andprocessing of quantum information in the presence of noise. To store informationreliably, we require that the QEC scheme is able to suppress errors when thephysical qubits meet a certain threshold error rate. To process information, werequire fault-tolerant operations that allow applications to perform generalpurpose quantum computations efficiently and limit the spread of errors thatoccur while computing with logical qubits. Schemes for fault-tolerant operationsinclude techniques such as lattice surgery and transversal operations. Together,QEC and fault-tolerance techniques bridges the accuracy gap between quantumhardware and algorithms.The error correction code distance (or just code distance in short) is aparameter that controls the number of errors that can be corrected, and thus theerror rate of the logical qubits and the number of physical qubits required toencode them. The higher the code distance, the better the accuracy, but alsothe higher the amount of physical qubits. The goal is to find the minimum codedistance that can achieve the required error rate set for a particularapplication. We will explain later in this notebook how a global error budgetis provided as input and how it is distributed throughout the estimation,including the logical error rate of logical qubits.We follow the standard way of modeling logical error rates using an exponentialmodel parameterized by the code distance $d$, physical error rate $p$, QECthreshold $p^*$. The physical error rate $p$ is extracted from the qubitparameters above as the worst-case error rate any physical Clifford operation inthe device. In particular, we set $p = {}$ `max(oneQubitMeasurementErrorRate,oneQubitGateErrorRate, twoQubitGateErrorRate)` for qubit parameters with agate-based instruction set, and $p = {}$ `max(oneQubitMeasurementErrorRate,twoQubitJointMeasurementErrorRate)` for qubit parameters with a Majoranainstruction set. QEC schemes typically have a error rate threshold $p^*$ belowwhich error correction suppresses errors.Our current implementation uses the formula$$P = a\left(\frac{p}{p^*}\right)^{\frac{d+1}{2}}$$as the generic model. The exact parameters for each pre-defined QEC scheme(including a crossing pre-factor $a$ which can be extracted numerically forsimulations) are listed below.In Azure Quantum Resource Estimation we can abstract the quantum errorcorrection scheme based on the above formula by providing values for thecrossing pre-factor $a$ and the error correction threshold $p^*$. Further, oneneeds to specify the logical cycle time, i.e., the time to execute a singlelogical operation, which depends on the code distance and the physicaloperation time assumptions of the underlying physical qubits. Finally, a secondformula computes the number of physical qubits required to encode one logicalqubit based on the code distance.As with the physical qubit parameters, one can choose from several pre-definedQEC schemes, can extend pre-defined ones, and can provide custom schemes byproviding all parameters. Note that QEC schemes are tightly connected to thephysical instruction set of the physical qubit parameters, and therefore aredefined specifically for one of the two instruction sets.We provide three pre-defined QEC schemes, two `"surface_code"` protocols forgate-based and Majorana physical instruction sets, and the `"floquet_code"`protocol that is so far only implemented for a Majorana physical instruction setin the resource estimator.| QEC scheme | Instruction set | References ||----------------|-----------------|------------------------------------------------------------------------------------------------------------|| `surface_code` | gate-based | [arXiv:1208.0928](https://arxiv.org/abs/1208.0928), [arXiv:1009.3686](https://arxiv.org/abs/1009.3686) || `surface_code` | Majorana | [arXiv:1909.03002](https://arxiv.org/abs/1909.03002), [arXiv:2007.00307](https://arxiv.org/abs/2007.00307) || `floquet_code` | Majorana | [arXiv:2202.11829](https://arxiv.org/abs/2202.11829) |In case of `"surface_code"` the corresponding scheme is selected based on thequbit type of the physical qubit parameters. The gate-based surface code isbased on [[arXiv:1208.0928](https://arxiv.org/abs/1208.0928)] and[[arXiv:1009.3686](https://arxiv.org/abs/1009.3686)]. The surface code forMajorana qubits is based on[[arXiv:1909.03002](https://arxiv.org/abs/1909.03002)] and[[arXiv:2007.00307](https://arxiv.org/abs/2007.00307)] (replacing 8 steps tomeasure a single stabilizer in the former reference by 20 steps to measure allstabilizers). The floquet code, which can only be selected for Majorana qubits,is based on [[arXiv:2202.11829](https://arxiv.org/abs/2202.11829)].Pre-defined qubit parameters can be selected by specifying the `name` field inthe `qecScheme` parameter. If no value is provided, `"surface_code"` is used asdefault value.Let's re-run resource estimation for our running example on the Majorana-basedqubit parameters with a Floquet code.<jupyter_code>job = backend.run(circ, qubitParams={ "name": "qubit_maj_ns_e6" }, qecScheme={ "name": "floquet_code" }) result_maj_floquet = job.result() result_maj_floquet<jupyter_output><empty_output><jupyter_text>To specify a QEC scheme the user has to specify 2 values, the`errorCorrectionThreshold` and the `crossingPrefactor`, as well as 2 formulasfor the `logicalCycleTime`, and the `physicalQubitsPerLogicalQubit`. A templatefor QEC schemes is as follows:```json{ "qecScheme": { "crossingPrefactor": , "errorCorrectionThreshold": , "logicalCycleTime": , "physicalQubitsPerLogicalQubit": }}```Inside the formulas, the user can make use of the following variables* `oneQubitGateTime`* `twoQubitGateTime`* `oneQubitMeasurementTime`* `twoQubitJointMeasurementTime`whose value is taken from the corresponding field from the physical qubitparameters (note that some variables are not available based on the qubitparameters' instruction set), as well as the variable* `codeDistance`for the code distance computed for the logical qubit, based on the physicalqubit properties, the error correction threshold, and the crossing prefactor.The time variables and `codeDistance` can be used to describe the`logicalCycleTime` formula. For the formula `physicalQubitsPerLogicalQubit`only the `codeDistance` can be used. Error budgetThe third parameter `errorBudget` models the total error budget $\epsilon$. Itsets the overall allowed error for the algorithm, i.e., the number of times itis allowed to fail. Its value must be between 0 and 1 and the default value is0.001, which corresponds to 0.1%, and means that the algorithm is allowed tofail once in 1000 executions. This parameter is highly application specific.For example, if one is running Shor's algorithm for factoring integers, a largevalue for the error budget may be tolerated as one can check that the output areindeed the prime factors of the input. On the other hand, a much smaller errorbudget may be needed for an algorithm solving a problem with a solution whichcannot be efficiently verified. This budget$$ \epsilon = \epsilon_{\log} + \epsilon_{\rm dis} + \epsilon_{\rm syn}$$is uniformly distributed and applies to errors $\epsilon_{\log}$ to implementlogical qubits, an error budget $\epsilon_{\rm dis}$ to produce T states throughdistillation, and an error budget $\epsilon_{\rm syn}$ to synthesize rotationgates with arbitrary angles. Note that for distillation and rotation synthesis,the respective error budgets $\epsilon_{\rm dis}$ and $\epsilon_{\rm syn}$ areuniformly distributed among all required T states and all required rotationgates, respectively. If there are no rotation gates in the input algorithm, theerror budget is uniformly distributed to logical errors and T state errors.Next, we re-run the last experiment with a an error budget of 10%.<jupyter_code>job = backend.run(circ, qubitParams={ "name": "qubit_maj_ns_e6" }, qecScheme={ "name": "floquet_code" }, errorBudget=0.1) result_maj_floquet_e1 = job.result() result_maj_floquet_e1<jupyter_output><empty_output>
azure-quantum-python/samples/resource-estimator/estimation-qiskit.ipynb/0
{ "file_path": "azure-quantum-python/samples/resource-estimator/estimation-qiskit.ipynb", "repo_id": "azure-quantum-python", "token_count": 7242 }
357
{ "name": "quantum-visualization-js", "version": "1.0.0", "description": "", "license": "MIT", "author": "", "main": "dist/index.js", "module": "dist/index.js", "files": [ "dist" ], "scripts": { "build": "webpack --mode development", "build:prod": "webpack --mode production", "sortpackagejson": "sort-package-json" }, "dependencies": { "@fluentui/react": "^8.110.8", "quantum-visualization": "^1.0.0", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@babel/preset-env": "^7.22.7", "@babel/preset-react": "^7.22.5", "babel-loader": "^9.1.2", "clean-webpack-plugin": "^4.0.0", "path": "^0.12.7", "sort-package-json": "^2.5.1", "ts-loader": "^9.4.3", "webpack": "^5.76.2", "webpack-cli": "^5.1.4" } }
azure-quantum-python/visualization/js-lib/package.json/0
{ "file_path": "azure-quantum-python/visualization/js-lib/package.json", "repo_id": "azure-quantum-python", "token_count": 405 }
358
/*------------------------------------ Copyright (c) Microsoft Corporation. Licensed under the MIT License. All rights reserved. ------------------------------------ */ import React from "react"; import { IColumn, IGroup, ThemeProvider } from "@fluentui/react"; import { JobResults } from "../../models/JobResults"; import DonutChart from "../d3-visualization-components/DonutChart"; import { GetColumns } from "../table/Column"; import { IItem, IState, TableComponent } from "../table/Table"; import "./Diagram.css"; export interface SpaceDiagramProps { data: string; } function SpaceDiagram({ data }: SpaceDiagramProps) { // Parse job results data. const jobResults = JSON.parse(data) as JobResults; /*------------------------------ Configure canvas sizing ------------------------------ */ const diagramRef = React.useRef<any>(); const [width, setWidth] = React.useState(0); const [height, setHeight] = React.useState(0); const [innerRadius, setInnerRadius] = React.useState(0); const [outerRadius, setOuterRadius] = React.useState(0); const handleWidth = () => { const width = diagramRef?.current?.offsetWidth; if (width) { setWidth(width); if (height) { const outerRadius = 0.3 * Math.min(height * 0.7, width); const innerRadius = 0.75 * outerRadius; setOuterRadius(outerRadius); setInnerRadius(innerRadius); } } }; const handleSize = () => { handleWidth(); const height = diagramRef?.current?.offsetHeight; if (height) { setHeight(height); } }; React.useLayoutEffect(() => { handleSize(); window.addEventListener("resize", handleWidth); }, [diagramRef.current]); /*------------------------------ Define and parse table and chart data ------------------------------ */ const physicalQubitsAlgorithm = jobResults.physicalCounts.breakdown.physicalQubitsForAlgorithm; const physicalQubitsTFactory = jobResults.physicalCounts.breakdown.physicalQubitsForTfactories; const numTFactories = jobResults.physicalCounts.breakdown.numTfactories; const numQubitsPerTFactory = Math.round( physicalQubitsTFactory / numTFactories, ); const chartData = [ { title: "Physical", value: physicalQubitsAlgorithm, legendTitle: "Algorithm qubits", }, { title: "Physical", value: physicalQubitsTFactory, legendTitle: "T factory qubits", }, ]; const numTFactoryQubitsString = "Physical qubits per single T factory (" + numQubitsPerTFactory.toLocaleString() + ") * T factory copies (" + numTFactories.toLocaleString() + ") = " + physicalQubitsTFactory.toLocaleString() + " Total physical qubits required for all T factories."; const tableItems: IItem[] = [ { name: "Total physical qubits", value: jobResults.physicalCounts.physicalQubits.toLocaleString(), description: "Total physical qubits required for algorithm and T factories.", }, { name: "Physical T factory qubits", value: physicalQubitsTFactory.toLocaleString(), description: "Total number of physical qubits required for the T factories.", }, { name: "T factory copies", value: numTFactories.toLocaleString(), description: "Number of T factories executed in parallel capable of producing the demanded T states during the algorithm's runtime.", }, { name: "Physical qubits per T factory", value: numQubitsPerTFactory.toLocaleString(), description: numTFactoryQubitsString, }, { name: "Physical algorithmic qubits", value: physicalQubitsAlgorithm.toLocaleString(), description: "Number of logical qubits for the algorithm after layout.", }, { name: "Logical algorithmic qubits", value: jobResults.physicalCounts.breakdown.algorithmicLogicalQubits.toLocaleString(), description: "Number of logical qubits for the algorithm after layout.", }, { name: "Physical qubits", value: jobResults.logicalQubit.physicalQubits.toLocaleString(), description: "Number of physical qubits per logical qubit.", }, ]; const tableGroups: IGroup[] = [ { key: "1", name: "Physical resource estimates", startIndex: 0, count: 1, }, { key: "2", name: "T factory parameters", startIndex: 1, count: 1, }, { key: "3", name: "Resource estimation breakdown", startIndex: 2, count: 4, }, { key: "4", name: "Logical qubit parameters", startIndex: 6, count: 1, }, ]; /*------------------------------ Create table ------------------------------ */ const tableProps: IState = { items: tableItems, groups: tableGroups, showItemIndexInView: false, isCompactMode: false, }; const columns: IColumn[] = GetColumns(); const Table = () => ( <ThemeProvider> <TableComponent state={tableProps} columns={columns} /> </ThemeProvider> ); return ( <div className="grid-container"> <div className="diagram" ref={diagramRef}> <DonutChart data={chartData} width={width} height={height} innerRadius={innerRadius} outerRadius={outerRadius} /> </div> <div className="table"> <Table /> </div> </div> ); } export default SpaceDiagram;
azure-quantum-python/visualization/react-lib/src/components/resource-estimator/SpaceDiagram.tsx/0
{ "file_path": "azure-quantum-python/visualization/react-lib/src/components/resource-estimator/SpaceDiagram.tsx", "repo_id": "azure-quantum-python", "token_count": 2022 }
359
bistr ===== .. testsetup:: * from bistring import bistr, Alignment .. autoclass:: bistring.bistr
bistring/docs/Python/bistr.rst/0
{ "file_path": "bistring/docs/Python/bistr.rst", "repo_id": "bistring", "token_count": 43 }
360
/*! * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ import Alignment, { Bounds } from "./alignment"; import BiStringBuilder from "./builder"; import heuristicInfer from "./infer"; import { Replacer, normalizeReplacer, cloneRegExp } from "./regex"; import * as unicode from "./unicode"; export type AnyString = string | BiString; /** * A bidirectionally transformed string. */ export default class BiString implements Iterable<String> { /** The original string, before any modifications. */ readonly original: string; /** The current value of the string, after all modifications. */ readonly modified: string; /** The sequence alignment between `original` and `modified`. */ readonly alignment: Alignment; /** The length of the modified string. */ readonly length: number; /** Indexes the code units of the modified string. */ readonly [i: number]: string; /** * A BiString can be constructed from only a single string, which will give it identical original and modified * strings and an identity alignment: * * .. code-block:: ts * * new BiString("test"); * * You can also explicitly specify both the original and modified strings. The inferred alignment will be as course * as possible: * * .. code-block:: ts * * new BiString("TEST", "test"); * * Finally, you can specify the alignment explicitly, if you know it: * * .. code-block:: ts * * new BiString("TEST", "test", Alignment.identity(4)); * * @param original * The original string, before any modifications. * @param modified * The modified string, after any modifications. * @param alignment * The alignment between the original and modified strings. */ constructor(original: string, modified?: string, alignment?: Alignment) { if (typeof(original) !== "string") { throw new TypeError("original was not a string"); } this.original = original; if (modified === undefined) { modified = original; if (alignment === undefined) { alignment = Alignment.identity(original.length); } } else if (typeof(modified) === "string") { if (alignment === undefined) { alignment = new Alignment([[0, 0], [original.length, modified.length]]); } } else { throw new TypeError("modified was not a string"); } this.modified = modified; if (!(alignment instanceof Alignment)) { throw new TypeError("alignment was not an Alignment"); } const [ostart, oend] = alignment.originalBounds(); if (ostart !== 0 || oend !== original.length) { throw new RangeError("Alignment incompatible with original string"); } const [mstart, mend] = alignment.modifiedBounds(); if (mstart !== 0 || mend !== modified.length) { throw new RangeError("Alignment incompatible with modified string"); } this.alignment = alignment; this.length = this.modified.length; for (let i = 0; i < this.length; ++i) { // @ts-ignore: https://github.com/microsoft/TypeScript/issues/6781 this[i] = this.modified[i]; } Object.freeze(this); } /** * Create a `BiString` from a string-like object. * * @param str * Either a `string` or a `BiString`. * @returns * The input coerced to a `BiString`. */ static from(str: AnyString): BiString { if (str instanceof BiString) { return str; } else { return new BiString(str); } } /** * Create a `BiString`, automatically inferring an alignment between the `original` and `modified` strings. * * @param original * The original string. * @param modified * The modified string. */ static infer(original: string, modified: string): BiString { return heuristicInfer(original, modified); } /** * Iterates over the code points in the modified string. */ [Symbol.iterator](): IterableIterator<string> { return this.modified[Symbol.iterator](); } /** * Like :js:meth:`String.prototype.charAt`, returns a code unit as a string from the modified string. */ charAt(pos: number): string { return this.modified.charAt(pos); } /** * Like :js:meth:`String.prototype.charCodeAt`, returns a code unit as a number from the modified string. */ charCodeAt(pos: number): number { return this.modified.charCodeAt(pos); } /** * Like :js:meth:`String.prototype.codePointAt`, returns a code point from the modified string. */ codePointAt(pos: number): number | undefined { return this.modified.codePointAt(pos); } /** * Extract a substring of this BiString, with similar semantics to :js:meth:`String.prototype.substring`. */ substring(start: number, end?: number): BiString { if (end === undefined) { end = this.length; } if (start > end) { [start, end] = [end, start]; } start = Math.max(0, Math.min(start, this.length)); end = Math.max(0, Math.min(end, this.length)); return this.slice(start, end); } /** * Extract a slice of this BiString, with similar semantics to :js:meth:`String.prototype.slice`. */ slice(start: number, end?: number): BiString { if (end === undefined) { end = this.length; } if (start < 0) { start += this.length; } if (end < 0) { end += this.length; } if (end < start) { end = start; } start = Math.max(0, Math.min(start, this.length)); end = Math.max(0, Math.min(end, this.length)); const alignment = this.alignment.sliceByModified(start, end); const modified = this.modified.slice(...alignment.modifiedBounds()); const original = this.original.slice(...alignment.originalBounds()); const [o0, m0] = alignment.values[0]; return new BiString(original, modified, alignment.shift(-o0, -m0)); } /** * Concatenate this string together with one or more others. The additional strings can be either BiStrings or * normal strings. */ concat(...others: AnyString[]): BiString { let original = this.original; let modified = this.modified; let alignment = this.alignment; for (const other of others) { const biother = BiString.from(other); alignment = alignment.concat(biother.alignment.shift(original.length, modified.length)); original += biother.original; modified += biother.modified; } return new BiString(original, modified, alignment); } /** * @returns * The inverse of this string, swapping the original and modified strings. */ inverse(): BiString { return new BiString(this.modified, this.original, this.alignment.inverse()); } /** * @returns * Whether this BiString is equal to another. */ equals(other: BiString): boolean { return this.original === other.original && this.modified === other.modified && this.alignment.equals(other.alignment); } /** * Like :js:meth:`String.prototype.indexOf`, finds the first occurrence of a substring. */ indexOf(searchValue: string, fromIndex?: number): number { return this.modified.indexOf(searchValue, fromIndex); } /** * Like :js:meth:`String.prototype.lastIndexOf`, finds the last occurrence of a substring. */ lastIndexOf(searchValue: string, fromIndex?: number): number { return this.modified.lastIndexOf(searchValue, fromIndex); } /** * Like :js:meth:`indexOf`, but returns both the start and end positions for convenience. */ boundsOf(searchValue: string, fromIndex?: number): Bounds { let start = this.indexOf(searchValue, fromIndex); if (start === -1) { return [-1, -1]; } else { return [start, start + searchValue.length]; } } /** * Like :js:meth:`lastIndexOf`, but returns both the start and end positions for convenience. */ lastBoundsOf(searchValue: string, fromIndex?: number): Bounds { let start = this.lastIndexOf(searchValue, fromIndex); if (start === -1) { return [-1, -1]; } else { return [start, start + searchValue.length]; } } /** * Like :js:meth:`String.prototype.search`, finds the position of the first match of a regular expression. */ search(regexp: RegExp): number { return this.modified.search(regexp); } /** * Like :js:meth:`search`, but returns both the start and end positions for convenience. */ searchBounds(regexp: RegExp): Bounds { const match = regexp.exec(this.modified); if (match === null) { return [-1, -1]; } else { return [match.index, match.index + match[0].length]; } } /** * Like :js:meth:`String.prototype.match`, returns the result of a regular expression match. */ match(regexp: RegExp): RegExpMatchArray | null { return this.modified.match(regexp); } /** * Like :js:meth:`String.prototype.matchAll`, returns an iterator over all regular expression matches. */ matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray> { return this.modified.matchAll(regexp); } private _replaceString(pattern: string, replacement: string | Replacer): BiString { const replacer = normalizeReplacer(replacement); const builder = new BiStringBuilder(this); while (!builder.isComplete) { const next = this.indexOf(pattern, builder.position); if (next < 0) { break; } builder.skip(next - builder.position); const match = [this.modified.slice(next, next + pattern.length)] as RegExpMatchArray; match.index = next; match.input = this.modified; builder.replace(pattern.length, replacer(match)); } builder.skipRest(); return builder.build(); } private _replaceRegExp(pattern: RegExp, replacement: string | Replacer): BiString { const builder = new BiStringBuilder(this); builder.replaceAll(pattern, replacement); return builder.build(); } /** * Like :js:meth:`String.prototype.replace`, returns a new string with regex or fixed-string matches replaced. */ replace(pattern: string | RegExp, replacement: string | Replacer): BiString { if (typeof(pattern) === "string") { return this._replaceString(pattern, replacement); } else { return this._replaceRegExp(pattern, replacement); } } /** * Like :js:meth:`String.prototype.trim`, returns a new string with leading and trailing whitespace removed. */ trim(): BiString { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); } /** * Like :js:meth:`String.prototype.trim`, returns a new string with leading whitespace removed. */ trimStart(): BiString { return this.replace(/^[\s\uFEFF\xA0]+/, ""); } /** * Like :js:meth:`String.prototype.trim`, returns a new string with trailing whitespace removed. */ trimEnd(): BiString { return this.replace(/[\s\uFEFF\xA0]+$/, ""); } /** * Like :js:meth:`String.prototype.padStart`, pads a string at the beginning to a target length. */ padStart(targetLength: number, padString: string = " "): BiString { const padLength = targetLength - this.length; if (padLength <= 0) { return this; } if (padString.length < padLength) { padString += padString.repeat(targetLength / padString.length); } padString = padString.slice(0, padLength); return new BiString("", padString).concat(this); } /** * Like :js:meth:`String.prototype.padEnd`, pads a string at the end to a target length. */ padEnd(targetLength: number, padString: string = " "): BiString { const padLength = targetLength - this.length; if (padLength <= 0) { return this; } if (padString.length < padLength) { padString += padString.repeat(targetLength / padString.length); } padString = padString.slice(0, padLength); return this.concat(new BiString("", padString)); } /** * Like :js:meth:`String.prototype.startsWith`, returns whether this string starts with the given prefix. */ startsWith(searchString: string, position?: number): boolean { return this.modified.startsWith(searchString, position); } /** * Like :js:meth:`String.prototype.endsWith`, returns whether this string ends with the given prefix. */ endsWith(searchString: string, position?: number): boolean { return this.modified.endsWith(searchString, position); } private _splitString(pattern: string, limit?: number): BiString[] { if (limit === undefined) { limit = Infinity; } const result = []; for (let i = 0, j, k; i >= 0 && result.length < limit; i = k) { if (pattern.length === 0) { if (i + 1 < this.length) { j = k = i + 1; } else { j = k = -1; } } else { [j, k] = this.boundsOf(pattern, i); } if (j >= 0) { result.push(this.slice(i, j)); } else { result.push(this.slice(i)); } } return result; } private _splitRegExp(pattern: RegExp, limit?: number): BiString[] { pattern = cloneRegExp(pattern, "g", "y"); if (limit === undefined) { limit = Infinity; } const result = []; let last = 0; for (const match of this.matchAll(pattern)) { if (result.length >= limit) { break; } const start = match.index!; const end = start + match[0].length; result.push(this.slice(last, start)); // String.prototype.split() will include any captured substrings in the result. But we can't support that // easily, since JS regexes give us no information about the position of matched capture groups if (match.length > 1) { throw new Error("split() with capture groups is not supported"); } last = end; } if (result.length < limit) { result.push(this.slice(last)); } return result; } /** * Like :js:meth:`String.prototype.split`, splits this string into chunks using a separator. */ split(separator?: string | RegExp, limit?: number): BiString[] { if (separator === undefined) { return [this]; } else if (typeof(separator) === "string") { return this._splitString(separator, limit); } else { return this._splitRegExp(separator, limit); } } /** * Like :js:meth:`Array.prototype.join`, joins a sequence together with this `BiString` as the separator. */ join(items: Iterable<AnyString>): BiString { let [first, ...rest] = items; if (first === undefined) { return new BiString(""); } first = BiString.from(first); rest = rest.flatMap(s => [this, s]); return first.concat(...rest); } private static _normalFormRegex(form: string) { switch (form) { case "NFC": return unicode.NFC_CHUNK; case "NFD": return unicode.NFD_CHUNK; case "NFKC": return unicode.NFKC_CHUNK; case "NFKD": return unicode.NFKD_CHUNK; default: throw new RangeError(`Expected a normalization form (NFC, NFD, NFKC, NFKD); found ${form}`); } } /** * Like :js:meth:`String.prototype.normalize`, applies a Unicode normalization form. * * @param form * The normalization form to apply, one of "NFC", "NFD", "NFKC", or "NFKD". */ normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): BiString { const regex = BiString._normalFormRegex(form); return this.replace(regex, m => { const result = m.normalize(form); if (result === m) { return new BiString(m); } else { return new BiString(m, result); } }); } private _isFinalSigmaAt(index: number): boolean { if (this[index] !== "Ξ£") { return false; } // Emulate negative lookahead: (?!\p{Case_Ignorable}*+\p{Cased}) for (let i = index + 1; i < this.length; ++i) { const cp = this.codePointAt(i)!; const c = String.fromCodePoint(cp); if (/\P{Case_Ignorable}/uy.test(c)) { if (/\p{Cased}/uy.test(c)) { return false; } else { break; } } if (cp > 0xFFFF) { ++i; } } // Emulate positive lookbehind: (?<=\p{Cased}\p{Case_Ignorable}*+) for (let i = index; i-- > 0;) { let cp = this.charCodeAt(i); if (i > 0 && (cp & 0xFC00) == 0xDC00 && (this.charCodeAt(i - 1) & 0xFC00) == 0xD800) { --i; cp = this.codePointAt(i)!; } const c = String.fromCodePoint(cp); if (/\P{Case_Ignorable}/uy.test(c)) { if (/\p{Cased}/uy.test(c)) { return true; } else { break; } } } return false; } /** * Like :js:meth:`String.prototype.toLowerCase`, converts a string to lowercase. */ toLowerCase(): BiString { return this.replace(/\p{Changes_When_Lowercased}/gu, (m, ...args) => { // This is the only contextual but non-language-specific mapping in SpecialCasing.txt as of Unicode 12.1 if (this._isFinalSigmaAt(args[args.length - 2])) { return "Ο‚"; } else { return m.toLowerCase(); } }); } /** * Like :js:meth:`String.prototype.toUpperCase`, converts a string to uppercase. */ toUpperCase(): BiString { return this.replace(/\p{Changes_When_Uppercased}/gu, m => m.toUpperCase()); } }
bistring/js/src/bistring.ts/0
{ "file_path": "bistring/js/src/bistring.ts", "repo_id": "bistring", "token_count": 8427 }
361
bistring ======== |PyPI version| The bistring library provides non-destructive versions of common string processing operations like normalization, case folding, and find/replace. Each bistring remembers the original string, and how its substrings map to substrings of the modified version. For example: .. code-block:: python >>> from bistring import bistr >>> s = bistr('π•Ώπ–π–Š π––π–šπ–Žπ–ˆπ–, π–‡π–—π–”π–œπ–“ 🦊 π–π–šπ–’π–•π–˜ π–”π–›π–Šπ–— π–™π–π–Š π–‘π–†π–Ÿπ–ž 🐢') >>> s = s.normalize('NFKD') # Unicode normalization >>> s = s.casefold() # Case-insensitivity >>> s = s.replace('🦊', 'fox') # Replace emoji with text >>> s = s.replace('🐢', 'dog') >>> s = s.sub(r'[^\w\s]+', '') # Strip everything but letters and spaces >>> s = s[:19] # Extract a substring >>> s.modified # The modified substring, after changes 'the quick brown fox' >>> s.original # The original substring, before changes 'π•Ώπ–π–Š π––π–šπ–Žπ–ˆπ–, π–‡π–—π–”π–œπ–“ 🦊' This allows you to perform very aggressive text processing completely invisibly. .. |PyPI version| image:: https://badge.fury.io/py/bistring.svg :target: https://pypi.org/project/bistring/
bistring/python/README.rst/0
{ "file_path": "bistring/python/README.rst", "repo_id": "bistring", "token_count": 552 }
362
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. from bistring import Alignment import pytest def test_empty(): pytest.raises(ValueError, Alignment, []) alignment = Alignment.identity(0) assert list(alignment) == [(0, 0)] assert alignment.original_bounds() == (0, 0) assert alignment.modified_bounds() == (0, 0) assert alignment.original_bounds(0, 0) == (0, 0) assert alignment.modified_bounds(0, 0) == (0, 0) def test_indexing(): data = [ (0, 1), (1, 2), (2, 4), (3, 8), (4, 16), ] length = len(data) alignment = Alignment(data) assert len(alignment) == length for i in range(length): assert alignment[i] == data[i] assert alignment[i - length] == data[i - length] for j in range(i + 1, length + 1): assert list(alignment[i:j]) == data[i:j] def test_identity(): alignment = Alignment.identity(1, 16) assert alignment == Alignment((i, i) for i in range(1, 17)) assert list(alignment) == [(i, i) for i in range(1, 17)] assert alignment.original_bounds() == (1, 16) assert alignment.modified_bounds() == (1, 16) assert alignment.original_bounds(4, 7) == (4, 7) assert alignment.modified_bounds(4, 7) == (4, 7) def test_aligning(): alignment = Alignment([(0, 0), (1, 2), (2, 4), (3, 6)]) assert alignment.original_bounds() == (0, 3) assert alignment.modified_bounds() == (0, 6) assert alignment.original_bounds(0, 0) == (0, 0) assert alignment.original_bounds(0, 1) == (0, 1) assert alignment.original_bounds(0, 2) == (0, 1) assert alignment.original_bounds(0, 3) == (0, 2) assert alignment.original_bounds(1, 1) == (0, 1) assert alignment.original_bounds(1, 3) == (0, 2) assert alignment.original_bounds(1, 4) == (0, 2) assert alignment.original_bounds(2, 2) == (1, 1) assert alignment.original_bounds(2, 4) == (1, 2) assert alignment.original_bounds(2, 5) == (1, 3) assert alignment.original_bounds(3, 3) == (1, 2) assert alignment.modified_bounds(0, 0) == (0, 0) assert alignment.modified_bounds(0, 1) == (0, 2) assert alignment.modified_bounds(0, 2) == (0, 4) assert alignment.modified_bounds(0, 3) == (0, 6) assert alignment.modified_bounds(1, 1) == (2, 2) assert alignment.modified_bounds(2, 2) == (4, 4) def test_canonicalization(): assert Alignment([(0, 0), (1, 2), (1, 2), (2, 4)]) == Alignment([(0, 0), (1, 2), (2, 4)]) assert Alignment([(0, 0), (1, 2)]) + Alignment([(1, 2), (2, 4)]) == Alignment([(0, 0), (1, 2), (2, 4)]) def _test_composition(first, second): composed = first.compose(second) of, ol = composed.original_bounds() mf, ml = composed.modified_bounds() assert (of, ol) == first.original_bounds() assert (mf, ml) == second.modified_bounds() for i in range(of, ol + 1): for j in range(i, ol + 1): assert composed.modified_bounds(i, j) == second.modified_bounds(first.modified_bounds(i, j)) for i in range(mf, ml + 1): for j in range(i, ml + 1): assert composed.original_bounds(i, j) == first.original_bounds(second.original_bounds(i, j)) def test_compose(): first = Alignment((i, 2 * i) for i in range(4)) second = Alignment((i, 2 * i) for i in range(7)) _test_composition(first, second) def _test_identity_composition(alignment): _test_composition(alignment, Alignment.identity(alignment.modified_range())) _test_composition(Alignment.identity(alignment.original_range()), alignment) def test_compose_identity(): alignment = Alignment([ (0, 2), (2, 2), (4, 4), (6, 6), (8, 6), ]) # Modified sequence is smaller _test_identity_composition(alignment) # Original sequence is smaller _test_identity_composition(alignment.inverse()) def test_infer(): assert Alignment.infer('test', 'test') == Alignment.identity(4) assert Alignment.infer('asdf', 'jkl;') == Alignment.identity(4) assert Alignment.infer('color', 'colour') == Alignment([ (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (4, 5), (5, 6), ]) assert Alignment.infer('color', 'colour') == Alignment.infer('colour', 'color').inverse() assert Alignment.infer("ab---", "ab") == Alignment([ (0, 0), (1, 1), (2, 2), (3, 2), (4, 2), (5, 2), ])
bistring/python/tests/test_alignment.py/0
{ "file_path": "bistring/python/tests/test_alignment.py", "repo_id": "bistring", "token_count": 1938 }
363
{ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "type": "AdaptiveCard", "version": "1.0", "body": [ { "type": "Image", "url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU", "size": "stretch" }, { "type": "TextBlock", "spacing": "medium", "size": "default", "weight": "bolder", "text": "Welcome to Bot Framework!", "wrap": true, "maxLines": 0 }, { "type": "TextBlock", "size": "default", "isSubtle": "true", "text": "Now that you have successfully run your bot, follow the links in this Adaptive Card to expand your knowledge of Bot Framework.", "wrap": true, "maxLines": 0 } ], "actions": [ { "type": "Action.OpenUrl", "title": "Get an overview", "url": "https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0" }, { "type": "Action.OpenUrl", "title": "Ask a question", "url": "https://stackoverflow.com/questions/tagged/botframework" }, { "type": "Action.OpenUrl", "title": "Learn how to deploy", "url": "https://docs.microsoft.com/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0" } ] }
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/cards/welcomeCard.json/0
{ "file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/cards/welcomeCard.json", "repo_id": "botbuilder-python", "token_count": 618 }
364
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from botbuilder.core import MessageFactory from botbuilder.dialogs import WaterfallDialog, DialogTurnResult, WaterfallStepContext from botbuilder.dialogs.prompts import ( DateTimePrompt, PromptValidatorContext, PromptOptions, DateTimeResolution, ) from botbuilder.schema import InputHints from datatypes_date_time.timex import Timex from .cancel_and_help_dialog import CancelAndHelpDialog class DateResolverDialog(CancelAndHelpDialog): def __init__(self, dialog_id: str = None): super(DateResolverDialog, self).__init__( dialog_id or DateResolverDialog.__name__ ) self.add_dialog( DateTimePrompt( DateTimePrompt.__name__, DateResolverDialog.datetime_prompt_validator ) ) self.add_dialog( WaterfallDialog( WaterfallDialog.__name__ + "2", [self.initial_step, self.final_step] ) ) self.initial_dialog_id = WaterfallDialog.__name__ + "2" async def initial_step( self, step_context: WaterfallStepContext ) -> DialogTurnResult: timex = step_context.options prompt_msg_text = "On what date would you like to travel?" prompt_msg = MessageFactory.text( prompt_msg_text, prompt_msg_text, InputHints.expecting_input ) reprompt_msg_text = "I'm sorry, for best results, please enter your travel date " \ "including the month, day and year." reprompt_msg = MessageFactory.text( reprompt_msg_text, reprompt_msg_text, InputHints.expecting_input ) if timex is None: # We were not given any date at all so prompt the user. return await step_context.prompt( DateTimePrompt.__name__, PromptOptions(prompt=prompt_msg, retry_prompt=reprompt_msg), ) # We have a Date we just need to check it is unambiguous. if "definite" not in Timex(timex).types: # This is essentially a "reprompt" of the data we were given up front. return await step_context.prompt( DateTimePrompt.__name__, PromptOptions(prompt=reprompt_msg) ) return await step_context.next(DateTimeResolution(timex=timex)) async def final_step(self, step_context: WaterfallStepContext): timex = step_context.result[0].timex return await step_context.end_dialog(timex) @staticmethod async def datetime_prompt_validator(prompt_context: PromptValidatorContext) -> bool: if prompt_context.recognized.succeeded: timex = prompt_context.recognized.value[0].timex.split("T")[0] return "definite" in Timex(timex).types return False
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/date_resolver_dialog.py/0
{ "file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/date_resolver_dialog.py", "repo_id": "botbuilder-python", "token_count": 1212 }
365
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class SlackAdapterOptions: """ Class for defining implementation of the SlackAdapter Options. """ def __init__(self): self.verify_incoming_requests = True
botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adatper_options.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adatper_options.py", "repo_id": "botbuilder-python", "token_count": 83 }
366
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from datetime import datetime from botbuilder.schema import ( Activity, ActivityTypes, ChannelAccount, ConversationAccount, ) class ActivityUtil: @staticmethod def create_trace( turn_activity: Activity, name: str, value: object = None, value_type: str = None, label: str = None, ) -> Activity: """Creates a trace activity based on this activity. :param turn_activity: :type turn_activity: Activity :param name: The value to assign to the trace activity's <see cref="Activity.name"/> property. :type name: str :param value: The value to assign to the trace activity's <see cref="Activity.value"/> property., defaults to None :param value: object, optional :param value_type: The value to assign to the trace activity's <see cref="Activity.value_type"/> property, defaults to None :param value_type: str, optional :param label: The value to assign to the trace activity's <see cref="Activity.label"/> property, defaults to None :param label: str, optional :return: The created trace activity. :rtype: Activity """ from_property = ( ChannelAccount( id=turn_activity.recipient.id, name=turn_activity.recipient.name ) if turn_activity.recipient is not None else ChannelAccount() ) if value_type is None and value is not None: value_type = type(value).__name__ reply = Activity( type=ActivityTypes.trace, timestamp=datetime.utcnow(), from_property=from_property, recipient=ChannelAccount( id=turn_activity.from_property.id, name=turn_activity.from_property.name ), reply_to_id=turn_activity.id, service_url=turn_activity.service_url, channel_id=turn_activity.channel_id, conversation=ConversationAccount( is_group=turn_activity.conversation.is_group, id=turn_activity.conversation.id, name=turn_activity.conversation.name, ), name=name, label=label, value_type=value_type, value=value, ) return reply
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py", "repo_id": "botbuilder-python", "token_count": 1071 }
367
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from .feedback_record import FeedbackRecord from .feedback_records import FeedbackRecords from .generate_answer_request_body import GenerateAnswerRequestBody from .join_operator import JoinOperator from .metadata import Metadata from .prompt import Prompt from .qnamaker_trace_info import QnAMakerTraceInfo from .qna_request_context import QnARequestContext from .qna_response_context import QnAResponseContext from .query_result import QueryResult from .query_results import QueryResults from .train_request_body import TrainRequestBody __all__ = [ "FeedbackRecord", "FeedbackRecords", "GenerateAnswerRequestBody", "JoinOperator", "Metadata", "Prompt", "QnAMakerTraceInfo", "QnARequestContext", "QnAResponseContext", "QueryResult", "QueryResults", "TrainRequestBody", ]
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/__init__.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/__init__.py", "repo_id": "botbuilder-python", "token_count": 320 }
368
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class QnAMakerEndpoint: def __init__(self, knowledge_base_id: str, endpoint_key: str, host: str): if not knowledge_base_id: raise TypeError("QnAMakerEndpoint.knowledge_base_id cannot be empty.") if not endpoint_key: raise TypeError("QnAMakerEndpoint.endpoint_key cannot be empty.") if not host: raise TypeError("QnAMakerEndpoint.host cannot be empty.") self.knowledge_base_id = knowledge_base_id self.endpoint_key = endpoint_key self.host = host
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_endpoint.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_endpoint.py", "repo_id": "botbuilder-python", "token_count": 245 }
369
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # pylint: disable=no-value-for-parameter import json from os import path from typing import Dict, Tuple, Union import re from unittest import mock from unittest.mock import MagicMock from aioresponses import aioresponses from aiounittest import AsyncTestCase from botbuilder.ai.luis import LuisRecognizerOptionsV3 from botbuilder.ai.luis import LuisApplication, LuisPredictionOptions, LuisRecognizer from botbuilder.ai.luis.luis_util import LuisUtil from botbuilder.core import ( BotAdapter, IntentScore, RecognizerResult, TurnContext, ) from botbuilder.core.adapters import TestAdapter from botbuilder.schema import ( Activity, ActivityTypes, ChannelAccount, ConversationAccount, ) class LuisRecognizerV3Test(AsyncTestCase): _luisAppId: str = "b31aeaf3-3511-495b-a07f-571fc873214b" _subscriptionKey: str = "048ec46dc58e495482b0c447cfdbd291" _endpoint: str = "https://westus.api.cognitive.microsoft.com" def __init__(self, *args, **kwargs): super(LuisRecognizerV3Test, self).__init__(*args, **kwargs) self._mocked_results: RecognizerResult = RecognizerResult( intents={"Test": IntentScore(score=0.2), "Greeting": IntentScore(score=0.4)} ) self._empty_luis_response: Dict[str, object] = json.loads( '{ "query": null, "intents": [], "entities": [] }' ) @staticmethod def _remove_none_property(dictionary: Dict[str, object]) -> Dict[str, object]: for key, value in list(dictionary.items()): if value is None: del dictionary[key] elif isinstance(value, dict): LuisRecognizerV3Test._remove_none_property(value) return dictionary @classmethod @aioresponses() async def _get_recognizer_result( cls, utterance: str, response_json: Union[str, Dict[str, object]], mock_get, bot_adapter: BotAdapter = TestAdapter(), options: Union[LuisRecognizerOptionsV3, LuisPredictionOptions] = None, include_api_results: bool = False, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, recognizer_class: type = LuisRecognizer, ) -> Tuple[LuisRecognizer, RecognizerResult]: if isinstance(response_json, str): response_json = LuisRecognizerV3Test._get_json_for_file( response_file=response_json ) recognizer = LuisRecognizerV3Test._get_luis_recognizer( recognizer_class, include_api_results=include_api_results, options=options ) context = LuisRecognizerV3Test._get_context(utterance, bot_adapter) # mock_get.return_value.__aenter__.return_value.json = CoroutineMock(side_effect=[response_json]) pattern = re.compile(r"^https://westus.api.cognitive.microsoft.com.*$") mock_get.post(pattern, payload=response_json, status=200) result = await recognizer.recognize( context, telemetry_properties, telemetry_metrics ) return recognizer, result @classmethod def _get_json_for_file(cls, response_file: str) -> Dict[str, object]: curr_dir = path.dirname(path.abspath(__file__)) response_path = path.join(curr_dir, "test_data", response_file) with open(response_path, "r", encoding="utf-8-sig") as file: response_str = file.read() response_json = json.loads(response_str) return response_json @classmethod def _get_luis_recognizer( cls, recognizer_class: type, options: Union[LuisPredictionOptions, LuisRecognizerOptionsV3] = None, include_api_results: bool = False, ) -> LuisRecognizer: luis_app = LuisApplication(cls._luisAppId, cls._subscriptionKey, cls._endpoint) if isinstance(options, LuisRecognizerOptionsV3): LuisRecognizerOptionsV3.include_api_results = include_api_results return recognizer_class( luis_app, prediction_options=options, include_api_results=include_api_results, ) @staticmethod def _get_context(utterance: str, bot_adapter: BotAdapter) -> TurnContext: activity = Activity( type=ActivityTypes.message, text=utterance, conversation=ConversationAccount(), recipient=ChannelAccount(), from_property=ChannelAccount(), ) return TurnContext(bot_adapter, activity) # Luis V3 endpoint tests begin here async def _test_json_v3(self, response_file: str) -> None: # Arrange expected_json = LuisRecognizerV3Test._get_json_for_file(response_file) response_json = expected_json["v3"]["response"] utterance = expected_json.get("text") if utterance is None: utterance = expected_json.get("Text") test_options = expected_json["v3"]["options"] options = LuisRecognizerOptionsV3( include_all_intents=test_options["includeAllIntents"], include_instance_data=test_options["includeInstanceData"], log=test_options["log"], prefer_external_entities=test_options["preferExternalEntities"], slot=test_options["slot"], include_api_results=test_options["includeAPIResults"], ) if "version" in test_options: options.version = test_options["version"] if "externalEntities" in test_options: options.external_entities = test_options["externalEntities"] # dynamic_lists: List = None, # external_entities: List = None, # telemetry_client: BotTelemetryClient = NullTelemetryClient(), # log_personal_information: bool = False,) # , # Act _, result = await LuisRecognizerV3Test._get_recognizer_result( utterance, response_json, options=options, include_api_results=True ) # Assert actual_result_json = LuisUtil.recognizer_result_as_dict(result) del expected_json["v3"] trimmed_expected = LuisRecognizerV3Test._remove_none_property(expected_json) trimmed_actual = LuisRecognizerV3Test._remove_none_property(actual_result_json) self.assertEqual(trimmed_expected, trimmed_actual) async def test_composite1_v3(self): await self._test_json_v3("Composite1_v3.json") async def test_composite2_v3(self): await self._test_json_v3("Composite2_v3.json") async def test_composite3_v3(self): await self._test_json_v3("Composite3_v3.json") async def test_external_entities_and_built_in_v3(self): await self._test_json_v3("ExternalEntitiesAndBuiltIn_v3.json") async def test_external_entities_and_composite_v3(self): await self._test_json_v3("ExternalEntitiesAndComposite_v3.json") async def test_external_entities_and_list_v3(self): await self._test_json_v3("ExternalEntitiesAndList_v3.json") async def test_external_entities_and_regex_v3(self): await self._test_json_v3("ExternalEntitiesAndRegex_v3.json") async def test_external_entities_and_simple_v3(self): await self._test_json_v3("ExternalEntitiesAndSimple_v3.json") async def test_geo_people_ordinal_v3(self): await self._test_json_v3("GeoPeopleOrdinal_v3.json") async def test_minimal_v3(self): await self._test_json_v3("Minimal_v3.json") async def test_no_entities_instance_true_v3(self): await self._test_json_v3("NoEntitiesInstanceTrue_v3.json") async def test_patterns_v3(self): await self._test_json_v3("Patterns_v3.json") async def test_prebuilt_v3(self): await self._test_json_v3("Prebuilt_v3.json") async def test_roles_v3(self): await self._test_json_v3("roles_v3.json") async def test_trace_activity(self): # Arrange utterance: str = "fly on delta at 3pm" expected_json = LuisRecognizerV3Test._get_json_for_file("Minimal_v3.json") response_json = expected_json["v3"]["response"] # add async support to magic mock. async def async_magic(): pass MagicMock.__await__ = lambda x: async_magic().__await__() # Act with mock.patch.object(TurnContext, "send_activity") as mock_send_activity: await LuisRecognizerV3Test._get_recognizer_result( utterance, response_json, options=LuisRecognizerOptionsV3() ) trace_activity: Activity = mock_send_activity.call_args[0][0] # Assert self.assertIsNotNone(trace_activity) self.assertEqual(LuisRecognizer.luis_trace_type, trace_activity.value_type) self.assertEqual(LuisRecognizer.luis_trace_label, trace_activity.label) luis_trace_info = trace_activity.value self.assertIsNotNone(luis_trace_info) self.assertIsNotNone(luis_trace_info["recognizerResult"]) self.assertIsNotNone(luis_trace_info["luisResult"]) self.assertIsNotNone(luis_trace_info["luisOptions"]) self.assertIsNotNone(luis_trace_info["luisModel"]) recognizer_result: RecognizerResult = luis_trace_info["recognizerResult"] self.assertEqual(utterance, recognizer_result["text"]) self.assertIsNotNone(recognizer_result["intents"]["Roles"]) self.assertEqual( LuisRecognizerV3Test._luisAppId, luis_trace_info["luisModel"]["ModelID"] )
botbuilder-python/libraries/botbuilder-ai/tests/luis/luis_recognizer_v3_test.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/luis_recognizer_v3_test.py", "repo_id": "botbuilder-python", "token_count": 4065 }
370
{ "entities": { "$instance": { "child": [ { "endIndex": 99, "modelType": "Prebuilt Entity Extractor", "recognitionSources": [ "model" ], "startIndex": 87, "text": "lisa simpson", "type": "builtin.personName" } ], "endloc": [ { "endIndex": 51, "modelType": "Prebuilt Entity Extractor", "recognitionSources": [ "model" ], "startIndex": 44, "text": "jakarta", "type": "builtin.geographyV2.city" } ], "ordinalV2": [ { "endIndex": 28, "modelType": "Prebuilt Entity Extractor", "recognitionSources": [ "model" ], "startIndex": 24, "text": "last", "type": "builtin.ordinalV2.relative" } ], "parent": [ { "endIndex": 69, "modelType": "Prebuilt Entity Extractor", "recognitionSources": [ "model" ], "startIndex": 56, "text": "homer simpson", "type": "builtin.personName" } ], "startloc": [ { "endIndex": 40, "modelType": "Prebuilt Entity Extractor", "recognitionSources": [ "model" ], "startIndex": 34, "text": "london", "type": "builtin.geographyV2.city" } ], "startpos": [ { "endIndex": 20, "modelType": "Prebuilt Entity Extractor", "recognitionSources": [ "model" ], "startIndex": 8, "text": "next to last", "type": "builtin.ordinalV2.relative" } ] }, "child": [ "lisa simpson" ], "endloc": [ { "location": "jakarta", "type": "city" } ], "ordinalV2": [ { "offset": 0, "relativeTo": "end" } ], "parent": [ "homer simpson" ], "startloc": [ { "location": "london", "type": "city" } ], "startpos": [ { "offset": -1, "relativeTo": "end" } ] }, "intents": { "Cancel": { "score": 0.000107549029 }, "Delivery": { "score": 0.00123035291 }, "EntityTests": { "score": 0.0009487789 }, "Greeting": { "score": 5.293933E-05 }, "Help": { "score": 0.0001358991 }, "None": { "score": 0.0109820236 }, "Roles": { "score": 0.999204934 }, "search": { "score": 0.0263254233 }, "SpecifyName": { "score": 0.00104324089 }, "Travel": { "score": 0.01043327 }, "Weather_GetForecast": { "score": 0.0106523167 } }, "sentiment": { "label": "neutral", "score": 0.5 }, "text": "go from next to last to last move london to jakarta and homer simpson is the parent of lisa simpson", "v3": { "options": { "includeAllIntents": true, "includeAPIResults": true, "includeInstanceData": true, "log": true, "preferExternalEntities": true, "slot": "production" }, "response": { "prediction": { "entities": { "$instance": { "child": [ { "length": 12, "modelType": "Prebuilt Entity Extractor", "modelTypeId": 2, "recognitionSources": [ "model" ], "role": "child", "startIndex": 87, "text": "lisa simpson", "type": "builtin.personName" } ], "endloc": [ { "length": 7, "modelType": "Prebuilt Entity Extractor", "modelTypeId": 2, "recognitionSources": [ "model" ], "role": "endloc", "startIndex": 44, "text": "jakarta", "type": "builtin.geographyV2.city" } ], "ordinalV2": [ { "length": 4, "modelType": "Prebuilt Entity Extractor", "modelTypeId": 2, "recognitionSources": [ "model" ], "startIndex": 24, "text": "last", "type": "builtin.ordinalV2.relative" } ], "parent": [ { "length": 13, "modelType": "Prebuilt Entity Extractor", "modelTypeId": 2, "recognitionSources": [ "model" ], "role": "parent", "startIndex": 56, "text": "homer simpson", "type": "builtin.personName" } ], "startloc": [ { "length": 6, "modelType": "Prebuilt Entity Extractor", "modelTypeId": 2, "recognitionSources": [ "model" ], "role": "startloc", "startIndex": 34, "text": "london", "type": "builtin.geographyV2.city" } ], "startpos": [ { "length": 12, "modelType": "Prebuilt Entity Extractor", "modelTypeId": 2, "recognitionSources": [ "model" ], "role": "startpos", "startIndex": 8, "text": "next to last", "type": "builtin.ordinalV2.relative" } ] }, "child": [ "lisa simpson" ], "endloc": [ { "value": "jakarta", "type": "city" } ], "ordinalV2": [ { "offset": 0, "relativeTo": "end" } ], "parent": [ "homer simpson" ], "startloc": [ { "value": "london", "type": "city" } ], "startpos": [ { "offset": -1, "relativeTo": "end" } ] }, "intents": { "Cancel": { "score": 0.000107549029 }, "Delivery": { "score": 0.00123035291 }, "EntityTests": { "score": 0.0009487789 }, "Greeting": { "score": 5.293933E-05 }, "Help": { "score": 0.0001358991 }, "None": { "score": 0.0109820236 }, "Roles": { "score": 0.999204934 }, "search": { "score": 0.0263254233 }, "SpecifyName": { "score": 0.00104324089 }, "Travel": { "score": 0.01043327 }, "Weather.GetForecast": { "score": 0.0106523167 } }, "normalizedQuery": "go from next to last to last move london to jakarta and homer simpson is the parent of lisa simpson", "sentiment": { "label": "neutral", "score": 0.5 }, "topIntent": "Roles" }, "query": "go from next to last to last move london to jakarta and homer simpson is the parent of lisa simpson" } } }
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/GeoPeopleOrdinal_v3.json/0
{ "file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/GeoPeopleOrdinal_v3.json", "repo_id": "botbuilder-python", "token_count": 5435 }
371
{ "answers": [ { "questions": [ "Where can you find Squirtle" ], "answer": "Did you not see him in the first three balls?", "score": 80.22, "id": 28, "source": "Editorial", "metadata": [ { "name": "species", "value": "turtle" }, { "name": "type", "value": "water" } ], "context": { "isContextOnly": false, "prompts": [] } }, { "questions": [ "Where can you find Ash", "Ash" ], "answer": "I don't know. Maybe ask your little electric mouse friend?", "score": 63.74, "id": 26, "source": "Editorial", "metadata": [ { "name": "species", "value": "human" }, { "name": "type", "value": "miscellaneous" } ], "context": { "isContextOnly": false, "prompts": [] } }, { "questions": [ "Where can you find Misty", "Misty" ], "answer": "Wherever people are having a swimming good time", "score": 31.13, "id": 27, "source": "Editorial", "metadata": [ { "name": "species", "value": "human" }, { "name": "type", "value": "water" } ], "context": { "isContextOnly": false, "prompts": [] } } ], "activeLearningEnabled": true }
botbuilder-python/libraries/botbuilder-ai/tests/qna/test_data/RetrunsAnswer_WithStrictFilter_Or_Operator.json/0
{ "file_path": "botbuilder-python/libraries/botbuilder-ai/tests/qna/test_data/RetrunsAnswer_WithStrictFilter_Or_Operator.json", "repo_id": "botbuilder-python", "token_count": 1357 }
372
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import datetime import inspect import sys import time import uuid from applicationinsights.channel import TelemetryContext, contracts from django.http import Http404 from . import common try: basestring # Python 2 except NameError: # Python 3 basestring = (str,) # pylint: disable=invalid-name # Pick a function to measure time; starting with 3.3, time.monotonic is available. try: TIME_FUNC = time.monotonic except AttributeError: TIME_FUNC = time.time class ApplicationInsightsMiddleware: """This class is a Django middleware that automatically enables request and exception telemetry. Django versions 1.7 and newer are supported. To enable, add this class to your settings.py file in MIDDLEWARE_CLASSES (pre-1.10) or MIDDLEWARE (1.10 and newer): .. code:: python # If on Django < 1.10 MIDDLEWARE_CLASSES = [ # ... or whatever is below for you ... 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # ... or whatever is above for you ... 'botbuilder.applicationinsights.django.ApplicationInsightsMiddleware', # Add this middleware to the end ] # If on Django >= 1.10 MIDDLEWARE = [ # ... or whatever is below for you ... 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # ... or whatever is above for you ... 'botbuilder.applicationinsights.django.ApplicationInsightsMiddleware', # Add this middleware to the end ] And then, add the following to your settings.py file: .. code:: python APPLICATION_INSIGHTS = { # (required) Your Application Insights instrumentation key 'ikey': "00000000-0000-0000-0000-000000000000", # (optional) By default, request names are logged as the request method # and relative path of the URL. To log the fully-qualified view names # instead, set this to True. Defaults to False. 'use_view_name': True, # (optional) To log arguments passed into the views as custom properties, # set this to True. Defaults to False. 'record_view_arguments': True, # (optional) Exceptions are logged by default, to disable, set this to False. 'log_exceptions': False, # (optional) Events are submitted to Application Insights asynchronously. # send_interval specifies how often the queue is checked for items to submit. # send_time specifies how long the sender waits for new input before recycling # the background thread. 'send_interval': 1.0, # Check every second 'send_time': 3.0, # Wait up to 3 seconds for an event # (optional, uncommon) If you must send to an endpoint other than the # default endpoint, specify it here: 'endpoint': "https://dc.services.visualstudio.com/v2/track", } Once these are in place, each request will have an `appinsights` object placed on it. This object will have the following properties: * `client`: This is an instance of the :class:`applicationinsights.TelemetryClient` type, which will submit telemetry to the same instrumentation key, and will parent each telemetry item to the current request. * `request`: This is the :class:`applicationinsights.channel.contracts.RequestData` instance for the current request. You can modify properties on this object during the handling of the current request. It will be submitted when the request has finished. * `context`: This is the :class:`applicationinsights.channel.TelemetryContext` object for the current ApplicationInsights sender. These properties will be present even when `DEBUG` is `True`, but it may not submit telemetry unless `debug_ikey` is set in `APPLICATION_INSIGHTS`, above. """ def __init__(self, get_response=None): self.get_response = get_response # Get configuration self._settings = common.load_settings() self._client = common.create_client(self._settings) # Pre-1.10 handler def process_request(self, request): # pylint: disable=useless-return # Populate context object onto request addon = RequestAddon(self._client) data = addon.request context = addon.context request.appinsights = addon # Basic request properties data.start_time = datetime.datetime.utcnow().isoformat() + "Z" data.http_method = request.method data.url = request.build_absolute_uri() data.name = "%s %s" % (request.method, request.path) context.operation.name = data.name context.operation.id = data.id context.location.ip = request.META.get("REMOTE_ADDR", "") context.user.user_agent = request.META.get("HTTP_USER_AGENT", "") # User if hasattr(request, "user"): if ( request.user is not None and not request.user.is_anonymous and request.user.is_authenticated ): context.user.account_id = request.user.get_short_name() # Run and time the request addon.start_stopwatch() return None # Pre-1.10 handler def process_response(self, request, response): if hasattr(request, "appinsights"): addon = request.appinsights data = addon.request context = addon.context # Fill in data from the response data.duration = addon.measure_duration() data.response_code = response.status_code data.success = response.status_code < 400 or response.status_code == 401 # Submit and return self._client.track(data, context) return response # 1.10 and up... def __call__(self, request): self.process_request(request) response = self.get_response(request) self.process_response(request, response) return response def process_view(self, request, view_func, view_args, view_kwargs): if not hasattr(request, "appinsights"): return None data = request.appinsights.request context = request.appinsights.context # Operation name is the method + url by default (set in __call__), # If use_view_name is set, then we'll look up the name of the view. if self._settings.use_view_name: mod = inspect.getmodule(view_func) if hasattr(view_func, "__name__"): name = view_func.__name__ elif hasattr(view_func, "__class__") and hasattr( view_func.__class__, "__name__" ): name = view_func.__class__.__name__ else: name = "<unknown>" if mod: opname = "%s %s.%s" % (data.http_method, mod.__name__, name) else: opname = "%s %s" % (data.http_method, name) data.name = opname context.operation.name = opname # Populate the properties with view arguments if self._settings.record_view_arguments: for i, arg in enumerate(view_args): data.properties["view_arg_" + str(i)] = arg_to_str(arg) for k, v in view_kwargs.items(): # pylint: disable=invalid-name data.properties["view_arg_" + k] = arg_to_str(v) return None def process_exception(self, request, exception): if not self._settings.log_exceptions: return None if isinstance(exception, Http404): return None _, _, tb = sys.exc_info() # pylint: disable=invalid-name if tb is None or exception is None: # No actual traceback or exception info, don't bother logging. return None client = common.get_telemetry_client_with_processor( self._client.context.instrumentation_key, self._client.channel ) if hasattr(request, "appinsights"): client.context.operation.parent_id = request.appinsights.request.id client.track_exception(type(exception), exception, tb) return None def process_template_response(self, request, response): if hasattr(request, "appinsights") and hasattr(response, "template_name"): data = request.appinsights.request data.properties["template_name"] = response.template_name return response class RequestAddon: def __init__(self, client): self._baseclient = client self._client = None self.request = contracts.RequestData() self.request.id = str(uuid.uuid4()) self.context = TelemetryContext() self.context.instrumentation_key = client.context.instrumentation_key self.context.operation.id = self.request.id self._process_start_time = None @property def client(self): if self._client is None: # Create a client that submits telemetry parented to the request. self._client = common.get_telemetry_client_with_processor( self.context.instrumentation_key, self._baseclient.channel ) self._client.context.operation.parent_id = self.context.operation.id return self._client def start_stopwatch(self): self._process_start_time = TIME_FUNC() def measure_duration(self): end_time = TIME_FUNC() return ms_to_duration(int((end_time - self._process_start_time) * 1000)) def ms_to_duration(n): # pylint: disable=invalid-name duration_parts = [] for multiplier in [1000, 60, 60, 24]: duration_parts.append(n % multiplier) n //= multiplier duration_parts.reverse() duration = "%02d:%02d:%02d.%03d" % tuple(duration_parts) if n: duration = "%d.%s" % (n, duration) return duration def arg_to_str(arg): if isinstance(arg, basestring): return arg if isinstance(arg, int): return str(arg) return repr(arg)
botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/django/middleware.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/django/middleware.py", "repo_id": "botbuilder-python", "token_count": 4479 }
373
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import json from typing import Dict, List from jsonpickle import encode from jsonpickle.unpickler import Unpickler from azure.core import MatchConditions from azure.core.exceptions import ( HttpResponseError, ResourceExistsError, ResourceNotFoundError, ) from azure.storage.blob.aio import ( BlobServiceClient, BlobClient, StorageStreamDownloader, ) from botbuilder.core import Storage class BlobStorageSettings: """The class for Azure Blob configuration for the Azure Bot Framework. :param container_name: Name of the Blob container. :type container_name: str :param account_name: Name of the Blob Storage account. Required if not using connection_string. :type account_name: str :param account_key: Key of the Blob Storage account. Required if not using connection_string. :type account_key: str :param connection_string: Connection string of the Blob Storage account. Required if not using account_name and account_key. :type connection_string: str """ def __init__( self, container_name: str, account_name: str = "", account_key: str = "", connection_string: str = "", ): self.container_name = container_name self.account_name = account_name self.account_key = account_key self.connection_string = connection_string # New Azure Blob SDK only allows connection strings, but our SDK allows key+name. # This is here for backwards compatibility. def convert_account_name_and_key_to_connection_string(settings: BlobStorageSettings): if not settings.account_name or not settings.account_key: raise Exception( "account_name and account_key are both required for BlobStorageSettings if not using a connections string." ) return ( f"DefaultEndpointsProtocol=https;AccountName={settings.account_name};" f"AccountKey={settings.account_key};EndpointSuffix=core.windows.net" ) class BlobStorage(Storage): """An Azure Blob based storage provider for a bot. This class uses a single Azure Storage Blob Container. Each entity or StoreItem is serialized into a JSON string and stored in an individual text blob. Each blob is named after the store item key, which is encoded so that it conforms a valid blob name. If an entity is an StoreItem, the storage object will set the entity's e_tag property value to the blob's e_tag upon read. Afterward, an match_condition with the ETag value will be generated during Write. New entities start with a null e_tag. :param settings: Settings used to instantiate the Blob service. :type settings: :class:`botbuilder.azure.BlobStorageSettings` """ def __init__(self, settings: BlobStorageSettings): if not settings.container_name: raise Exception("Container name is required.") if settings.connection_string: blob_service_client = BlobServiceClient.from_connection_string( settings.connection_string ) else: blob_service_client = BlobServiceClient.from_connection_string( convert_account_name_and_key_to_connection_string(settings) ) self.__container_client = blob_service_client.get_container_client( settings.container_name ) self.__initialized = False async def _initialize(self): if self.__initialized is False: # This should only happen once - assuming this is a singleton. # ContainerClient.exists() method is available in an unreleased version of the SDK. Until then, we use: try: await self.__container_client.create_container() except ResourceExistsError: pass self.__initialized = True return self.__initialized async def read(self, keys: List[str]) -> Dict[str, object]: """Retrieve entities from the configured blob container. :param keys: An array of entity keys. :type keys: Dict[str, object] :return dict: """ if not keys: raise Exception("Keys are required when reading") await self._initialize() items = {} for key in keys: blob_client = self.__container_client.get_blob_client(key) try: items[key] = await self._inner_read_blob(blob_client) except HttpResponseError as err: if err.status_code == 404: continue return items async def write(self, changes: Dict[str, object]): """Stores a new entity in the configured blob container. :param changes: The changes to write to storage. :type changes: Dict[str, object] :return: """ if changes is None: raise Exception("Changes are required when writing") if not changes: return await self._initialize() for name, item in changes.items(): blob_reference = self.__container_client.get_blob_client(name) e_tag = None if isinstance(item, dict): e_tag = item.get("e_tag", None) elif hasattr(item, "e_tag"): e_tag = item.e_tag e_tag = None if e_tag == "*" else e_tag if e_tag == "": raise Exception("blob_storage.write(): etag missing") item_str = self._store_item_to_str(item) if e_tag: await blob_reference.upload_blob( item_str, match_condition=MatchConditions.IfNotModified, etag=e_tag ) else: await blob_reference.upload_blob(item_str, overwrite=True) async def delete(self, keys: List[str]): """Deletes entity blobs from the configured container. :param keys: An array of entity keys. :type keys: Dict[str, object] """ if keys is None: raise Exception("BlobStorage.delete: keys parameter can't be null") await self._initialize() for key in keys: blob_client = self.__container_client.get_blob_client(key) try: await blob_client.delete_blob() # We can't delete what's already gone. except ResourceNotFoundError: pass def _store_item_to_str(self, item: object) -> str: return encode(item) async def _inner_read_blob(self, blob_client: BlobClient): blob = await blob_client.download_blob() return await self._blob_to_store_item(blob) @staticmethod async def _blob_to_store_item(blob: StorageStreamDownloader) -> object: item = json.loads(await blob.content_as_text()) item["e_tag"] = blob.properties.etag.replace('"', "") result = Unpickler().restore(item) return result
botbuilder-python/libraries/botbuilder-azure/botbuilder/azure/blob_storage.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-azure/botbuilder/azure/blob_storage.py", "repo_id": "botbuilder-python", "token_count": 2804 }
374
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # TODO: enable this in the future # With python 3.7 the line below will allow to do Postponed Evaluation of Annotations. See PEP 563 # from __future__ import annotations import asyncio import inspect import uuid from datetime import datetime from uuid import uuid4 from typing import Awaitable, Coroutine, Dict, List, Callable, Union from copy import copy from threading import Lock from botframework.connector.auth import AppCredentials, ClaimsIdentity from botframework.connector.token_api.models import ( SignInUrlResponse, TokenExchangeResource, TokenExchangeRequest, ) from botbuilder.schema import ( ActivityTypes, Activity, ConversationAccount, ConversationReference, ChannelAccount, ResourceResponse, TokenResponse, ) from ..bot_adapter import BotAdapter from ..turn_context import TurnContext from ..oauth.extended_user_token_provider import ExtendedUserTokenProvider class UserToken: def __init__( self, connection_name: str = None, user_id: str = None, channel_id: str = None, token: str = None, ): self.connection_name = connection_name self.user_id = user_id self.channel_id = channel_id self.token = token def equals_key(self, rhs: "UserToken"): return ( rhs is not None and self.connection_name == rhs.connection_name and self.user_id == rhs.user_id and self.channel_id == rhs.channel_id ) class ExchangeableToken(UserToken): def __init__( self, connection_name: str = None, user_id: str = None, channel_id: str = None, token: str = None, exchangeable_item: str = None, ): super(ExchangeableToken, self).__init__( connection_name=connection_name, user_id=user_id, channel_id=channel_id, token=token, ) self.exchangeable_item = exchangeable_item def equals_key(self, rhs: "ExchangeableToken") -> bool: return ( rhs is not None and self.exchangeable_item == rhs.exchangeable_item and super().equals_key(rhs) ) def to_key(self) -> str: return self.exchangeable_item class TokenMagicCode: def __init__(self, key: UserToken = None, magic_code: str = None): self.key = key self.magic_code = magic_code class TestAdapter(BotAdapter, ExtendedUserTokenProvider): __test__ = False __EXCEPTION_EXPECTED = "ExceptionExpected" def __init__( self, logic: Coroutine = None, template_or_conversation: Union[Activity, ConversationReference] = None, send_trace_activities: bool = False, ): """ Creates a new TestAdapter instance. :param logic: :param conversation: A reference to the conversation to begin the adapter state with. """ super(TestAdapter, self).__init__() self.logic = logic self._next_id: int = 0 self._user_tokens: List[UserToken] = [] self._magic_codes: List[TokenMagicCode] = [] self._conversation_lock = Lock() self.exchangeable_tokens: Dict[str, ExchangeableToken] = {} self.activity_buffer: List[Activity] = [] self.updated_activities: List[Activity] = [] self.deleted_activities: List[ConversationReference] = [] self.send_trace_activities = send_trace_activities self.template = ( template_or_conversation if isinstance(template_or_conversation, Activity) else Activity( channel_id="test", service_url="https://test.com", from_property=ChannelAccount(id="User1", name="user"), recipient=ChannelAccount(id="bot", name="Bot"), conversation=ConversationAccount(id="Convo1"), ) ) if isinstance(template_or_conversation, ConversationReference): self.template.channel_id = template_or_conversation.channel_id async def process_activity( self, activity: Activity, logic: Callable[[TurnContext], Awaitable] ): self._conversation_lock.acquire() try: # ready for next reply if activity.type is None: activity.type = ActivityTypes.message activity.channel_id = self.template.channel_id activity.from_property = self.template.from_property activity.recipient = self.template.recipient activity.conversation = self.template.conversation activity.service_url = self.template.service_url activity.id = str((self._next_id)) self._next_id += 1 finally: self._conversation_lock.release() activity.timestamp = activity.timestamp or datetime.utcnow() await self.run_pipeline(self.create_turn_context(activity), logic) async def send_activities( self, context, activities: List[Activity] ) -> List[ResourceResponse]: """ INTERNAL: called by the logic under test to send a set of activities. These will be buffered to the current `TestFlow` instance for comparison against the expected results. :param context: :param activities: :return: """ def id_mapper(activity): self.activity_buffer.append(activity) self._next_id += 1 return ResourceResponse(id=str(self._next_id)) return [ id_mapper(activity) for activity in activities if self.send_trace_activities or activity.type != "trace" ] async def delete_activity(self, context, reference: ConversationReference): """ INTERNAL: called by the logic under test to delete an existing activity. These are simply pushed onto a [deletedActivities](#deletedactivities) array for inspection after the turn completes. :param reference: :return: """ self.deleted_activities.append(reference) async def update_activity(self, context, activity: Activity): """ INTERNAL: called by the logic under test to replace an existing activity. These are simply pushed onto an [updatedActivities](#updatedactivities) array for inspection after the turn completes. :param activity: :return: """ self.updated_activities.append(activity) async def continue_conversation( self, reference: ConversationReference, callback: Callable, bot_id: str = None, claims_identity: ClaimsIdentity = None, # pylint: disable=unused-argument audience: str = None, ): """ The `TestAdapter` just calls parent implementation. :param reference: :param callback: :param bot_id: :param claims_identity: :return: """ await super().continue_conversation( reference, callback, bot_id, claims_identity, audience ) async def create_conversation( # pylint: disable=arguments-differ self, channel_id: str, callback: Callable # pylint: disable=unused-argument ): self.activity_buffer.clear() update = Activity( type=ActivityTypes.conversation_update, members_added=[], members_removed=[], channel_id=channel_id, conversation=ConversationAccount(id=str(uuid.uuid4())), ) context = self.create_turn_context(update) return await callback(context) async def receive_activity(self, activity): """ INTERNAL: called by a `TestFlow` instance to simulate a user sending a message to the bot. This will cause the adapters middleware pipe to be run and it's logic to be called. :param activity: :return: """ if isinstance(activity, str): activity = Activity(type="message", text=activity) # Initialize request. request = copy(self.template) for key, value in vars(activity).items(): if value is not None and key != "additional_properties": setattr(request, key, value) request.type = request.type or ActivityTypes.message if not request.id: self._next_id += 1 request.id = str(self._next_id) # Create context object and run middleware. context = self.create_turn_context(request) return await self.run_pipeline(context, self.logic) def get_next_activity(self) -> Activity: if len(self.activity_buffer) > 0: return self.activity_buffer.pop(0) return None async def send(self, user_says) -> object: """ Sends something to the bot. This returns a new `TestFlow` instance which can be used to add additional steps for inspecting the bots reply and then sending additional activities. :param user_says: :return: A new instance of the TestFlow object """ return TestFlow(await self.receive_activity(user_says), self) async def test( self, user_says, expected, description=None, timeout=None ) -> "TestFlow": """ Send something to the bot and expects the bot to return with a given reply. This is simply a wrapper around calls to `send()` and `assertReply()`. This is such a common pattern that a helper is provided. :param user_says: :param expected: :param description: :param timeout: :return: """ test_flow = await self.send(user_says) test_flow = await test_flow.assert_reply(expected, description, timeout) return test_flow async def tests(self, *args): """ Support multiple test cases without having to manually call `test()` repeatedly. This is a convenience layer around the `test()`. Valid args are either lists or tuples of parameters :param args: :return: """ for arg in args: description = None timeout = None if len(arg) >= 3: description = arg[2] if len(arg) == 4: timeout = arg[3] await self.test(arg[0], arg[1], description, timeout) @staticmethod def create_conversation_reference( name: str, user: str = "User1", bot: str = "Bot" ) -> ConversationReference: return ConversationReference( channel_id="test", service_url="https://test.com", conversation=ConversationAccount( is_group=False, conversation_type=name, id=name, ), user=ChannelAccount( id=user.lower(), name=user.lower(), ), bot=ChannelAccount( id=bot.lower(), name=bot.lower(), ), ) def add_user_token( self, connection_name: str, channel_id: str, user_id: str, token: str, magic_code: str = None, ): key = UserToken() key.channel_id = channel_id key.connection_name = connection_name key.user_id = user_id key.token = token if not magic_code: self._user_tokens.append(key) else: code = TokenMagicCode() code.key = key code.magic_code = magic_code self._magic_codes.append(code) async def get_user_token( self, context: TurnContext, connection_name: str, magic_code: str = None, oauth_app_credentials: AppCredentials = None, # pylint: disable=unused-argument ) -> TokenResponse: key = UserToken() key.channel_id = context.activity.channel_id key.connection_name = connection_name key.user_id = context.activity.from_property.id if magic_code: magic_code_record = list( filter(lambda x: key.equals_key(x.key), self._magic_codes) ) if magic_code_record and magic_code_record[0].magic_code == magic_code: # Move the token to long term dictionary. self.add_user_token( connection_name, key.channel_id, key.user_id, magic_code_record[0].key.token, ) # Remove from the magic code list. idx = self._magic_codes.index(magic_code_record[0]) self._magic_codes = [self._magic_codes.pop(idx)] match = [token for token in self._user_tokens if key.equals_key(token)] if match: return TokenResponse( connection_name=match[0].connection_name, token=match[0].token, expiration=None, ) # Not found. return None async def sign_out_user( self, context: TurnContext, connection_name: str = None, user_id: str = None, oauth_app_credentials: AppCredentials = None, # pylint: disable=unused-argument ): channel_id = context.activity.channel_id user_id = context.activity.from_property.id new_records = [] for token in self._user_tokens: if ( token.channel_id != channel_id or token.user_id != user_id or (connection_name and connection_name != token.connection_name) ): new_records.append(token) self._user_tokens = new_records async def get_oauth_sign_in_link( self, context: TurnContext, connection_name: str, final_redirect: str = None, # pylint: disable=unused-argument oauth_app_credentials: AppCredentials = None, # pylint: disable=unused-argument ) -> str: return ( f"https://fake.com/oauthsignin" f"/{connection_name}/{context.activity.channel_id}/{context.activity.from_property.id}" ) async def get_token_status( self, context: TurnContext, connection_name: str = None, user_id: str = None, include_filter: str = None, oauth_app_credentials: AppCredentials = None, ) -> Dict[str, TokenResponse]: return None async def get_aad_tokens( self, context: TurnContext, connection_name: str, resource_urls: List[str], user_id: str = None, # pylint: disable=unused-argument oauth_app_credentials: AppCredentials = None, # pylint: disable=unused-argument ) -> Dict[str, TokenResponse]: return None def add_exchangeable_token( self, connection_name: str, channel_id: str, user_id: str, exchangeable_item: str, token: str, ): key = ExchangeableToken( connection_name=connection_name, channel_id=channel_id, user_id=user_id, exchangeable_item=exchangeable_item, token=token, ) self.exchangeable_tokens[key.to_key()] = key def throw_on_exchange_request( self, connection_name: str, channel_id: str, user_id: str, exchangeable_item: str, ): key = ExchangeableToken( connection_name=connection_name, channel_id=channel_id, user_id=user_id, exchangeable_item=exchangeable_item, token=TestAdapter.__EXCEPTION_EXPECTED, ) self.exchangeable_tokens[key.to_key()] = key async def get_sign_in_resource_from_user( self, turn_context: TurnContext, connection_name: str, user_id: str, final_redirect: str = None, ) -> SignInUrlResponse: return await self.get_sign_in_resource_from_user_and_credentials( turn_context, None, connection_name, user_id, final_redirect ) async def get_sign_in_resource_from_user_and_credentials( self, turn_context: TurnContext, oauth_app_credentials: AppCredentials, connection_name: str, user_id: str, final_redirect: str = None, ) -> SignInUrlResponse: return SignInUrlResponse( sign_in_link=f"https://fake.com/oauthsignin/{connection_name}/{turn_context.activity.channel_id}/{user_id}", token_exchange_resource=TokenExchangeResource( id=str(uuid4()), provider_id=None, uri=f"api://{connection_name}/resource", ), ) async def exchange_token( self, turn_context: TurnContext, connection_name: str, user_id: str, exchange_request: TokenExchangeRequest, ) -> TokenResponse: return await self.exchange_token_from_credentials( turn_context, None, connection_name, user_id, exchange_request ) async def exchange_token_from_credentials( self, turn_context: TurnContext, oauth_app_credentials: AppCredentials, connection_name: str, user_id: str, exchange_request: TokenExchangeRequest, ) -> TokenResponse: exchangeable_value = exchange_request.token or exchange_request.uri key = ExchangeableToken( channel_id=turn_context.activity.channel_id, connection_name=connection_name, exchangeable_item=exchangeable_value, user_id=user_id, ) token_exchange_response = self.exchangeable_tokens.get(key.to_key()) if token_exchange_response: if token_exchange_response.token == TestAdapter.__EXCEPTION_EXPECTED: raise Exception("Exception occurred during exchanging tokens") return TokenResponse( channel_id=key.channel_id, connection_name=key.connection_name, token=token_exchange_response.token, expiration=None, ) return None def create_turn_context(self, activity: Activity) -> TurnContext: return TurnContext(self, activity) class TestFlow: __test__ = False def __init__(self, previous: Callable, adapter: TestAdapter): """ INTERNAL: creates a TestFlow instance. :param previous: :param adapter: """ self.previous = previous self.adapter = adapter async def test( self, user_says, expected, description=None, timeout=None ) -> "TestFlow": """ Send something to the bot and expects the bot to return with a given reply. This is simply a wrapper around calls to `send()` and `assertReply()`. This is such a common pattern that a helper is provided. :param user_says: :param expected: :param description: :param timeout: :return: """ test_flow = await self.send(user_says) return await test_flow.assert_reply( expected, description or f'test("{user_says}", "{expected}")', timeout ) async def send(self, user_says) -> "TestFlow": """ Sends something to the bot. :param user_says: :return: """ async def new_previous(): nonlocal self, user_says if callable(self.previous): await self.previous() await self.adapter.receive_activity(user_says) return TestFlow(await new_previous(), self.adapter) async def assert_reply( self, expected: Union[str, Activity, Callable[[Activity, str], None]], description=None, timeout=None, # pylint: disable=unused-argument is_substring=False, ) -> "TestFlow": """ Generates an assertion if the bots response doesn't match the expected text/activity. :param expected: :param description: :param timeout: :param is_substring: :return: """ # TODO: refactor method so expected can take a Callable[[Activity], None] def default_inspector(reply, description=None): if isinstance(expected, Activity): validate_activity(reply, expected) else: assert reply.type == "message", description + f" type == {reply.type}" if is_substring: assert expected in reply.text.strip(), ( description + f" text == {reply.text}" ) else: assert reply.text.strip() == expected.strip(), ( description + f" text == {reply.text}" ) if description is None: description = "" inspector = expected if callable(expected) else default_inspector async def test_flow_previous(): nonlocal timeout if not timeout: timeout = 3000 start = datetime.now() adapter = self.adapter async def wait_for_activity(): nonlocal expected, timeout current = datetime.now() if (current - start).total_seconds() * 1000 > timeout: if isinstance(expected, Activity): expecting = expected.text elif callable(expected): expecting = inspect.getsourcefile(expected) else: expecting = str(expected) raise RuntimeError( f"TestAdapter.assert_reply({expecting}): {description} Timed out after " f"{current - start}ms." ) if adapter.activity_buffer: reply = adapter.activity_buffer.pop(0) try: await inspector(reply, description) except Exception: inspector(reply, description) else: await asyncio.sleep(0.05) await wait_for_activity() await wait_for_activity() return TestFlow(await test_flow_previous(), self.adapter) async def assert_no_reply( self, description=None, timeout=None, # pylint: disable=unused-argument ) -> "TestFlow": """ Generates an assertion if the bot responds when no response is expected. :param description: :param timeout: """ if description is None: description = "" async def test_flow_previous(): nonlocal timeout if not timeout: timeout = 3000 start = datetime.now() adapter = self.adapter async def wait_for_activity(): nonlocal timeout current = datetime.now() if (current - start).total_seconds() * 1000 > timeout: # operation timed out and recieved no reply return if adapter.activity_buffer: reply = adapter.activity_buffer.pop(0) raise RuntimeError( f"TestAdapter.assert_no_reply(): '{reply.text}' is responded when waiting for no reply." ) await asyncio.sleep(0.05) await wait_for_activity() await wait_for_activity() return TestFlow(await test_flow_previous(), self.adapter) def validate_activity(activity, expected) -> None: """ Helper method that compares activities :param activity: :param expected: :return: """ iterable_expected = vars(expected).items() for attr, value in iterable_expected: if value is not None and attr != "additional_properties": assert value == getattr(activity, attr)
botbuilder-python/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py", "repo_id": "botbuilder-python", "token_count": 11031 }
375
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from abc import ABC from botbuilder.schema import Activity from botbuilder.core import InvokeResponse class BotFrameworkClient(ABC): def post_activity( self, from_bot_id: str, to_bot_id: str, to_url: str, service_url: str, conversation_id: str, activity: Activity, ) -> InvokeResponse: raise NotImplementedError()
botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/bot_framework_client.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/bot_framework_client.py", "repo_id": "botbuilder-python", "token_count": 188 }
376
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import json from botframework.streaming.payloads.models import Serializable class VersionInfo(Serializable): def __init__(self, *, user_agent: str = None): self.user_agent = user_agent def to_json(self) -> str: obj = {"userAgent": self.user_agent} return json.dumps(obj) def from_json(self, json_str: str) -> "ResponsePayload": obj = json.loads(json_str) self.user_agent = obj.get("userAgent") return self
botbuilder-python/libraries/botbuilder-core/botbuilder/core/streaming/version_info.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/streaming/version_info.py", "repo_id": "botbuilder-python", "token_count": 210 }
377
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from typing import Awaitable, Callable from botbuilder.core import Middleware, TurnContext class CallCountingMiddleware(Middleware): def __init__(self): self.counter = 0 def on_turn( # pylint: disable=unused-argument self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] ): self.counter += 1 logic()
botbuilder-python/libraries/botbuilder-core/tests/call_counting_middleware.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-core/tests/call_counting_middleware.py", "repo_id": "botbuilder-python", "token_count": 156 }
378
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from unittest.mock import MagicMock import aiounittest from botbuilder.core import ( BotState, ConversationState, MemoryStorage, Storage, StoreItem, TurnContext, UserState, ) from botbuilder.core.adapters import TestAdapter from botbuilder.schema import Activity, ConversationAccount from test_utilities import TestUtilities RECEIVED_MESSAGE = Activity(type="message", text="received") STORAGE_KEY = "stateKey" def cached_state(context, state_key): cached = context.services.get(state_key) return cached["state"] if cached is not None else None def key_factory(context): assert context is not None return STORAGE_KEY class BotStateForTest(BotState): def __init__(self, storage: Storage): super().__init__(storage, f"BotState:BotState") def get_storage_key(self, turn_context: TurnContext) -> str: return f"botstate/{turn_context.activity.channel_id}/{turn_context.activity.conversation.id}/BotState" class CustomState(StoreItem): def __init__(self, custom_string: str = None, e_tag: str = "*"): super().__init__(custom_string=custom_string, e_tag=e_tag) class TestPocoState: __test__ = False def __init__(self, value=None): self.value = value class TestBotState(aiounittest.AsyncTestCase): storage = MemoryStorage() adapter = TestAdapter() context = TurnContext(adapter, RECEIVED_MESSAGE) middleware = BotState(storage, key_factory) def test_state_empty_name(self): # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) # Act with self.assertRaises(TypeError) as _: user_state.create_property("") def test_state_none_name(self): # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) # Act with self.assertRaises(TypeError) as _: user_state.create_property(None) async def test_storage_not_called_no_changes(self): """Verify storage not called when no changes are made""" # Mock a storage provider, which counts read/writes dictionary = {} async def mock_write_result(self): # pylint: disable=unused-argument return async def mock_read_result(self): # pylint: disable=unused-argument return {} mock_storage = MemoryStorage(dictionary) mock_storage.write = MagicMock(side_effect=mock_write_result) mock_storage.read = MagicMock(side_effect=mock_read_result) # Arrange user_state = UserState(mock_storage) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property_a") self.assertEqual(mock_storage.write.call_count, 0) await user_state.save_changes(context) await property_a.set(context, "hello") self.assertEqual(mock_storage.read.call_count, 1) # Initial save bumps count self.assertEqual(mock_storage.write.call_count, 0) # Initial save bumps count await property_a.set(context, "there") self.assertEqual( mock_storage.write.call_count, 0 ) # Set on property should not bump await user_state.save_changes(context) self.assertEqual(mock_storage.write.call_count, 1) # Explicit save should bump value_a = await property_a.get(context) self.assertEqual("there", value_a) self.assertEqual(mock_storage.write.call_count, 1) # Gets should not bump await user_state.save_changes(context) self.assertEqual(mock_storage.write.call_count, 1) await property_a.delete(context) # Delete alone no bump self.assertEqual(mock_storage.write.call_count, 1) await user_state.save_changes(context) # Save when dirty should bump self.assertEqual(mock_storage.write.call_count, 2) self.assertEqual(mock_storage.read.call_count, 1) await user_state.save_changes(context) # Save not dirty should not bump self.assertEqual(mock_storage.write.call_count, 2) self.assertEqual(mock_storage.read.call_count, 1) async def test_state_set_no_load(self): """Should be able to set a property with no Load""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property_a") await property_a.set(context, "hello") async def test_state_multiple_loads(self): """Should be able to load multiple times""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act user_state.create_property("property_a") await user_state.load(context) await user_state.load(context) async def test_state_get_no_load_with_default(self): """Should be able to get a property with no Load and default""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property_a") value_a = await property_a.get(context, lambda: "Default!") self.assertEqual("Default!", value_a) async def test_state_get_no_load_no_default(self): """Cannot get a string with no default set""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property_a") value_a = await property_a.get(context) # Assert self.assertIsNone(value_a) async def test_state_poco_no_default(self): """Cannot get a POCO with no default set""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act test_property = user_state.create_property("test") value = await test_property.get(context) # Assert self.assertIsNone(value) async def test_state_bool_no_default(self): """Cannot get a bool with no default set""" # Arange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act test_property = user_state.create_property("test") value = await test_property.get(context) # Assert self.assertFalse(value) async def test_state_set_after_save(self): """Verify setting property after save""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property-a") property_b = user_state.create_property("property-b") await user_state.load(context) await property_a.set(context, "hello") await property_b.set(context, "world") await user_state.save_changes(context) await property_a.set(context, "hello2") async def test_state_multiple_save(self): """Verify multiple saves""" # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property-a") property_b = user_state.create_property("property-b") await user_state.load(context) await property_a.set(context, "hello") await property_b.set(context, "world") await user_state.save_changes(context) await property_a.set(context, "hello2") await user_state.save_changes(context) value_a = await property_a.get(context) self.assertEqual("hello2", value_a) async def test_load_set_save(self): # Arrange dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() # Act property_a = user_state.create_property("property-a") property_b = user_state.create_property("property-b") await user_state.load(context) await property_a.set(context, "hello") await property_b.set(context, "world") await user_state.save_changes(context) # Assert obj = dictionary["EmptyContext/users/[email protected]"] self.assertEqual("hello", obj["property-a"]) self.assertEqual("world", obj["property-b"]) async def test_load_set_save_twice(self): # Arrange dictionary = {} context = TestUtilities.create_empty_context() # Act user_state = UserState(MemoryStorage(dictionary)) property_a = user_state.create_property("property-a") property_b = user_state.create_property("property-b") property_c = user_state.create_property("property-c") await user_state.load(context) await property_a.set(context, "hello") await property_b.set(context, "world") await property_c.set(context, "test") await user_state.save_changes(context) # Assert obj = dictionary["EmptyContext/users/[email protected]"] self.assertEqual("hello", obj["property-a"]) self.assertEqual("world", obj["property-b"]) # Act 2 user_state2 = UserState(MemoryStorage(dictionary)) property_a2 = user_state2.create_property("property-a") property_b2 = user_state2.create_property("property-b") await user_state2.load(context) await property_a2.set(context, "hello-2") await property_b2.set(context, "world-2") await user_state2.save_changes(context) # Assert 2 obj2 = dictionary["EmptyContext/users/[email protected]"] self.assertEqual("hello-2", obj2["property-a"]) self.assertEqual("world-2", obj2["property-b"]) self.assertEqual("test", obj2["property-c"]) async def test_load_save_delete(self): # Arrange dictionary = {} context = TestUtilities.create_empty_context() # Act user_state = UserState(MemoryStorage(dictionary)) property_a = user_state.create_property("property-a") property_b = user_state.create_property("property-b") await user_state.load(context) await property_a.set(context, "hello") await property_b.set(context, "world") await user_state.save_changes(context) # Assert obj = dictionary["EmptyContext/users/[email protected]"] self.assertEqual("hello", obj["property-a"]) self.assertEqual("world", obj["property-b"]) # Act 2 user_state2 = UserState(MemoryStorage(dictionary)) property_a2 = user_state2.create_property("property-a") property_b2 = user_state2.create_property("property-b") await user_state2.load(context) await property_a2.set(context, "hello-2") await property_b2.delete(context) await user_state2.save_changes(context) # Assert 2 obj2 = dictionary["EmptyContext/users/[email protected]"] self.assertEqual("hello-2", obj2["property-a"]) with self.assertRaises(KeyError) as _: obj2["property-b"] # pylint: disable=pointless-statement async def test_state_use_bot_state_directly(self): async def exec_test(context: TurnContext): # pylint: disable=unnecessary-lambda bot_state_manager = BotStateForTest(MemoryStorage()) test_property = bot_state_manager.create_property("test") # read initial state object await bot_state_manager.load(context) custom_state = await test_property.get(context, lambda: CustomState()) # this should be a 'CustomState' as nothing is currently stored in storage assert isinstance(custom_state, CustomState) # amend property and write to storage custom_state.custom_string = "test" await bot_state_manager.save_changes(context) custom_state.custom_string = "asdfsadf" # read into context again await bot_state_manager.load(context, True) custom_state = await test_property.get(context) # check object read from value has the correct value for custom_string assert custom_state.custom_string == "test" adapter = TestAdapter(exec_test) await adapter.send("start") async def test_user_state_bad_from_throws(self): dictionary = {} user_state = UserState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() context.activity.from_property = None test_property = user_state.create_property("test") with self.assertRaises(AttributeError): await test_property.get(context) async def test_conversation_state_bad_conversation_throws(self): dictionary = {} user_state = ConversationState(MemoryStorage(dictionary)) context = TestUtilities.create_empty_context() context.activity.conversation = None test_property = user_state.create_property("test") with self.assertRaises(AttributeError): await test_property.get(context) async def test_clear_and_save(self): # pylint: disable=unnecessary-lambda turn_context = TestUtilities.create_empty_context() turn_context.activity.conversation = ConversationAccount(id="1234") storage = MemoryStorage({}) # Turn 0 bot_state1 = ConversationState(storage) ( await bot_state1.create_property("test-name").get( turn_context, lambda: TestPocoState() ) ).value = "test-value" await bot_state1.save_changes(turn_context) # Turn 1 bot_state2 = ConversationState(storage) value1 = ( await bot_state2.create_property("test-name").get( turn_context, lambda: TestPocoState(value="default-value") ) ).value assert value1 == "test-value" # Turn 2 bot_state3 = ConversationState(storage) await bot_state3.clear_state(turn_context) await bot_state3.save_changes(turn_context) # Turn 3 bot_state4 = ConversationState(storage) value2 = ( await bot_state4.create_property("test-name").get( turn_context, lambda: TestPocoState(value="default-value") ) ).value assert value2, "default-value" async def test_bot_state_delete(self): # pylint: disable=unnecessary-lambda turn_context = TestUtilities.create_empty_context() turn_context.activity.conversation = ConversationAccount(id="1234") storage = MemoryStorage({}) # Turn 0 bot_state1 = ConversationState(storage) ( await bot_state1.create_property("test-name").get( turn_context, lambda: TestPocoState() ) ).value = "test-value" await bot_state1.save_changes(turn_context) # Turn 1 bot_state2 = ConversationState(storage) value1 = ( await bot_state2.create_property("test-name").get( turn_context, lambda: TestPocoState(value="default-value") ) ).value assert value1 == "test-value" # Turn 2 bot_state3 = ConversationState(storage) await bot_state3.delete(turn_context) # Turn 3 bot_state4 = ConversationState(storage) value2 = ( await bot_state4.create_property("test-name").get( turn_context, lambda: TestPocoState(value="default-value") ) ).value assert value2 == "default-value" async def test_bot_state_get(self): # pylint: disable=unnecessary-lambda turn_context = TestUtilities.create_empty_context() turn_context.activity.conversation = ConversationAccount(id="1234") storage = MemoryStorage({}) test_bot_state = BotStateForTest(storage) ( await test_bot_state.create_property("test-name").get( turn_context, lambda: TestPocoState() ) ).value = "test-value" result = test_bot_state.get(turn_context) assert result["test-name"].value == "test-value" async def test_bot_state_get_cached_state(self): # pylint: disable=unnecessary-lambda turn_context = TestUtilities.create_empty_context() turn_context.activity.conversation = ConversationAccount(id="1234") storage = MemoryStorage({}) test_bot_state = BotStateForTest(storage) ( await test_bot_state.create_property("test-name").get( turn_context, lambda: TestPocoState() ) ).value = "test-value" result = test_bot_state.get_cached_state(turn_context) assert result is not None assert result == test_bot_state.get_cached_state(turn_context)
botbuilder-python/libraries/botbuilder-core/tests/test_bot_state.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_bot_state.py", "repo_id": "botbuilder-python", "token_count": 7278 }
379
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import aiounittest from botbuilder.core import TurnContext, MemoryStorage, UserState from botbuilder.core.adapters import TestAdapter from botbuilder.schema import Activity, ChannelAccount RECEIVED_MESSAGE = Activity( type="message", text="received", channel_id="test", from_property=ChannelAccount(id="user"), ) MISSING_CHANNEL_ID = Activity( type="message", text="received", from_property=ChannelAccount(id="user") ) MISSING_FROM_PROPERTY = Activity(type="message", text="received", channel_id="test") class TestUserState(aiounittest.AsyncTestCase): storage = MemoryStorage() adapter = TestAdapter() context = TurnContext(adapter, RECEIVED_MESSAGE) user_state = UserState(storage) async def test_should_load_and_save_state_from_storage(self): await self.user_state.load(self.context) key = self.user_state.get_storage_key(self.context) state = self.user_state.get(self.context) assert state is not None, "State not loaded" assert key, "Key not found" state["test"] = "foo" await self.user_state.save_changes(self.context) items = await self.storage.read([key]) assert key in items, "Saved state not found in storage" assert items[key]["test"] == "foo", "Missing saved value in stored storage" async def test_should_reject_with_error_if_channel_id_is_missing(self): context = TurnContext(self.adapter, MISSING_CHANNEL_ID) async def next_middleware(): assert False, "Should not have called next_middleware" try: await self.user_state.on_process_request(context, next_middleware) except AttributeError: pass else: raise AssertionError( "Should not have completed and not raised AttributeError." ) async def test_should_reject_with_error_if_from_property_is_missing(self): context = TurnContext(self.adapter, MISSING_FROM_PROPERTY) async def next_middleware(): assert False, "Should not have called next_middleware" try: await self.user_state.on_process_request(context, next_middleware) except AttributeError: pass else: raise AssertionError( "Should not have completed and not raised AttributeError." )
botbuilder-python/libraries/botbuilder-core/tests/test_user_state.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_user_state.py", "repo_id": "botbuilder-python", "token_count": 964 }
380
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class FoundValue: """Represents a result from matching user input against a list of choices""" def __init__(self, value: str, index: int, score: float): """ Parameters: ---------- value: The value that was matched. index: The index of the value that was matched. score: The accuracy with which the synonym matched the specified portion of the utterance. A value of 1.0 would indicate a perfect match. """ self.value = value self.index = index self.score = score
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_value.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_value.py", "repo_id": "botbuilder-python", "token_count": 227 }
381
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from enum import Enum class DialogReason(Enum): """ Indicates in which a dialog-related method is being called. :var BeginCalled: A dialog is being started through a call to :meth:`DialogContext.begin()`. :vartype BeginCalled: int :var ContinueCalled: A dialog is being continued through a call to :meth:`DialogContext.continue_dialog()`. :vartype ContinueCalled: int :var EndCalled: A dialog ended normally through a call to :meth:`DialogContext.end_dialog() :vartype EndCalled: int :var ReplaceCalled: A dialog is ending and replaced through a call to :meth:``DialogContext.replace_dialog()`. :vartype ReplacedCalled: int :var CancelCalled: A dialog was cancelled as part of a call to :meth:`DialogContext.cancel_all_dialogs()`. :vartype CancelCalled: int :var NextCalled: A preceding step was skipped through a call to :meth:`WaterfallStepContext.next()`. :vartype NextCalled: int """ BeginCalled = 1 ContinueCalled = 2 EndCalled = 3 ReplaceCalled = 4 CancelCalled = 5 NextCalled = 6
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_reason.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_reason.py", "repo_id": "botbuilder-python", "token_count": 394 }
382
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from .alias_path_resolver import AliasPathResolver class AtPathResolver(AliasPathResolver): _DELIMITERS = [".", "["] def __init__(self): super().__init__(alias="@", prefix="") self._PREFIX = "turn.recognized.entities." # pylint: disable=invalid-name def transform_path(self, path: str): if not path: raise TypeError(f"Expecting: path, but received None") path = path.strip() if ( path.startswith("@") and len(path) > 1 and AtPathResolver._is_path_char(path[1]) ): end = any(delimiter in path for delimiter in AtPathResolver._DELIMITERS) if end == -1: end = len(path) prop = path[1:end] suffix = path[end:] path = f"{self._PREFIX}{prop}.first(){suffix}" return path @staticmethod def _index_of_any(string: str, elements_to_search_for) -> int: for element in elements_to_search_for: index = string.find(element) if index != -1: return index return -1
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/path_resolvers/at_path_resolver.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/path_resolvers/at_path_resolver.py", "repo_id": "botbuilder-python", "token_count": 560 }
383
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from botbuilder.core import UserState from botbuilder.dialogs.memory import scope_path from .bot_state_memory_scope import BotStateMemoryScope class UserMemoryScope(BotStateMemoryScope): def __init__(self): super().__init__(UserState, scope_path.USER)
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/user_memory_scope.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/user_memory_scope.py", "repo_id": "botbuilder-python", "token_count": 106 }
384
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from typing import List from botbuilder.schema import Activity from botbuilder.dialogs.choices import Choice, ListStyle class PromptOptions: """ Contains settings to pass to a :class:`Prompt` object when the prompt is started. """ def __init__( self, prompt: Activity = None, retry_prompt: Activity = None, choices: List[Choice] = None, style: ListStyle = None, validations: object = None, number_of_attempts: int = 0, ): """ Sets the initial prompt to send to the user as an :class:`botbuilder.schema.Activity`. :param prompt: The initial prompt to send to the user :type prompt: :class:`botbuilder.schema.Activity` :param retry_prompt: The retry prompt to send to the user :type retry_prompt: :class:`botbuilder.schema.Activity` :param choices: The choices to send to the user :type choices: :class:`List` :param style: The style of the list of choices to send to the user :type style: :class:`ListStyle` :param validations: The prompt validations :type validations: :class:`Object` :param number_of_attempts: The number of attempts allowed :type number_of_attempts: :class:`int` """ self.prompt = prompt self.retry_prompt = retry_prompt self.choices = choices self.style = style self.validations = validations self.number_of_attempts = number_of_attempts
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_options.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_options.py", "repo_id": "botbuilder-python", "token_count": 626 }
385
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import unittest from typing import List from botbuilder.dialogs.choices import Choice from botbuilder.schema import CardAction class ChoiceTest(unittest.TestCase): def test_value_round_trips(self) -> None: choice = Choice() expected = "any" choice.value = expected self.assertIs(expected, choice.value) def test_action_round_trips(self) -> None: choice = Choice() expected = CardAction() choice.action = expected self.assertIs(expected, choice.action) def test_synonyms_round_trips(self) -> None: choice = Choice() expected: List[str] = [] choice.synonyms = expected self.assertIs(expected, choice.synonyms)
botbuilder-python/libraries/botbuilder-dialogs/tests/choices/test_choice.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/choices/test_choice.py", "repo_id": "botbuilder-python", "token_count": 302 }
386
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import aiounittest from botbuilder.dialogs.prompts import OAuthPromptSettings from botbuilder.schema import ( Activity, ActivityTypes, ChannelAccount, ConversationAccount, InputHints, SignInConstants, TokenResponse, ) from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext from botbuilder.core.adapters import TestAdapter from botbuilder.dialogs import DialogSet, DialogTurnStatus, PromptOptions from botbuilder.dialogs.prompts import OAuthPrompt def create_reply(activity): return Activity( type=ActivityTypes.message, from_property=ChannelAccount( id=activity.recipient.id, name=activity.recipient.name ), recipient=ChannelAccount( id=activity.from_property.id, name=activity.from_property.name ), reply_to_id=activity.id, service_url=activity.service_url, channel_id=activity.channel_id, conversation=ConversationAccount( is_group=activity.conversation.is_group, id=activity.conversation.id, name=activity.conversation.name, ), ) class OAuthPromptTests(aiounittest.AsyncTestCase): async def test_should_call_oauth_prompt(self): connection_name = "myConnection" token = "abc123" async def callback_handler(turn_context: TurnContext): dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: await dialog_context.prompt("prompt", PromptOptions()) elif results.status == DialogTurnStatus.Complete: if results.result.token: await turn_context.send_activity("Logged in.") else: await turn_context.send_activity("Failed") await convo_state.save_changes(turn_context) # Initialize TestAdapter. adapter = TestAdapter(callback_handler) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialogState") dialogs = DialogSet(dialog_state) dialogs.add( OAuthPrompt( "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000) ) ) async def inspector( activity: Activity, description: str = None ): # pylint: disable=unused-argument self.assertTrue(len(activity.attachments) == 1) self.assertTrue( activity.attachments[0].content_type == CardFactory.content_types.oauth_card ) # send a mock EventActivity back to the bot with the token adapter.add_user_token( connection_name, activity.channel_id, activity.recipient.id, token ) event_activity = create_reply(activity) event_activity.type = ActivityTypes.event event_activity.from_property, event_activity.recipient = ( event_activity.recipient, event_activity.from_property, ) event_activity.name = "tokens/response" event_activity.value = TokenResponse( connection_name=connection_name, token=token ) context = TurnContext(adapter, event_activity) await callback_handler(context) step1 = await adapter.send("Hello") step2 = await step1.assert_reply(inspector) await step2.assert_reply("Logged in.") async def test_should_call_oauth_prompt_with_code(self): connection_name = "myConnection" token = "abc123" magic_code = "888999" async def exec_test(turn_context: TurnContext): dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: await dialog_context.prompt("prompt", PromptOptions()) elif results.status == DialogTurnStatus.Complete: if results.result.token: await turn_context.send_activity("Logged in.") else: await turn_context.send_activity("Failed") await convo_state.save_changes(turn_context) # Initialize TestAdapter. adapter = TestAdapter(exec_test) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialog_state") dialogs = DialogSet(dialog_state) dialogs.add( OAuthPrompt( "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000) ) ) def inspector( activity: Activity, description: str = None ): # pylint: disable=unused-argument assert len(activity.attachments) == 1 assert ( activity.attachments[0].content_type == CardFactory.content_types.oauth_card ) # send a mock EventActivity back to the bot with the token adapter.add_user_token( connection_name, activity.channel_id, activity.recipient.id, token, magic_code, ) step1 = await adapter.send("Hello") step2 = await step1.assert_reply(inspector) step3 = await step2.send(magic_code) await step3.assert_reply("Logged in.") async def test_oauth_prompt_doesnt_detect_code_in_begin_dialog(self): connection_name = "myConnection" token = "abc123" magic_code = "888999" async def exec_test(turn_context: TurnContext): # Add a magic code to the adapter preemptively so that we can test if the message that triggers # BeginDialogAsync uses magic code detection adapter.add_user_token( connection_name, turn_context.activity.channel_id, turn_context.activity.from_property.id, token, magic_code, ) dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: # If magicCode is detected when prompting, this will end the dialog and return the token in tokenResult token_result = await dialog_context.prompt("prompt", PromptOptions()) if isinstance(token_result.result, TokenResponse): self.assertTrue(False) # pylint: disable=redundant-unittest-assert await convo_state.save_changes(turn_context) # Initialize TestAdapter. adapter = TestAdapter(exec_test) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialog_state") dialogs = DialogSet(dialog_state) dialogs.add( OAuthPrompt( "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000) ) ) def inspector( activity: Activity, description: str = None ): # pylint: disable=unused-argument assert len(activity.attachments) == 1 assert ( activity.attachments[0].content_type == CardFactory.content_types.oauth_card ) step1 = await adapter.send(magic_code) await step1.assert_reply(inspector) async def test_should_add_accepting_input_hint_oauth_prompt(self): connection_name = "myConnection" called = False async def callback_handler(turn_context: TurnContext): nonlocal called dialog_context = await dialogs.create_context(turn_context) await dialog_context.continue_dialog() await dialog_context.prompt( "prompt", PromptOptions(prompt=Activity(), retry_prompt=Activity()) ) self.assertTrue( dialog_context.active_dialog.state["options"].prompt.input_hint == InputHints.accepting_input ) self.assertTrue( dialog_context.active_dialog.state["options"].retry_prompt.input_hint == InputHints.accepting_input ) await convo_state.save_changes(turn_context) called = True # Initialize TestAdapter. adapter = TestAdapter(callback_handler) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialogState") dialogs = DialogSet(dialog_state) dialogs.add( OAuthPrompt( "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000) ) ) await adapter.send("Hello") self.assertTrue(called) async def test_should_end_oauth_prompt_on_invalid_message_when_end_on_invalid_message( self, ): connection_name = "myConnection" token = "abc123" magic_code = "888999" async def exec_test(turn_context: TurnContext): dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: await dialog_context.prompt("prompt", PromptOptions()) elif results.status == DialogTurnStatus.Complete: if results.result and results.result.token: await turn_context.send_activity("Failed") else: await turn_context.send_activity("Ended") await convo_state.save_changes(turn_context) # Initialize TestAdapter. adapter = TestAdapter(exec_test) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialog_state") dialogs = DialogSet(dialog_state) dialogs.add( OAuthPrompt( "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000, None, True), ) ) def inspector( activity: Activity, description: str = None ): # pylint: disable=unused-argument assert len(activity.attachments) == 1 assert ( activity.attachments[0].content_type == CardFactory.content_types.oauth_card ) # send a mock EventActivity back to the bot with the token adapter.add_user_token( connection_name, activity.channel_id, activity.recipient.id, token, magic_code, ) step1 = await adapter.send("Hello") step2 = await step1.assert_reply(inspector) step3 = await step2.send("test invalid message") await step3.assert_reply("Ended") async def test_should_timeout_oauth_prompt_with_message_activity( self, ): activity = Activity(type=ActivityTypes.message, text="any") await self.run_timeout_test(activity) async def test_should_timeout_oauth_prompt_with_token_response_event_activity( self, ): activity = Activity( type=ActivityTypes.event, name=SignInConstants.token_response_event_name ) await self.run_timeout_test(activity) async def test_should_timeout_oauth_prompt_with_verify_state_operation_activity( self, ): activity = Activity( type=ActivityTypes.invoke, name=SignInConstants.verify_state_operation_name ) await self.run_timeout_test(activity) async def test_should_not_timeout_oauth_prompt_with_custom_event_activity( self, ): activity = Activity(type=ActivityTypes.event, name="custom event name") await self.run_timeout_test(activity, False, "Ended", "Failed") async def run_timeout_test( self, activity: Activity, should_succeed: bool = True, token_response: str = "Failed", no_token_resonse="Ended", ): connection_name = "myConnection" token = "abc123" magic_code = "888999" async def exec_test(turn_context: TurnContext): dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: await dialog_context.prompt("prompt", PromptOptions()) elif results.status == DialogTurnStatus.Complete or ( results.status == DialogTurnStatus.Waiting and not should_succeed ): if results.result and results.result.token: await turn_context.send_activity(token_response) else: await turn_context.send_activity(no_token_resonse) await convo_state.save_changes(turn_context) # Initialize TestAdapter. adapter = TestAdapter(exec_test) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialog_state") dialogs = DialogSet(dialog_state) dialogs.add( OAuthPrompt( "prompt", OAuthPromptSettings(connection_name, "Login", None, 1), ) ) def inspector( activity: Activity, description: str = None ): # pylint: disable=unused-argument assert len(activity.attachments) == 1 assert ( activity.attachments[0].content_type == CardFactory.content_types.oauth_card ) # send a mock EventActivity back to the bot with the token adapter.add_user_token( connection_name, activity.channel_id, activity.recipient.id, token, magic_code, ) step1 = await adapter.send("Hello") step2 = await step1.assert_reply(inspector) step3 = await step2.send(activity) await step3.assert_reply(no_token_resonse)
botbuilder-python/libraries/botbuilder-dialogs/tests/test_oauth_prompt.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/test_oauth_prompt.py", "repo_id": "botbuilder-python", "token_count": 6864 }
387
from .aio_http_client_factory import AioHttpClientFactory from .skill_http_client import SkillHttpClient __all__ = ["AioHttpClientFactory", "SkillHttpClient"]
botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/__init__.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/__init__.py", "repo_id": "botbuilder-python", "token_count": 48 }
388
from unittest.mock import Mock from aiounittest import AsyncTestCase import aiohttp # pylint: disable=unused-import from botbuilder.integration.applicationinsights.aiohttp import ( aiohttp_telemetry_middleware, AiohttpTelemetryProcessor, ) class TestAiohttpTelemetryProcessor(AsyncTestCase): # pylint: disable=protected-access def test_can_process(self): assert AiohttpTelemetryProcessor.detect_aiohttp() assert AiohttpTelemetryProcessor().can_process() def test_retrieve_aiohttp_body(self): aiohttp_telemetry_middleware._REQUEST_BODIES = Mock() aiohttp_telemetry_middleware._REQUEST_BODIES.pop = Mock( return_value="test body" ) assert aiohttp_telemetry_middleware.retrieve_aiohttp_body() == "test body" assert AiohttpTelemetryProcessor().get_request_body() == "test body" aiohttp_telemetry_middleware._REQUEST_BODIES = {}
botbuilder-python/libraries/botbuilder-integration-applicationinsights-aiohttp/tests/test_aiohttp_processor.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-integration-applicationinsights-aiohttp/tests/test_aiohttp_processor.py", "repo_id": "botbuilder-python", "token_count": 363 }
389
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import aiounittest from botframework.connector.models import ( MessageActionsPayloadFrom, MessageActionsPayloadBody, MessageActionsPayloadAttachment, MessageActionsPayloadMention, MessageActionsPayloadReaction, ) from botbuilder.schema.teams import MessageActionsPayload class TestingMessageActionsPayload(aiounittest.AsyncTestCase): # Arrange test_id = "01" reply_to_id = "test_reply_to_id" message_type = "test_message_type" created_date_time = "01/01/2000" last_modified_date_time = "01/01/2000" deleted = False subject = "test_subject" summary = "test_summary" importance = "high" locale = "test_locale" link_to_message = "https://teams.microsoft/com/l/message/testing-id" from_property = MessageActionsPayloadFrom() body = MessageActionsPayloadBody attachment_layout = "test_attachment_layout" attachments = [MessageActionsPayloadAttachment()] mentions = [MessageActionsPayloadMention()] reactions = [MessageActionsPayloadReaction()] # Act message = MessageActionsPayload( id=test_id, reply_to_id=reply_to_id, message_type=message_type, created_date_time=created_date_time, last_modified_date_time=last_modified_date_time, deleted=deleted, subject=subject, summary=summary, importance=importance, locale=locale, link_to_message=link_to_message, from_property=from_property, body=body, attachment_layout=attachment_layout, attachments=attachments, mentions=mentions, reactions=reactions, ) def test_assign_id(self, message_action_payload=message, test_id=test_id): # Assert self.assertEqual(message_action_payload.id, test_id) def test_assign_reply_to_id( self, message_action_payload=message, reply_to_id=reply_to_id ): # Assert self.assertEqual(message_action_payload.reply_to_id, reply_to_id) def test_assign_message_type( self, message_action_payload=message, message_type=message_type ): # Assert self.assertEqual(message_action_payload.message_type, message_type) def test_assign_created_date_time( self, message_action_payload=message, created_date_time=created_date_time ): # Assert self.assertEqual(message_action_payload.created_date_time, created_date_time) def test_assign_last_modified_date_time( self, message_action_payload=message, last_modified_date_time=last_modified_date_time, ): # Assert self.assertEqual( message_action_payload.last_modified_date_time, last_modified_date_time ) def test_assign_deleted(self, message_action_payload=message, deleted=deleted): # Assert self.assertEqual(message_action_payload.deleted, deleted) def test_assign_subject(self, message_action_payload=message, subject=subject): # Assert self.assertEqual(message_action_payload.subject, subject) def test_assign_summary(self, message_action_payload=message, summary=summary): # Assert self.assertEqual(message_action_payload.summary, summary) def test_assign_importance( self, message_action_payload=message, importance=importance ): # Assert self.assertEqual(message_action_payload.importance, importance) def test_assign_locale(self, message_action_payload=message, locale=locale): # Assert self.assertEqual(message_action_payload.locale, locale) def test_assign_link_to_message( self, message_action_payload=message, link_to_message=link_to_message ): # Assert self.assertEqual(message_action_payload.link_to_message, link_to_message) def test_assign_from_property( self, message_action_payload=message, from_property=from_property ): # Assert self.assertEqual(message_action_payload.from_property, from_property) def test_assign_body(self, message_action_payload=message, body=body): # Assert self.assertEqual(message_action_payload.body, body) def test_assign_attachment_layout( self, message_action_payload=message, attachment_layout=attachment_layout ): # Assert self.assertEqual(message_action_payload.attachment_layout, attachment_layout) def test_assign_attachments( self, message_action_payload=message, attachments=attachments ): # Assert self.assertEqual(message_action_payload.attachments, attachments) def test_assign_mentions(self, message_action_payload=message, mentions=mentions): # Assert self.assertEqual(message_action_payload.mentions, mentions) def test_assign_reactions( self, message_action_payload=message, reactions=reactions ): # Assert self.assertEqual(message_action_payload.reactions, reactions)
botbuilder-python/libraries/botbuilder-schema/tests/teams/test_message_actions_payload.py/0
{ "file_path": "botbuilder-python/libraries/botbuilder-schema/tests/teams/test_message_actions_payload.py", "repo_id": "botbuilder-python", "token_count": 2051 }
390
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from .http_client_base import HttpClientBase from .http_request import HttpRequest from .http_response_base import HttpResponseBase class _NotImplementedHttpClient(HttpClientBase): async def post( self, *, request: HttpRequest # pylint: disable=unused-argument ) -> HttpResponseBase: raise RuntimeError( "Please provide an http implementation for the skill BotFrameworkClient" )
botbuilder-python/libraries/botframework-connector/botframework/connector/_not_implemented_http_client.py/0
{ "file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/_not_implemented_http_client.py", "repo_id": "botbuilder-python", "token_count": 168 }
391
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from logging import Logger from botbuilder.schema import CallerIdConstants from ..bot_framework_sdk_client_async import BotFrameworkConnectorConfiguration from ..http_client_factory import HttpClientFactory from .service_client_credentials_factory import ServiceClientCredentialsFactory from .authentication_configuration import AuthenticationConfiguration from .authentication_constants import AuthenticationConstants from ._built_in_bot_framework_authentication import _BuiltinBotFrameworkAuthentication class _PublicCloudBotFrameworkAuthentication(_BuiltinBotFrameworkAuthentication): def __init__( self, credentials_factory: ServiceClientCredentialsFactory, auth_configuration: AuthenticationConfiguration, http_client_factory: HttpClientFactory, connector_client_configuration: BotFrameworkConnectorConfiguration = None, logger: Logger = None, ): super(_PublicCloudBotFrameworkAuthentication, self).__init__( AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, AuthenticationConstants.TO_CHANNEL_FROM_BOT_LOGIN_URL_PREFIX, CallerIdConstants.public_azure_channel, "", # channel_service AuthenticationConstants.OAUTH_URL, credentials_factory, auth_configuration, http_client_factory, connector_client_configuration, logger, )
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/_public_cloud_bot_framework_authentication.py/0
{ "file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/_public_cloud_bot_framework_authentication.py", "repo_id": "botbuilder-python", "token_count": 534 }
392
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from abc import ABC from typing import Union from .authentication_configuration import AuthenticationConfiguration from .authentication_constants import AuthenticationConstants from .channel_validation import ChannelValidation from .channel_provider import ChannelProvider from .claims_identity import ClaimsIdentity from .credential_provider import CredentialProvider from .jwt_token_extractor import JwtTokenExtractor from .verify_options import VerifyOptions class EnterpriseChannelValidation(ABC): TO_BOT_FROM_ENTERPRISE_CHANNEL_TOKEN_VALIDATION_PARAMETERS = VerifyOptions( issuer=[AuthenticationConstants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER], audience=None, clock_tolerance=5 * 60, ignore_expiration=False, ) @staticmethod async def authenticate_channel_token( auth_header: str, credentials: CredentialProvider, channel_id: str, channel_service_or_provider: Union[str, ChannelProvider], auth_configuration: AuthenticationConfiguration = None, ) -> ClaimsIdentity: channel_service = channel_service_or_provider if isinstance(channel_service_or_provider, ChannelProvider): channel_service = await channel_service_or_provider.get_channel_service() endpoint = ( ChannelValidation.open_id_metadata_endpoint if ChannelValidation.open_id_metadata_endpoint else AuthenticationConstants.TO_BOT_FROM_ENTERPRISE_CHANNEL_OPEN_ID_METADATA_URL_FORMAT.replace( "{channelService}", channel_service ) ) token_extractor = JwtTokenExtractor( EnterpriseChannelValidation.TO_BOT_FROM_ENTERPRISE_CHANNEL_TOKEN_VALIDATION_PARAMETERS, endpoint, AuthenticationConstants.ALLOWED_SIGNING_ALGORITHMS, ) identity: ClaimsIdentity = await token_extractor.get_identity_from_auth_header( auth_header, channel_id, auth_configuration.required_endorsements ) return await EnterpriseChannelValidation.validate_identity( identity, credentials ) @staticmethod async def authenticate_channel_token_with_service_url( auth_header: str, credentials: CredentialProvider, service_url: str, channel_id: str, channel_service_or_provider: Union[str, ChannelProvider], auth_configuration: AuthenticationConfiguration = None, ) -> ClaimsIdentity: identity: ClaimsIdentity = ( await EnterpriseChannelValidation.authenticate_channel_token( auth_header, credentials, channel_id, channel_service_or_provider, auth_configuration, ) ) service_url_claim: str = identity.get_claim_value( AuthenticationConstants.SERVICE_URL_CLAIM ) if service_url_claim != service_url: raise PermissionError("Unauthorized. service_url claim do not match.") return identity @staticmethod async def validate_identity( identity: ClaimsIdentity, credentials: CredentialProvider ) -> ClaimsIdentity: if identity is None: # No valid identity. Not Authorized. raise PermissionError("Unauthorized. No valid identity.") if not identity.is_authenticated: # The token is in some way invalid. Not Authorized. raise PermissionError("Unauthorized. Is not authenticated.") # Now check that the AppID in the claim set matches # what we're looking for. Note that in a multi-tenant bot, this value # comes from developer code that may be reaching out to a service, hence the # Async validation. # Look for the "aud" claim, but only if issued from the Bot Framework if ( identity.get_claim_value(AuthenticationConstants.ISSUER_CLAIM) != AuthenticationConstants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER ): # The relevant Audience Claim MUST be present. Not Authorized. raise PermissionError("Unauthorized. Issuer claim MUST be present.") # The AppId from the claim in the token must match the AppId specified by the developer. # In this case, the token is destined for the app, so we find the app ID in the audience claim. aud_claim: str = identity.get_claim_value( AuthenticationConstants.AUDIENCE_CLAIM ) if not await credentials.is_valid_appid(aud_claim or ""): # The AppId is not valid or not present. Not Authorized. raise PermissionError( f"Unauthorized. Invalid AppId passed on token: { aud_claim }" ) return identity
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/enterprise_channel_validation.py/0
{ "file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/enterprise_channel_validation.py", "repo_id": "botbuilder-python", "token_count": 1919 }
393