diff --git a/testbed/huggingface__pytorch-image-models/docs/javascripts/tables.js b/testbed/huggingface__pytorch-image-models/docs/javascripts/tables.js new file mode 100644 index 0000000000000000000000000000000000000000..5f21b4d22c7c022fcb6b2fbadcc0148f240798b8 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/javascripts/tables.js @@ -0,0 +1,6 @@ +app.location$.subscribe(function() { + var tables = document.querySelectorAll("article table") + tables.forEach(function(table) { + new Tablesort(table) + }) +}) \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.pages b/testbed/huggingface__pytorch-image-models/docs/models/.pages new file mode 100644 index 0000000000000000000000000000000000000000..c3c88fc4d9fbd3788c1afe04c2615672b00debc9 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.pages @@ -0,0 +1 @@ +title: Model Pages \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/code_snippets.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/code_snippets.md new file mode 100644 index 0000000000000000000000000000000000000000..1dbea838ff31c5077bd900bd62294c6a91e77371 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/code_snippets.md @@ -0,0 +1,62 @@ +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('{{ model_name }}', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `{{ model_name }}`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('{{ model_name }}', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/generate_readmes.py b/testbed/huggingface__pytorch-image-models/docs/models/.templates/generate_readmes.py new file mode 100644 index 0000000000000000000000000000000000000000..0cdefd0d55c445cad235a28679ad9fdee7073bc9 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/generate_readmes.py @@ -0,0 +1,64 @@ +""" +Run this script to generate the model-index files in `models` from the templates in `.templates/models`. +""" + +import argparse +from pathlib import Path + +from jinja2 import Environment, FileSystemLoader + +import modelindex + + +def generate_readmes(templates_path: Path, dest_path: Path): + """Add the code snippet template to the readmes""" + readme_templates_path = templates_path / "models" + code_template_path = templates_path / "code_snippets.md" + + env = Environment( + loader=FileSystemLoader([readme_templates_path, readme_templates_path.parent]), + ) + + for readme in readme_templates_path.iterdir(): + if readme.suffix == ".md": + template = env.get_template(readme.name) + + # get the first model_name for this model family + mi = modelindex.load(str(readme)) + model_name = mi.models[0].name + + full_content = template.render(model_name=model_name) + + # generate full_readme + with open(dest_path / readme.name, "w") as f: + f.write(full_content) + + +def main(): + parser = argparse.ArgumentParser(description="Model index generation config") + parser.add_argument( + "-t", + "--templates", + default=Path(__file__).parent / ".templates", + type=str, + help="Location of the markdown templates", + ) + parser.add_argument( + "-d", + "--dest", + default=Path(__file__).parent / "models", + type=str, + help="Destination folder that contains the generated model-index files.", + ) + args = parser.parse_args() + templates_path = Path(args.templates) + dest_readmes_path = Path(args.dest) + + generate_readmes( + templates_path, + dest_readmes_path, + ) + + +if __name__ == "__main__": + main() diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/adversarial-inception-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/adversarial-inception-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..b4aa03612127a14a0fddf795bb78fa4cdd19c045 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/adversarial-inception-v3.md @@ -0,0 +1,98 @@ +# Adversarial Inception v3 + +**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module). + +This particular model was trained for study of adversarial examples (adversarial training). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1804-00097, + author = {Alexey Kurakin and + Ian J. Goodfellow and + Samy Bengio and + Yinpeng Dong and + Fangzhou Liao and + Ming Liang and + Tianyu Pang and + Jun Zhu and + Xiaolin Hu and + Cihang Xie and + Jianyu Wang and + Zhishuai Zhang and + Zhou Ren and + Alan L. Yuille and + Sangxia Huang and + Yao Zhao and + Yuzhe Zhao and + Zhonglin Han and + Junjiajia Long and + Yerkebulan Berdibekov and + Takuya Akiba and + Seiya Tokui and + Motoki Abe}, + title = {Adversarial Attacks and Defences Competition}, + journal = {CoRR}, + volume = {abs/1804.00097}, + year = {2018}, + url = {http://arxiv.org/abs/1804.00097}, + archivePrefix = {arXiv}, + eprint = {1804.00097}, + timestamp = {Thu, 31 Oct 2019 16:31:22 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1804-00097.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..228faa0c20630eba10e1f6fdc3725d2d4645fa62 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-resnet.md @@ -0,0 +1,76 @@ +# CSP-ResNet + +**CSPResNet** is a convolutional neural network where we apply the Cross Stage Partial Network (CSPNet) approach to [ResNet](https://paperswithcode.com/method/resnet). The CSPNet partitions the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wang2019cspnet, + title={CSPNet: A New Backbone that can Enhance Learning Capability of CNN}, + author={Chien-Yao Wang and Hong-Yuan Mark Liao and I-Hau Yeh and Yueh-Hua Wu and Ping-Yang Chen and Jun-Wei Hsieh}, + year={2019}, + eprint={1911.11929}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..cea88183df8e8d3dc1a32ffdaa40cbed5a047f00 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/csp-resnext.md @@ -0,0 +1,77 @@ +# CSP-ResNeXt + +**CSPResNeXt** is a convolutional neural network where we apply the Cross Stage Partial Network (CSPNet) approach to [ResNeXt](https://paperswithcode.com/method/resnext). The CSPNet partitions the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wang2019cspnet, + title={CSPNet: A New Backbone that can Enhance Learning Capability of CNN}, + author={Chien-Yao Wang and Hong-Yuan Mark Liao and I-Hau Yeh and Yueh-Hua Wu and Ping-Yang Chen and Jun-Wei Hsieh}, + year={2019}, + eprint={1911.11929}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/densenet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/densenet.md new file mode 100644 index 0000000000000000000000000000000000000000..9db9f324070d9664c707682db201e4bfb3d957ba --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/densenet.md @@ -0,0 +1,305 @@ +# DenseNet + +**DenseNet** is a type of convolutional neural network that utilises dense connections between layers, through [Dense Blocks](http://www.paperswithcode.com/method/dense-block), where we connect *all layers* (with matching feature-map sizes) directly with each other. To preserve the feed-forward nature, each layer obtains additional inputs from all preceding layers and passes on its own feature-maps to all subsequent layers. + +The **DenseNet Blur** variant in this collection by Ross Wightman employs [Blur Pooling](http://www.paperswithcode.com/method/blur-pooling) + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/HuangLW16a, + author = {Gao Huang and + Zhuang Liu and + Kilian Q. Weinberger}, + title = {Densely Connected Convolutional Networks}, + journal = {CoRR}, + volume = {abs/1608.06993}, + year = {2016}, + url = {http://arxiv.org/abs/1608.06993}, + archivePrefix = {arXiv}, + eprint = {1608.06993}, + timestamp = {Mon, 10 Sep 2018 15:49:32 +0200}, + biburl = {https://dblp.org/rec/journals/corr/HuangLW16a.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + +``` +@misc{rw2019timm, + author = {Ross Wightman}, + title = {PyTorch Image Models}, + year = {2019}, + publisher = {GitHub}, + journal = {GitHub repository}, + doi = {10.5281/zenodo.4414861}, + howpublished = {\url{https://github.com/rwightman/pytorch-image-models}} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/dla.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/dla.md new file mode 100644 index 0000000000000000000000000000000000000000..7f860a5663ff6d6fc7596bf80761cb21889823c0 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/dla.md @@ -0,0 +1,545 @@ +# Deep Layer Aggregation + +Extending “shallow” skip connections, **Dense Layer Aggregation (DLA)** incorporates more depth and sharing. The authors introduce two structures for deep layer aggregation (DLA): iterative deep aggregation (IDA) and hierarchical deep aggregation (HDA). These structures are expressed through an architectural framework, independent of the choice of backbone, for compatibility with current and future networks. + +IDA focuses on fusing resolutions and scales while HDA focuses on merging features from all modules and channels. IDA follows the base hierarchy to refine resolution and aggregate scale stage-bystage. HDA assembles its own hierarchy of tree-structured connections that cross and merge stages to aggregate different levels of representation. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{yu2019deep, + title={Deep Layer Aggregation}, + author={Fisher Yu and Dequan Wang and Evan Shelhamer and Trevor Darrell}, + year={2019}, + eprint={1707.06484}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ecaresnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ecaresnet.md new file mode 100644 index 0000000000000000000000000000000000000000..126aaaccc314f97fa769b05ae3ae1548f913809d --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ecaresnet.md @@ -0,0 +1,236 @@ +# ECA-ResNet + +An **ECA ResNet** is a variant on a [ResNet](https://paperswithcode.com/method/resnet) that utilises an [Efficient Channel Attention module](https://paperswithcode.com/method/efficient-channel-attention). Efficient Channel Attention is an architectural unit based on [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) that reduces model complexity without dimensionality reduction. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wang2020ecanet, + title={ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks}, + author={Qilong Wang and Banggu Wu and Pengfei Zhu and Peihua Li and Wangmeng Zuo and Qinghua Hu}, + year={2020}, + eprint={1910.03151}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/efficientnet-pruned.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/efficientnet-pruned.md new file mode 100644 index 0000000000000000000000000000000000000000..1742f12777e207695dddb80117e7ba8bb951bde8 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/efficientnet-pruned.md @@ -0,0 +1,145 @@ +# EfficientNet (Knapsack Pruned) + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +This collection consists of pruned EfficientNet models. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2020efficientnet, + title={EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks}, + author={Mingxing Tan and Quoc V. Le}, + year={2020}, + eprint={1905.11946}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + +``` +@misc{aflalo2020knapsack, + title={Knapsack Pruning with Inner Distillation}, + author={Yonathan Aflalo and Asaf Noy and Ming Lin and Itamar Friedman and Lihi Zelnik}, + year={2020}, + eprint={2002.08258}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/efficientnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/efficientnet.md new file mode 100644 index 0000000000000000000000000000000000000000..729df0cacdbe7231deea63006ef2f2e1a31083b6 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/efficientnet.md @@ -0,0 +1,325 @@ +# EfficientNet + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2020efficientnet, + title={EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks}, + author={Mingxing Tan and Quoc V. Le}, + year={2020}, + eprint={1905.11946}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ensemble-adversarial.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ensemble-adversarial.md new file mode 100644 index 0000000000000000000000000000000000000000..e21fe51e9d3a219117a0a2335a07461ca535006d --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ensemble-adversarial.md @@ -0,0 +1,98 @@ +# # Ensemble Adversarial Inception ResNet v2 + +**Inception-ResNet-v2** is a convolutional neural architecture that builds on the Inception family of architectures but incorporates [residual connections](https://paperswithcode.com/method/residual-connection) (replacing the filter concatenation stage of the Inception architecture). + +This particular model was trained for study of adversarial examples (adversarial training). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1804-00097, + author = {Alexey Kurakin and + Ian J. Goodfellow and + Samy Bengio and + Yinpeng Dong and + Fangzhou Liao and + Ming Liang and + Tianyu Pang and + Jun Zhu and + Xiaolin Hu and + Cihang Xie and + Jianyu Wang and + Zhishuai Zhang and + Zhou Ren and + Alan L. Yuille and + Sangxia Huang and + Yao Zhao and + Yuzhe Zhao and + Zhonglin Han and + Junjiajia Long and + Yerkebulan Berdibekov and + Takuya Akiba and + Seiya Tokui and + Motoki Abe}, + title = {Adversarial Attacks and Defences Competition}, + journal = {CoRR}, + volume = {abs/1804.00097}, + year = {2018}, + url = {http://arxiv.org/abs/1804.00097}, + archivePrefix = {arXiv}, + eprint = {1804.00097}, + timestamp = {Thu, 31 Oct 2019 16:31:22 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1804-00097.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ese-vovnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ese-vovnet.md new file mode 100644 index 0000000000000000000000000000000000000000..5f942f00f2d32885dc6afc8ab4cb256790330d35 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ese-vovnet.md @@ -0,0 +1,92 @@ +# ESE-VoVNet + +**VoVNet** is a convolutional neural network that seeks to make [DenseNet](https://paperswithcode.com/method/densenet) more efficient by concatenating all features only once in the last feature map, which makes input size constant and enables enlarging new output channel. + +Read about [one-shot aggregation here](https://paperswithcode.com/method/one-shot-aggregation). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{lee2019energy, + title={An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection}, + author={Youngwan Lee and Joong-won Hwang and Sangrok Lee and Yuseok Bae and Jongyoul Park}, + year={2019}, + eprint={1904.09730}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/fbnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/fbnet.md new file mode 100644 index 0000000000000000000000000000000000000000..0a6de412cba321373d85ee7f53c38b9f92e2c3d7 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/fbnet.md @@ -0,0 +1,76 @@ +# FBNet + +**FBNet** is a type of convolutional neural architectures discovered through [DNAS](https://paperswithcode.com/method/dnas) neural architecture search. It utilises a basic type of image model block inspired by [MobileNetv2](https://paperswithcode.com/method/mobilenetv2) that utilises depthwise convolutions and an inverted residual structure (see components). + +The principal building block is the [FBNet Block](https://paperswithcode.com/method/fbnet-block). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wu2019fbnet, + title={FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural Architecture Search}, + author={Bichen Wu and Xiaoliang Dai and Peizhao Zhang and Yanghan Wang and Fei Sun and Yiming Wu and Yuandong Tian and Peter Vajda and Yangqing Jia and Kurt Keutzer}, + year={2019}, + eprint={1812.03443}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-inception-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-inception-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..90e25b911cfb064682ecfe9ca54af626be6cd2bc --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-inception-v3.md @@ -0,0 +1,78 @@ +# (Gluon) Inception v3 + +**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module). + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/SzegedyVISW15, + author = {Christian Szegedy and + Vincent Vanhoucke and + Sergey Ioffe and + Jonathon Shlens and + Zbigniew Wojna}, + title = {Rethinking the Inception Architecture for Computer Vision}, + journal = {CoRR}, + volume = {abs/1512.00567}, + year = {2015}, + url = {http://arxiv.org/abs/1512.00567}, + archivePrefix = {arXiv}, + eprint = {1512.00567}, + timestamp = {Mon, 13 Aug 2018 16:49:07 +0200}, + biburl = {https://dblp.org/rec/journals/corr/SzegedyVISW15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..a66a658c229444de03259e46459b6cc9c0d7388d --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-resnet.md @@ -0,0 +1,504 @@ +# (Gluon) ResNet + +**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/HeZRS15, + author = {Kaiming He and + Xiangyu Zhang and + Shaoqing Ren and + Jian Sun}, + title = {Deep Residual Learning for Image Recognition}, + journal = {CoRR}, + volume = {abs/1512.03385}, + year = {2015}, + url = {http://arxiv.org/abs/1512.03385}, + archivePrefix = {arXiv}, + eprint = {1512.03385}, + timestamp = {Wed, 17 Apr 2019 17:23:45 +0200}, + biburl = {https://dblp.org/rec/journals/corr/HeZRS15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..b41353f07d92a878ee5c8ce02d873e0cc96fe943 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-resnext.md @@ -0,0 +1,142 @@ +# (Gluon) ResNeXt + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/XieGDTH16, + author = {Saining Xie and + Ross B. Girshick and + Piotr Doll{\'{a}}r and + Zhuowen Tu and + Kaiming He}, + title = {Aggregated Residual Transformations for Deep Neural Networks}, + journal = {CoRR}, + volume = {abs/1611.05431}, + year = {2016}, + url = {http://arxiv.org/abs/1611.05431}, + archivePrefix = {arXiv}, + eprint = {1611.05431}, + timestamp = {Mon, 13 Aug 2018 16:45:58 +0200}, + biburl = {https://dblp.org/rec/journals/corr/XieGDTH16.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-senet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-senet.md new file mode 100644 index 0000000000000000000000000000000000000000..281a782fb9a9f531a8a11caed71f03d21dcadbc4 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-senet.md @@ -0,0 +1,63 @@ +# (Gluon) SENet + +A **SENet** is a convolutional neural network architecture that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-seresnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-seresnext.md new file mode 100644 index 0000000000000000000000000000000000000000..d0f2de01b62384850701a93e7e3ae23426d2d75b --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-seresnext.md @@ -0,0 +1,136 @@ +# (Gluon) SE-ResNeXt + +**SE ResNeXt** is a variant of a [ResNext](https://www.paperswithcode.com/method/resnext) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-xception.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-xception.md new file mode 100644 index 0000000000000000000000000000000000000000..9dfc773aa4a462f63acbe8742bed54a35b6bbc5a --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/gloun-xception.md @@ -0,0 +1,66 @@ +# (Gluon) Xception + +**Xception** is a convolutional neural network architecture that relies solely on [depthwise separable convolution](https://paperswithcode.com/method/depthwise-separable-convolution) layers. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{chollet2017xception, + title={Xception: Deep Learning with Depthwise Separable Convolutions}, + author={François Chollet}, + year={2017}, + eprint={1610.02357}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/hrnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/hrnet.md new file mode 100644 index 0000000000000000000000000000000000000000..ab496f3db3b6277a193d8abe6605642926311296 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/hrnet.md @@ -0,0 +1,358 @@ +# HRNet + +**HRNet**, or **High-Resolution Net**, is a general purpose convolutional neural network for tasks like semantic segmentation, object detection and image classification. It is able to maintain high resolution representations through the whole process. We start from a high-resolution convolution stream, gradually add high-to-low resolution convolution streams one by one, and connect the multi-resolution streams in parallel. The resulting network consists of several ($4$ in the paper) stages and the $n$th stage contains $n$ streams corresponding to $n$ resolutions. The authors conduct repeated multi-resolution fusions by exchanging the information across the parallel streams over and over. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{sun2019highresolution, + title={High-Resolution Representations for Labeling Pixels and Regions}, + author={Ke Sun and Yang Zhao and Borui Jiang and Tianheng Cheng and Bin Xiao and Dong Liu and Yadong Mu and Xinggang Wang and Wenyu Liu and Jingdong Wang}, + year={2019}, + eprint={1904.04514}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ig-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ig-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..6a317b2da76f159507046572a80ebb69dce68c61 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ig-resnext.md @@ -0,0 +1,209 @@ +# Instagram ResNeXt WSL + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +This model was trained on billions of Instagram images using thousands of distinct hashtags as labels exhibit excellent transfer learning performance. + +Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{mahajan2018exploring, + title={Exploring the Limits of Weakly Supervised Pretraining}, + author={Dhruv Mahajan and Ross Girshick and Vignesh Ramanathan and Kaiming He and Manohar Paluri and Yixuan Li and Ashwin Bharambe and Laurens van der Maaten}, + year={2018}, + eprint={1805.00932}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-resnet-v2.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-resnet-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..99e09a1da30ea31f1705741137151d8169dd5636 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-resnet-v2.md @@ -0,0 +1,72 @@ +# Inception ResNet v2 + +**Inception-ResNet-v2** is a convolutional neural architecture that builds on the Inception family of architectures but incorporates [residual connections](https://paperswithcode.com/method/residual-connection) (replacing the filter concatenation stage of the Inception architecture). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{szegedy2016inceptionv4, + title={Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning}, + author={Christian Szegedy and Sergey Ioffe and Vincent Vanhoucke and Alex Alemi}, + year={2016}, + eprint={1602.07261}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..ec8f4c0def9caabb4c9da206a9641dfd734fda9a --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-v3.md @@ -0,0 +1,85 @@ +# Inception v3 + +**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/SzegedyVISW15, + author = {Christian Szegedy and + Vincent Vanhoucke and + Sergey Ioffe and + Jonathon Shlens and + Zbigniew Wojna}, + title = {Rethinking the Inception Architecture for Computer Vision}, + journal = {CoRR}, + volume = {abs/1512.00567}, + year = {2015}, + url = {http://arxiv.org/abs/1512.00567}, + archivePrefix = {arXiv}, + eprint = {1512.00567}, + timestamp = {Mon, 13 Aug 2018 16:49:07 +0200}, + biburl = {https://dblp.org/rec/journals/corr/SzegedyVISW15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-v4.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-v4.md new file mode 100644 index 0000000000000000000000000000000000000000..3427cc85e43f666d9b2cb9b4f45082b1164396be --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/inception-v4.md @@ -0,0 +1,71 @@ +# Inception v4 + +**Inception-v4** is a convolutional neural network architecture that builds on previous iterations of the Inception family by simplifying the architecture and using more inception modules than [Inception-v3](https://paperswithcode.com/method/inception-v3). +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{szegedy2016inceptionv4, + title={Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning}, + author={Christian Szegedy and Sergey Ioffe and Vincent Vanhoucke and Alex Alemi}, + year={2016}, + eprint={1602.07261}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-se-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-se-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..33f0c806c3378376c9cbbd5420408664171e6552 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-se-resnet.md @@ -0,0 +1,257 @@ +# (Legacy) SE-ResNet + +**SE ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-se-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-se-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..fd610b59e8dedef77523993816028284df3d1a13 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-se-resnext.md @@ -0,0 +1,167 @@ +# (Legacy) SE-ResNeXt + +**SE ResNeXt** is a variant of a [ResNeXt](https://www.paperswithcode.com/method/resnext) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-senet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-senet.md new file mode 100644 index 0000000000000000000000000000000000000000..2547999451e7367e76e586f609796ec6a49ef140 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/legacy-senet.md @@ -0,0 +1,74 @@ +# (Legacy) SENet + +A **SENet** is a convolutional neural network architecture that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +The weights from this model were ported from Gluon. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mixnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mixnet.md new file mode 100644 index 0000000000000000000000000000000000000000..f1e04e454d88e50b1685f0e41f59c4b7ccce4ec6 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mixnet.md @@ -0,0 +1,164 @@ +# MixNet + +**MixNet** is a type of convolutional neural network discovered via AutoML that utilises [MixConvs](https://paperswithcode.com/method/mixconv) instead of regular [depthwise convolutions](https://paperswithcode.com/method/depthwise-convolution). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2019mixconv, + title={MixConv: Mixed Depthwise Convolutional Kernels}, + author={Mingxing Tan and Quoc V. Le}, + year={2019}, + eprint={1907.09595}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mnasnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mnasnet.md new file mode 100644 index 0000000000000000000000000000000000000000..e9ad625f938593a019f523dff1c223266b918ea7 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mnasnet.md @@ -0,0 +1,109 @@ +# MnasNet + +**MnasNet** is a type of convolutional neural network optimized for mobile devices that is discovered through mobile neural architecture search, which explicitly incorporates model latency into the main objective so that the search can identify a model that achieves a good trade-off between accuracy and latency. The main building block is an [inverted residual block](https://paperswithcode.com/method/inverted-residual-block) (from [MobileNetV2](https://paperswithcode.com/method/mobilenetv2)). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2019mnasnet, + title={MnasNet: Platform-Aware Neural Architecture Search for Mobile}, + author={Mingxing Tan and Bo Chen and Ruoming Pang and Vijay Vasudevan and Mark Sandler and Andrew Howard and Quoc V. Le}, + year={2019}, + eprint={1807.11626}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mobilenet-v2.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mobilenet-v2.md new file mode 100644 index 0000000000000000000000000000000000000000..ef37f4e7ac6711c297046a1e2d59d05030a4561a --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mobilenet-v2.md @@ -0,0 +1,210 @@ +# MobileNet v2 + +**MobileNetV2** is a convolutional neural network architecture that seeks to perform well on mobile devices. It is based on an [inverted residual structure](https://paperswithcode.com/method/inverted-residual-block) where the residual connections are between the bottleneck layers. The intermediate expansion layer uses lightweight depthwise convolutions to filter features as a source of non-linearity. As a whole, the architecture of MobileNetV2 contains the initial fully convolution layer with 32 filters, followed by 19 residual bottleneck layers. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1801-04381, + author = {Mark Sandler and + Andrew G. Howard and + Menglong Zhu and + Andrey Zhmoginov and + Liang{-}Chieh Chen}, + title = {Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, + Detection and Segmentation}, + journal = {CoRR}, + volume = {abs/1801.04381}, + year = {2018}, + url = {http://arxiv.org/abs/1801.04381}, + archivePrefix = {arXiv}, + eprint = {1801.04381}, + timestamp = {Tue, 12 Jan 2021 15:30:06 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1801-04381.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mobilenet-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mobilenet-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..8cc75b383baf1bc1ae6990a6ecc5510baa9ae461 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/mobilenet-v3.md @@ -0,0 +1,138 @@ +# MobileNet v3 + +**MobileNetV3** is a convolutional neural network that is designed for mobile phone CPUs. The network design includes the use of a [hard swish activation](https://paperswithcode.com/method/hard-swish) and [squeeze-and-excitation](https://paperswithcode.com/method/squeeze-and-excitation-block) modules in the [MBConv blocks](https://paperswithcode.com/method/inverted-residual-block). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-02244, + author = {Andrew Howard and + Mark Sandler and + Grace Chu and + Liang{-}Chieh Chen and + Bo Chen and + Mingxing Tan and + Weijun Wang and + Yukun Zhu and + Ruoming Pang and + Vijay Vasudevan and + Quoc V. Le and + Hartwig Adam}, + title = {Searching for MobileNetV3}, + journal = {CoRR}, + volume = {abs/1905.02244}, + year = {2019}, + url = {http://arxiv.org/abs/1905.02244}, + archivePrefix = {arXiv}, + eprint = {1905.02244}, + timestamp = {Tue, 12 Jan 2021 15:30:06 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-02244.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/nasnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/nasnet.md new file mode 100644 index 0000000000000000000000000000000000000000..5cc7e5b0da1e930d80956b5ab8f962263bb5d73e --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/nasnet.md @@ -0,0 +1,70 @@ +# NASNet + +**NASNet** is a type of convolutional neural network discovered through neural architecture search. The building blocks consist of normal and reduction cells. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{zoph2018learning, + title={Learning Transferable Architectures for Scalable Image Recognition}, + author={Barret Zoph and Vijay Vasudevan and Jonathon Shlens and Quoc V. Le}, + year={2018}, + eprint={1707.07012}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/noisy-student.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/noisy-student.md new file mode 100644 index 0000000000000000000000000000000000000000..6525f6937f1cc4def68077a032e856c8806a6da2 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/noisy-student.md @@ -0,0 +1,510 @@ +# Noisy Student (EfficientNet) + +**Noisy Student Training** is a semi-supervised learning approach. It extends the idea of self-training +and distillation with the use of equal-or-larger student models and noise added to the student during learning. It has three main steps: + +1. train a teacher model on labeled images +2. use the teacher to generate pseudo labels on unlabeled images +3. train a student model on the combination of labeled images and pseudo labeled images. + +The algorithm is iterated a few times by treating the student as a teacher to relabel the unlabeled data and training a new student. + +Noisy Student Training seeks to improve on self-training and distillation in two ways. First, it makes the student larger than, or at least equal to, the teacher so the student can better learn from a larger dataset. Second, it adds noise to the student so the noised student is forced to learn harder from the pseudo labels. To noise the student, it uses input noise such as RandAugment data augmentation, and model noise such as dropout and stochastic depth during training. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{xie2020selftraining, + title={Self-training with Noisy Student improves ImageNet classification}, + author={Qizhe Xie and Minh-Thang Luong and Eduard Hovy and Quoc V. Le}, + year={2020}, + eprint={1911.04252}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/pnasnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/pnasnet.md new file mode 100644 index 0000000000000000000000000000000000000000..49d117ec7dbbf4a1a015397cf5b6b952b6c72e7a --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/pnasnet.md @@ -0,0 +1,71 @@ +# PNASNet + +**Progressive Neural Architecture Search**, or **PNAS**, is a method for learning the structure of convolutional neural networks (CNNs). It uses a sequential model-based optimization (SMBO) strategy, where we search the space of cell structures, starting with simple (shallow) models and progressing to complex ones, pruning out unpromising structures as we go. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{liu2018progressive, + title={Progressive Neural Architecture Search}, + author={Chenxi Liu and Barret Zoph and Maxim Neumann and Jonathon Shlens and Wei Hua and Li-Jia Li and Li Fei-Fei and Alan Yuille and Jonathan Huang and Kevin Murphy}, + year={2018}, + eprint={1712.00559}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/regnetx.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/regnetx.md new file mode 100644 index 0000000000000000000000000000000000000000..90e3a2d68c911bba7dc2d009abb6146c7a4d944d --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/regnetx.md @@ -0,0 +1,492 @@ +# RegNetX + +**RegNetX** is a convolutional network design space with simple, regular models with parameters: depth $d$, initial width $w\_{0} > 0$, and slope $w\_{a} > 0$, and generates a different block width $u\_{j}$ for each block $j < d$. The key restriction for the RegNet types of model is that there is a linear parameterisation of block widths (the design space only contains models with this linear structure): + +$$ u\_{j} = w\_{0} + w\_{a}\cdot{j} $$ + +For **RegNetX** we have additional restrictions: we set $b = 1$ (the bottleneck ratio), $12 \leq d \leq 28$, and $w\_{m} \geq 2$ (the width multiplier). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{radosavovic2020designing, + title={Designing Network Design Spaces}, + author={Ilija Radosavovic and Raj Prateek Kosaraju and Ross Girshick and Kaiming He and Piotr Dollár}, + year={2020}, + eprint={2003.13678}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/regnety.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/regnety.md new file mode 100644 index 0000000000000000000000000000000000000000..2dc9fca91a2d60ba59d4aaaadd6158359f144833 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/regnety.md @@ -0,0 +1,506 @@ +# RegNetY + +**RegNetY** is a convolutional network design space with simple, regular models with parameters: depth $d$, initial width $w\_{0} > 0$, and slope $w\_{a} > 0$, and generates a different block width $u\_{j}$ for each block $j < d$. The key restriction for the RegNet types of model is that there is a linear parameterisation of block widths (the design space only contains models with this linear structure): + +$$ u\_{j} = w\_{0} + w\_{a}\cdot{j} $$ + +For **RegNetX** authors have additional restrictions: we set $b = 1$ (the bottleneck ratio), $12 \leq d \leq 28$, and $w\_{m} \geq 2$ (the width multiplier). + +For **RegNetY** authors make one change, which is to include [Squeeze-and-Excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{radosavovic2020designing, + title={Designing Network Design Spaces}, + author={Ilija Radosavovic and Raj Prateek Kosaraju and Ross Girshick and Kaiming He and Piotr Dollár}, + year={2020}, + eprint={2003.13678}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/res2net.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/res2net.md new file mode 100644 index 0000000000000000000000000000000000000000..ce59015283be1f279264b1ad2cbb7b5edd9e7f5c --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/res2net.md @@ -0,0 +1,260 @@ +# Res2Net + +**Res2Net** is an image model that employs a variation on bottleneck residual blocks, [Res2Net Blocks](https://paperswithcode.com/method/res2net-block). The motivation is to be able to represent features at multiple scales. This is achieved through a novel building block for CNNs that constructs hierarchical residual-like connections within one single residual block. This represents multi-scale features at a granular level and increases the range of receptive fields for each network layer. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{Gao_2021, + title={Res2Net: A New Multi-Scale Backbone Architecture}, + volume={43}, + ISSN={1939-3539}, + url={http://dx.doi.org/10.1109/TPAMI.2019.2938758}, + DOI={10.1109/tpami.2019.2938758}, + number={2}, + journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, + publisher={Institute of Electrical and Electronics Engineers (IEEE)}, + author={Gao, Shang-Hua and Cheng, Ming-Ming and Zhao, Kai and Zhang, Xin-Yu and Yang, Ming-Hsuan and Torr, Philip}, + year={2021}, + month={Feb}, + pages={652–662} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/res2next.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/res2next.md new file mode 100644 index 0000000000000000000000000000000000000000..03ab96e8cd5a76912652d326ea0301f6c449db9c --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/res2next.md @@ -0,0 +1,75 @@ +# Res2NeXt + +**Res2NeXt** is an image model that employs a variation on [ResNeXt](https://paperswithcode.com/method/resnext) bottleneck residual blocks. The motivation is to be able to represent features at multiple scales. This is achieved through a novel building block for CNNs that constructs hierarchical residual-like connections within one single residual block. This represents multi-scale features at a granular level and increases the range of receptive fields for each network layer. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{Gao_2021, + title={Res2Net: A New Multi-Scale Backbone Architecture}, + volume={43}, + ISSN={1939-3539}, + url={http://dx.doi.org/10.1109/TPAMI.2019.2938758}, + DOI={10.1109/tpami.2019.2938758}, + number={2}, + journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, + publisher={Institute of Electrical and Electronics Engineers (IEEE)}, + author={Gao, Shang-Hua and Cheng, Ming-Ming and Zhao, Kai and Zhang, Xin-Yu and Yang, Ming-Hsuan and Torr, Philip}, + year={2021}, + month={Feb}, + pages={652–662} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnest.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnest.md new file mode 100644 index 0000000000000000000000000000000000000000..320aacb86ea1f68b80a4328e39f1025a08430001 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnest.md @@ -0,0 +1,408 @@ +# ResNeSt + +A **ResNeSt** is a variant on a [ResNet](https://paperswithcode.com/method/resnet), which instead stacks [Split-Attention blocks](https://paperswithcode.com/method/split-attention). The cardinal group representations are then concatenated along the channel dimension: $V = \text{Concat}${$V^{1},V^{2},\cdots{V}^{K}$}. As in standard residual blocks, the final output $Y$ of otheur Split-Attention block is produced using a shortcut connection: $Y=V+X$, if the input and output feature-map share the same shape. For blocks with a stride, an appropriate transformation $\mathcal{T}$ is applied to the shortcut connection to align the output shapes: $Y=V+\mathcal{T}(X)$. For example, $\mathcal{T}$ can be strided convolution or combined convolution-with-pooling. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{zhang2020resnest, + title={ResNeSt: Split-Attention Networks}, + author={Hang Zhang and Chongruo Wu and Zhongyue Zhang and Yi Zhu and Haibin Lin and Zhi Zhang and Yue Sun and Tong He and Jonas Mueller and R. Manmatha and Mu Li and Alexander Smola}, + year={2020}, + eprint={2004.08955}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnet-d.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnet-d.md new file mode 100644 index 0000000000000000000000000000000000000000..689f181c6f9005c5c373464f9fea051ccfcf0c99 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnet-d.md @@ -0,0 +1,263 @@ +# ResNet-D + +**ResNet-D** is a modification on the [ResNet](https://paperswithcode.com/method/resnet) architecture that utilises an [average pooling](https://paperswithcode.com/method/average-pooling) tweak for downsampling. The motivation is that in the unmodified ResNet, the [1×1 convolution](https://paperswithcode.com/method/1x1-convolution) for the downsampling block ignores 3/4 of input feature maps, so this is modified so no information will be ignored + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{he2018bag, + title={Bag of Tricks for Image Classification with Convolutional Neural Networks}, + author={Tong He and Zhi Zhang and Hang Zhang and Zhongyue Zhang and Junyuan Xie and Mu Li}, + year={2018}, + eprint={1812.01187}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..58cd0599edd319c9cfc5520762545cf00e679576 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnet.md @@ -0,0 +1,378 @@ +# ResNet + +**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/HeZRS15, + author = {Kaiming He and + Xiangyu Zhang and + Shaoqing Ren and + Jian Sun}, + title = {Deep Residual Learning for Image Recognition}, + journal = {CoRR}, + volume = {abs/1512.03385}, + year = {2015}, + url = {http://arxiv.org/abs/1512.03385}, + archivePrefix = {arXiv}, + eprint = {1512.03385}, + timestamp = {Wed, 17 Apr 2019 17:23:45 +0200}, + biburl = {https://dblp.org/rec/journals/corr/HeZRS15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..e2dcbb863b072066fe159f089f550eb53fec7b98 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/resnext.md @@ -0,0 +1,183 @@ +# ResNeXt + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/XieGDTH16, + author = {Saining Xie and + Ross B. Girshick and + Piotr Doll{\'{a}}r and + Zhuowen Tu and + Kaiming He}, + title = {Aggregated Residual Transformations for Deep Neural Networks}, + journal = {CoRR}, + volume = {abs/1611.05431}, + year = {2016}, + url = {http://arxiv.org/abs/1611.05431}, + archivePrefix = {arXiv}, + eprint = {1611.05431}, + timestamp = {Mon, 13 Aug 2018 16:45:58 +0200}, + biburl = {https://dblp.org/rec/journals/corr/XieGDTH16.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/rexnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/rexnet.md new file mode 100644 index 0000000000000000000000000000000000000000..602f5c493df812279a3de6a5062eb98098bfa4c5 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/rexnet.md @@ -0,0 +1,197 @@ +# RexNet + +**Rank Expansion Networks** (ReXNets) follow a set of new design principles for designing bottlenecks in image classification models. Authors refine each layer by 1) expanding the input channel size of the convolution layer and 2) replacing the [ReLU6s](https://www.paperswithcode.com/method/relu6). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{han2020rexnet, + title={ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network}, + author={Dongyoon Han and Sangdoo Yun and Byeongho Heo and YoungJoon Yoo}, + year={2020}, + eprint={2007.00992}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/se-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/se-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..e1155492026e126522f713681b5910403675662c --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/se-resnet.md @@ -0,0 +1,122 @@ +# SE-ResNet + +**SE ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/selecsls.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/selecsls.md new file mode 100644 index 0000000000000000000000000000000000000000..9a359e6492065f606bf8adcbf7a3c215002f19aa --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/selecsls.md @@ -0,0 +1,136 @@ +# SelecSLS + +**SelecSLS** uses novel selective long and short range skip connections to improve the information flow allowing for a drastically faster network without compromising accuracy. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{Mehta_2020, + title={XNect}, + volume={39}, + ISSN={1557-7368}, + url={http://dx.doi.org/10.1145/3386569.3392410}, + DOI={10.1145/3386569.3392410}, + number={4}, + journal={ACM Transactions on Graphics}, + publisher={Association for Computing Machinery (ACM)}, + author={Mehta, Dushyant and Sotnychenko, Oleksandr and Mueller, Franziska and Xu, Weipeng and Elgharib, Mohamed and Fua, Pascal and Seidel, Hans-Peter and Rhodin, Helge and Pons-Moll, Gerard and Theobalt, Christian}, + year={2020}, + month={Jul} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/seresnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/seresnext.md new file mode 100644 index 0000000000000000000000000000000000000000..41be0451a60d1d0c8f85221083dc07d528c52fec --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/seresnext.md @@ -0,0 +1,167 @@ +# SE-ResNeXt + +**SE ResNeXt** is a variant of a [ResNext](https://www.paperswithcode.com/method/resneXt) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/skresnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/skresnet.md new file mode 100644 index 0000000000000000000000000000000000000000..3df53b033568f6513cc3b120fdde739bdfba3cfd --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/skresnet.md @@ -0,0 +1,112 @@ +# SK-ResNet + +**SK ResNet** is a variant of a [ResNet](https://www.paperswithcode.com/method/resnet) that employs a [Selective Kernel](https://paperswithcode.com/method/selective-kernel) unit. In general, all the large kernel convolutions in the original bottleneck blocks in ResNet are replaced by the proposed [SK convolutions](https://paperswithcode.com/method/selective-kernel-convolution), enabling the network to choose appropriate receptive field sizes in an adaptive manner. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{li2019selective, + title={Selective Kernel Networks}, + author={Xiang Li and Wenhai Wang and Xiaolin Hu and Jian Yang}, + year={2019}, + eprint={1903.06586}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/skresnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/skresnext.md new file mode 100644 index 0000000000000000000000000000000000000000..06e98b06dd5fd16f577ca8fccaa0248a16493b41 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/skresnext.md @@ -0,0 +1,70 @@ +# SK-ResNeXt + +**SK ResNeXt** is a variant of a [ResNeXt](https://www.paperswithcode.com/method/resnext) that employs a [Selective Kernel](https://paperswithcode.com/method/selective-kernel) unit. In general, all the large kernel convolutions in the original bottleneck blocks in ResNext are replaced by the proposed [SK convolutions](https://paperswithcode.com/method/selective-kernel-convolution), enabling the network to choose appropriate receptive field sizes in an adaptive manner. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{li2019selective, + title={Selective Kernel Networks}, + author={Xiang Li and Wenhai Wang and Xiaolin Hu and Jian Yang}, + year={2019}, + eprint={1903.06586}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/spnasnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/spnasnet.md new file mode 100644 index 0000000000000000000000000000000000000000..99cc96126b41f0a837b6128609c7f0ae93bf88bb --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/spnasnet.md @@ -0,0 +1,62 @@ +# SPNASNet + +**Single-Path NAS** is a novel differentiable NAS method for designing hardware-efficient ConvNets in less than 4 hours. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{stamoulis2019singlepath, + title={Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours}, + author={Dimitrios Stamoulis and Ruizhou Ding and Di Wang and Dimitrios Lymberopoulos and Bodhi Priyantha and Jie Liu and Diana Marculescu}, + year={2019}, + eprint={1904.02877}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ssl-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ssl-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..9d4392db8d81fe193ea0fc2aaf7f87a14e739eb9 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ssl-resnet.md @@ -0,0 +1,131 @@ +# SSL ResNet + +**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks. + +The model in this collection utilises semi-supervised learning to improve the performance of the model. The approach brings important gains to standard architectures for image, video and fine-grained classification. + +Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-00546, + author = {I. Zeki Yalniz and + Herv{\'{e}} J{\'{e}}gou and + Kan Chen and + Manohar Paluri and + Dhruv Mahajan}, + title = {Billion-scale semi-supervised learning for image classification}, + journal = {CoRR}, + volume = {abs/1905.00546}, + year = {2019}, + url = {http://arxiv.org/abs/1905.00546}, + archivePrefix = {arXiv}, + eprint = {1905.00546}, + timestamp = {Mon, 28 Sep 2020 08:19:37 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-00546.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ssl-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ssl-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..c540e78a4eefd1bd51f32335c3a7a1ad41198098 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/ssl-resnext.md @@ -0,0 +1,217 @@ +# SSL ResNeXT + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +The model in this collection utilises semi-supervised learning to improve the performance of the model. The approach brings important gains to standard architectures for image, video and fine-grained classification. + +Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-00546, + author = {I. Zeki Yalniz and + Herv{\'{e}} J{\'{e}}gou and + Kan Chen and + Manohar Paluri and + Dhruv Mahajan}, + title = {Billion-scale semi-supervised learning for image classification}, + journal = {CoRR}, + volume = {abs/1905.00546}, + year = {2019}, + url = {http://arxiv.org/abs/1905.00546}, + archivePrefix = {arXiv}, + eprint = {1905.00546}, + timestamp = {Mon, 28 Sep 2020 08:19:37 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-00546.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/swsl-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/swsl-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..6d764226900650ae6f771665ba8db330e1654c42 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/swsl-resnet.md @@ -0,0 +1,131 @@ +# SWSL ResNet + +**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks. + +The models in this collection utilise semi-weakly supervised learning to improve the performance of the model. The approach brings important gains to standard architectures for image, video and fine-grained classification. + +Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-00546, + author = {I. Zeki Yalniz and + Herv{\'{e}} J{\'{e}}gou and + Kan Chen and + Manohar Paluri and + Dhruv Mahajan}, + title = {Billion-scale semi-supervised learning for image classification}, + journal = {CoRR}, + volume = {abs/1905.00546}, + year = {2019}, + url = {http://arxiv.org/abs/1905.00546}, + archivePrefix = {arXiv}, + eprint = {1905.00546}, + timestamp = {Mon, 28 Sep 2020 08:19:37 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-00546.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/swsl-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/swsl-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..cdc59511fe0feb91a22125eaab0325317505a39b --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/swsl-resnext.md @@ -0,0 +1,217 @@ +# SWSL ResNeXt + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +The models in this collection utilise semi-weakly supervised learning to improve the performance of the model. The approach brings important gains to standard architectures for image, video and fine-grained classification. + +Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-00546, + author = {I. Zeki Yalniz and + Herv{\'{e}} J{\'{e}}gou and + Kan Chen and + Manohar Paluri and + Dhruv Mahajan}, + title = {Billion-scale semi-supervised learning for image classification}, + journal = {CoRR}, + volume = {abs/1905.00546}, + year = {2019}, + url = {http://arxiv.org/abs/1905.00546}, + archivePrefix = {arXiv}, + eprint = {1905.00546}, + timestamp = {Mon, 28 Sep 2020 08:19:37 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-00546.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet-condconv.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet-condconv.md new file mode 100644 index 0000000000000000000000000000000000000000..a70cc8fa83ce94b747043b3755fb712257246e3a --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet-condconv.md @@ -0,0 +1,189 @@ +# (Tensorflow) EfficientNet CondConv + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to squeeze-and-excitation blocks. + +This collection of models amends EfficientNet by adding [CondConv](https://paperswithcode.com/method/condconv) convolutions. + +The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1904-04971, + author = {Brandon Yang and + Gabriel Bender and + Quoc V. Le and + Jiquan Ngiam}, + title = {Soft Conditional Computation}, + journal = {CoRR}, + volume = {abs/1904.04971}, + year = {2019}, + url = {http://arxiv.org/abs/1904.04971}, + archivePrefix = {arXiv}, + eprint = {1904.04971}, + timestamp = {Thu, 25 Apr 2019 13:55:01 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1904-04971.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet-lite.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet-lite.md new file mode 100644 index 0000000000000000000000000000000000000000..deb35d94e4f6366c5b1f019a600281caa262b3f2 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet-lite.md @@ -0,0 +1,195 @@ +# (Tensorflow) EfficientNet Lite + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2). + +EfficientNet-Lite makes EfficientNet more suitable for mobile devices by introducing [ReLU6](https://paperswithcode.com/method/relu6) activation functions and removing [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation). + +The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2020efficientnet, + title={EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks}, + author={Mingxing Tan and Quoc V. Le}, + year={2020}, + eprint={1905.11946}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet.md new file mode 100644 index 0000000000000000000000000000000000000000..473dd6839b7d4c9162a090aad4dfc12351e56b5e --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-efficientnet.md @@ -0,0 +1,602 @@ +# (Tensorflow) EfficientNet + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2020efficientnet, + title={EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks}, + author={Mingxing Tan and Quoc V. Le}, + year={2020}, + eprint={1905.11946}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-inception-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-inception-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..9f140b02ef45b706abe9d77d2362427a162eca8e --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-inception-v3.md @@ -0,0 +1,87 @@ +# (Tensorflow) Inception v3 + +**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/SzegedyVISW15, + author = {Christian Szegedy and + Vincent Vanhoucke and + Sergey Ioffe and + Jonathon Shlens and + Zbigniew Wojna}, + title = {Rethinking the Inception Architecture for Computer Vision}, + journal = {CoRR}, + volume = {abs/1512.00567}, + year = {2015}, + url = {http://arxiv.org/abs/1512.00567}, + archivePrefix = {arXiv}, + eprint = {1512.00567}, + timestamp = {Mon, 13 Aug 2018 16:49:07 +0200}, + biburl = {https://dblp.org/rec/journals/corr/SzegedyVISW15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-mixnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-mixnet.md new file mode 100644 index 0000000000000000000000000000000000000000..1cff51101ac880043ff73949d6eae5178ce5796b --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-mixnet.md @@ -0,0 +1,133 @@ +# (Tensorflow) MixNet + +**MixNet** is a type of convolutional neural network discovered via AutoML that utilises [MixConvs](https://paperswithcode.com/method/mixconv) instead of regular [depthwise convolutions](https://paperswithcode.com/method/depthwise-convolution). + +The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2019mixconv, + title={MixConv: Mixed Depthwise Convolutional Kernels}, + author={Mingxing Tan and Quoc V. Le}, + year={2019}, + eprint={1907.09595}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-mobilenet-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-mobilenet-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..5e93db85860a0ee86c500bdbd1844998473478f6 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tf-mobilenet-v3.md @@ -0,0 +1,320 @@ +# (Tensorflow) MobileNet v3 + +**MobileNetV3** is a convolutional neural network that is designed for mobile phone CPUs. The network design includes the use of a [hard swish activation](https://paperswithcode.com/method/hard-swish) and [squeeze-and-excitation](https://paperswithcode.com/method/squeeze-and-excitation-block) modules in the [MBConv blocks](https://paperswithcode.com/method/inverted-residual-block). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-02244, + author = {Andrew Howard and + Mark Sandler and + Grace Chu and + Liang{-}Chieh Chen and + Bo Chen and + Mingxing Tan and + Weijun Wang and + Yukun Zhu and + Ruoming Pang and + Vijay Vasudevan and + Quoc V. Le and + Hartwig Adam}, + title = {Searching for MobileNetV3}, + journal = {CoRR}, + volume = {abs/1905.02244}, + year = {2019}, + url = {http://arxiv.org/abs/1905.02244}, + archivePrefix = {arXiv}, + eprint = {1905.02244}, + timestamp = {Tue, 12 Jan 2021 15:30:06 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-02244.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tresnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tresnet.md new file mode 100644 index 0000000000000000000000000000000000000000..2ecf677bd105609bb3c002108949678fdc02fb58 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/tresnet.md @@ -0,0 +1,291 @@ +# TResNet + +A **TResNet** is a variant on a [ResNet](https://paperswithcode.com/method/resnet) that aim to boost accuracy while maintaining GPU training and inference efficiency. They contain several design tricks including a SpaceToDepth stem, [Anti-Alias downsampling](https://paperswithcode.com/method/anti-alias-downsampling), In-Place Activated BatchNorm, Blocks selection and [squeeze-and-excitation layers](https://paperswithcode.com/method/squeeze-and-excitation-block). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{ridnik2020tresnet, + title={TResNet: High Performance GPU-Dedicated Architecture}, + author={Tal Ridnik and Hussam Lawen and Asaf Noy and Emanuel Ben Baruch and Gilad Sharir and Itamar Friedman}, + year={2020}, + eprint={2003.13630}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/vision-transformer.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/vision-transformer.md new file mode 100644 index 0000000000000000000000000000000000000000..105e985322434e877b91b4a44e8491e4e67c08a1 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/vision-transformer.md @@ -0,0 +1,319 @@ +# Vision Transformer (ViT) + +The **Vision Transformer** is a model for image classification that employs a Transformer-like architecture over patches of the image. This includes the use of [Multi-Head Attention](https://paperswithcode.com/method/multi-head-attention), [Scaled Dot-Product Attention](https://paperswithcode.com/method/scaled) and other architectural features seen in the [Transformer](https://paperswithcode.com/method/transformer) architecture traditionally used for NLP. + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{dosovitskiy2020image, + title={An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale}, + author={Alexey Dosovitskiy and Lucas Beyer and Alexander Kolesnikov and Dirk Weissenborn and Xiaohua Zhai and Thomas Unterthiner and Mostafa Dehghani and Matthias Minderer and Georg Heigold and Sylvain Gelly and Jakob Uszkoreit and Neil Houlsby}, + year={2020}, + eprint={2010.11929}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/wide-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/wide-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..2e4bb89a393177ee7f9f5811ff27bb91224cba70 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/wide-resnet.md @@ -0,0 +1,102 @@ +# Wide ResNet + +**Wide Residual Networks** are a variant on [ResNets](https://paperswithcode.com/method/resnet) where we decrease depth and increase the width of residual networks. This is achieved through the use of [wide residual blocks](https://paperswithcode.com/method/wide-residual-block). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/ZagoruykoK16, + author = {Sergey Zagoruyko and + Nikos Komodakis}, + title = {Wide Residual Networks}, + journal = {CoRR}, + volume = {abs/1605.07146}, + year = {2016}, + url = {http://arxiv.org/abs/1605.07146}, + archivePrefix = {arXiv}, + eprint = {1605.07146}, + timestamp = {Mon, 13 Aug 2018 16:46:42 +0200}, + biburl = {https://dblp.org/rec/journals/corr/ZagoruykoK16.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/xception.md b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/xception.md new file mode 100644 index 0000000000000000000000000000000000000000..ee5216e8288fc0c5cf05c13647fb3176d5570c4b --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/.templates/models/xception.md @@ -0,0 +1,163 @@ +# Xception + +**Xception** is a convolutional neural network architecture that relies solely on [depthwise separable convolution layers](https://paperswithcode.com/method/depthwise-separable-convolution). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +{% include 'code_snippets.md' %} + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/ZagoruykoK16, +@misc{chollet2017xception, + title={Xception: Deep Learning with Depthwise Separable Convolutions}, + author={François Chollet}, + year={2017}, + eprint={1610.02357}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + diff --git a/testbed/huggingface__pytorch-image-models/docs/models/adversarial-inception-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/adversarial-inception-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..2ee4014408fe8f79467b86a1a5ea3772aa67dfe7 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/adversarial-inception-v3.md @@ -0,0 +1,159 @@ +# Adversarial Inception v3 + +**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module). + +This particular model was trained for study of adversarial examples (adversarial training). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('adv_inception_v3', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `adv_inception_v3`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('adv_inception_v3', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1804-00097, + author = {Alexey Kurakin and + Ian J. Goodfellow and + Samy Bengio and + Yinpeng Dong and + Fangzhou Liao and + Ming Liang and + Tianyu Pang and + Jun Zhu and + Xiaolin Hu and + Cihang Xie and + Jianyu Wang and + Zhishuai Zhang and + Zhou Ren and + Alan L. Yuille and + Sangxia Huang and + Yao Zhao and + Yuzhe Zhao and + Zhonglin Han and + Junjiajia Long and + Yerkebulan Berdibekov and + Takuya Akiba and + Seiya Tokui and + Motoki Abe}, + title = {Adversarial Attacks and Defences Competition}, + journal = {CoRR}, + volume = {abs/1804.00097}, + year = {2018}, + url = {http://arxiv.org/abs/1804.00097}, + archivePrefix = {arXiv}, + eprint = {1804.00097}, + timestamp = {Thu, 31 Oct 2019 16:31:22 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1804-00097.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/advprop.md b/testbed/huggingface__pytorch-image-models/docs/models/advprop.md new file mode 100644 index 0000000000000000000000000000000000000000..42ffbf87a269eb09cdd589cb78831da5365abdb6 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/advprop.md @@ -0,0 +1,518 @@ +# AdvProp (EfficientNet) + +**AdvProp** is an adversarial training scheme which treats adversarial examples as additional examples, to prevent overfitting. Key to the method is the usage of a separate auxiliary batch norm for adversarial examples, as they have different underlying distributions to normal examples. + +The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('tf_efficientnet_b0_ap', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `tf_efficientnet_b0_ap`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('tf_efficientnet_b0_ap', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{xie2020adversarial, + title={Adversarial Examples Improve Image Recognition}, + author={Cihang Xie and Mingxing Tan and Boqing Gong and Jiang Wang and Alan Yuille and Quoc V. Le}, + year={2020}, + eprint={1911.09665}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/big-transfer.md b/testbed/huggingface__pytorch-image-models/docs/models/big-transfer.md new file mode 100644 index 0000000000000000000000000000000000000000..3663ff5aa9bc508381018a4ddd764cdbd2228e63 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/big-transfer.md @@ -0,0 +1,356 @@ +# Big Transfer (BiT) + +**Big Transfer (BiT)** is a type of pretraining recipe that pre-trains on a large supervised source dataset, and fine-tunes the weights on the target task. Models are trained on the JFT-300M dataset. The finetuned models contained in this collection are finetuned on ImageNet. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('resnetv2_101x1_bitm', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `resnetv2_101x1_bitm`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('resnetv2_101x1_bitm', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{kolesnikov2020big, + title={Big Transfer (BiT): General Visual Representation Learning}, + author={Alexander Kolesnikov and Lucas Beyer and Xiaohua Zhai and Joan Puigcerver and Jessica Yung and Sylvain Gelly and Neil Houlsby}, + year={2020}, + eprint={1912.11370}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/csp-darknet.md b/testbed/huggingface__pytorch-image-models/docs/models/csp-darknet.md new file mode 100644 index 0000000000000000000000000000000000000000..7a0a1bd0524860c95646bebd8b17d6c3f784d477 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/csp-darknet.md @@ -0,0 +1,142 @@ +# CSP-DarkNet + +**CSPDarknet53** is a convolutional neural network and backbone for object detection that uses [DarkNet-53](https://paperswithcode.com/method/darknet-53). It employs a CSPNet strategy to partition the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network. + +This CNN is used as the backbone for [YOLOv4](https://paperswithcode.com/method/yolov4). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('cspdarknet53', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `cspdarknet53`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('cspdarknet53', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{bochkovskiy2020yolov4, + title={YOLOv4: Optimal Speed and Accuracy of Object Detection}, + author={Alexey Bochkovskiy and Chien-Yao Wang and Hong-Yuan Mark Liao}, + year={2020}, + eprint={2004.10934}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/csp-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/csp-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..707f20eb3baa2f0d60b7ddb2c2d2a1c8bdd1ab5d --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/csp-resnet.md @@ -0,0 +1,137 @@ +# CSP-ResNet + +**CSPResNet** is a convolutional neural network where we apply the Cross Stage Partial Network (CSPNet) approach to [ResNet](https://paperswithcode.com/method/resnet). The CSPNet partitions the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('cspresnet50', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `cspresnet50`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('cspresnet50', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wang2019cspnet, + title={CSPNet: A New Backbone that can Enhance Learning Capability of CNN}, + author={Chien-Yao Wang and Hong-Yuan Mark Liao and I-Hau Yeh and Yueh-Hua Wu and Ping-Yang Chen and Jun-Wei Hsieh}, + year={2019}, + eprint={1911.11929}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/csp-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/csp-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..ff35f0eee23056aee684eb4d8a47aa43dde70177 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/csp-resnext.md @@ -0,0 +1,138 @@ +# CSP-ResNeXt + +**CSPResNeXt** is a convolutional neural network where we apply the Cross Stage Partial Network (CSPNet) approach to [ResNeXt](https://paperswithcode.com/method/resnext). The CSPNet partitions the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('cspresnext50', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `cspresnext50`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('cspresnext50', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wang2019cspnet, + title={CSPNet: A New Backbone that can Enhance Learning Capability of CNN}, + author={Chien-Yao Wang and Hong-Yuan Mark Liao and I-Hau Yeh and Yueh-Hua Wu and Ping-Yang Chen and Jun-Wei Hsieh}, + year={2019}, + eprint={1911.11929}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/densenet.md b/testbed/huggingface__pytorch-image-models/docs/models/densenet.md new file mode 100644 index 0000000000000000000000000000000000000000..2ed86503d63749cc36600a33e174b10143511c30 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/densenet.md @@ -0,0 +1,366 @@ +# DenseNet + +**DenseNet** is a type of convolutional neural network that utilises dense connections between layers, through [Dense Blocks](http://www.paperswithcode.com/method/dense-block), where we connect *all layers* (with matching feature-map sizes) directly with each other. To preserve the feed-forward nature, each layer obtains additional inputs from all preceding layers and passes on its own feature-maps to all subsequent layers. + +The **DenseNet Blur** variant in this collection by Ross Wightman employs [Blur Pooling](http://www.paperswithcode.com/method/blur-pooling) + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('densenet121', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `densenet121`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('densenet121', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/HuangLW16a, + author = {Gao Huang and + Zhuang Liu and + Kilian Q. Weinberger}, + title = {Densely Connected Convolutional Networks}, + journal = {CoRR}, + volume = {abs/1608.06993}, + year = {2016}, + url = {http://arxiv.org/abs/1608.06993}, + archivePrefix = {arXiv}, + eprint = {1608.06993}, + timestamp = {Mon, 10 Sep 2018 15:49:32 +0200}, + biburl = {https://dblp.org/rec/journals/corr/HuangLW16a.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + +``` +@misc{rw2019timm, + author = {Ross Wightman}, + title = {PyTorch Image Models}, + year = {2019}, + publisher = {GitHub}, + journal = {GitHub repository}, + doi = {10.5281/zenodo.4414861}, + howpublished = {\url{https://github.com/rwightman/pytorch-image-models}} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/dla.md b/testbed/huggingface__pytorch-image-models/docs/models/dla.md new file mode 100644 index 0000000000000000000000000000000000000000..d4d7626e5a7ac2ca523e79d3ebf8bfd1a57ebb08 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/dla.md @@ -0,0 +1,606 @@ +# Deep Layer Aggregation + +Extending “shallow” skip connections, **Dense Layer Aggregation (DLA)** incorporates more depth and sharing. The authors introduce two structures for deep layer aggregation (DLA): iterative deep aggregation (IDA) and hierarchical deep aggregation (HDA). These structures are expressed through an architectural framework, independent of the choice of backbone, for compatibility with current and future networks. + +IDA focuses on fusing resolutions and scales while HDA focuses on merging features from all modules and channels. IDA follows the base hierarchy to refine resolution and aggregate scale stage-bystage. HDA assembles its own hierarchy of tree-structured connections that cross and merge stages to aggregate different levels of representation. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('dla102', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `dla102`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('dla102', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{yu2019deep, + title={Deep Layer Aggregation}, + author={Fisher Yu and Dequan Wang and Evan Shelhamer and Trevor Darrell}, + year={2019}, + eprint={1707.06484}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/dpn.md b/testbed/huggingface__pytorch-image-models/docs/models/dpn.md new file mode 100644 index 0000000000000000000000000000000000000000..b18ce9b82dca602a9470190f8740dbc0b8ad99ba --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/dpn.md @@ -0,0 +1,317 @@ +# Dual Path Network (DPN) + +A **Dual Path Network (DPN)** is a convolutional neural network which presents a new topology of connection paths internally. The intuition is that [ResNets](https://paperswithcode.com/method/resnet) enables feature re-usage while DenseNet enables new feature exploration, and both are important for learning good representations. To enjoy the benefits from both path topologies, Dual Path Networks share common features while maintaining the flexibility to explore new features through dual path architectures. + +The principal building block is an [DPN Block](https://paperswithcode.com/method/dpn-block). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('dpn107', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `dpn107`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('dpn107', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{chen2017dual, + title={Dual Path Networks}, + author={Yunpeng Chen and Jianan Li and Huaxin Xiao and Xiaojie Jin and Shuicheng Yan and Jiashi Feng}, + year={2017}, + eprint={1707.01629}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/ecaresnet.md b/testbed/huggingface__pytorch-image-models/docs/models/ecaresnet.md new file mode 100644 index 0000000000000000000000000000000000000000..fe76b6dd51fa486bfd65401644f36a71c9cc2fed --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/ecaresnet.md @@ -0,0 +1,297 @@ +# ECA-ResNet + +An **ECA ResNet** is a variant on a [ResNet](https://paperswithcode.com/method/resnet) that utilises an [Efficient Channel Attention module](https://paperswithcode.com/method/efficient-channel-attention). Efficient Channel Attention is an architectural unit based on [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) that reduces model complexity without dimensionality reduction. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('ecaresnet101d', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `ecaresnet101d`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('ecaresnet101d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wang2020ecanet, + title={ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks}, + author={Qilong Wang and Banggu Wu and Pengfei Zhu and Peihua Li and Wangmeng Zuo and Qinghua Hu}, + year={2020}, + eprint={1910.03151}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/efficientnet-pruned.md b/testbed/huggingface__pytorch-image-models/docs/models/efficientnet-pruned.md new file mode 100644 index 0000000000000000000000000000000000000000..8dd88272400fa83f5baaba7536137e941bddd5bf --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/efficientnet-pruned.md @@ -0,0 +1,206 @@ +# EfficientNet (Knapsack Pruned) + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +This collection consists of pruned EfficientNet models. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('efficientnet_b1_pruned', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `efficientnet_b1_pruned`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('efficientnet_b1_pruned', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2020efficientnet, + title={EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks}, + author={Mingxing Tan and Quoc V. Le}, + year={2020}, + eprint={1905.11946}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + +``` +@misc{aflalo2020knapsack, + title={Knapsack Pruning with Inner Distillation}, + author={Yonathan Aflalo and Asaf Noy and Ming Lin and Itamar Friedman and Lihi Zelnik}, + year={2020}, + eprint={2002.08258}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/efficientnet.md b/testbed/huggingface__pytorch-image-models/docs/models/efficientnet.md new file mode 100644 index 0000000000000000000000000000000000000000..d04d86ab1dbb0625bc35de5598d07fd85a542ee4 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/efficientnet.md @@ -0,0 +1,386 @@ +# EfficientNet + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('efficientnet_b0', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `efficientnet_b0`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('efficientnet_b0', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2020efficientnet, + title={EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks}, + author={Mingxing Tan and Quoc V. Le}, + year={2020}, + eprint={1905.11946}, + archivePrefix={arXiv}, + primaryClass={cs.LG} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/ensemble-adversarial.md b/testbed/huggingface__pytorch-image-models/docs/models/ensemble-adversarial.md new file mode 100644 index 0000000000000000000000000000000000000000..bc33b7f0185b5c2d0223091007a2d667dd2d1e28 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/ensemble-adversarial.md @@ -0,0 +1,159 @@ +# # Ensemble Adversarial Inception ResNet v2 + +**Inception-ResNet-v2** is a convolutional neural architecture that builds on the Inception family of architectures but incorporates [residual connections](https://paperswithcode.com/method/residual-connection) (replacing the filter concatenation stage of the Inception architecture). + +This particular model was trained for study of adversarial examples (adversarial training). + +The weights from this model were ported from [Tensorflow/Models](https://github.com/tensorflow/models). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('ens_adv_inception_resnet_v2', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `ens_adv_inception_resnet_v2`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('ens_adv_inception_resnet_v2', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1804-00097, + author = {Alexey Kurakin and + Ian J. Goodfellow and + Samy Bengio and + Yinpeng Dong and + Fangzhou Liao and + Ming Liang and + Tianyu Pang and + Jun Zhu and + Xiaolin Hu and + Cihang Xie and + Jianyu Wang and + Zhishuai Zhang and + Zhou Ren and + Alan L. Yuille and + Sangxia Huang and + Yao Zhao and + Yuzhe Zhao and + Zhonglin Han and + Junjiajia Long and + Yerkebulan Berdibekov and + Takuya Akiba and + Seiya Tokui and + Motoki Abe}, + title = {Adversarial Attacks and Defences Competition}, + journal = {CoRR}, + volume = {abs/1804.00097}, + year = {2018}, + url = {http://arxiv.org/abs/1804.00097}, + archivePrefix = {arXiv}, + eprint = {1804.00097}, + timestamp = {Thu, 31 Oct 2019 16:31:22 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1804-00097.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/ese-vovnet.md b/testbed/huggingface__pytorch-image-models/docs/models/ese-vovnet.md new file mode 100644 index 0000000000000000000000000000000000000000..ca02b0a47db0b4c9043a1f8811a3cda8b9b082b9 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/ese-vovnet.md @@ -0,0 +1,153 @@ +# ESE-VoVNet + +**VoVNet** is a convolutional neural network that seeks to make [DenseNet](https://paperswithcode.com/method/densenet) more efficient by concatenating all features only once in the last feature map, which makes input size constant and enables enlarging new output channel. + +Read about [one-shot aggregation here](https://paperswithcode.com/method/one-shot-aggregation). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('ese_vovnet19b_dw', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `ese_vovnet19b_dw`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('ese_vovnet19b_dw', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{lee2019energy, + title={An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection}, + author={Youngwan Lee and Joong-won Hwang and Sangrok Lee and Yuseok Bae and Jongyoul Park}, + year={2019}, + eprint={1904.09730}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/fbnet.md b/testbed/huggingface__pytorch-image-models/docs/models/fbnet.md new file mode 100644 index 0000000000000000000000000000000000000000..7c5de5a652eac8d20ca0d2263c14a870c16f1e8f --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/fbnet.md @@ -0,0 +1,137 @@ +# FBNet + +**FBNet** is a type of convolutional neural architectures discovered through [DNAS](https://paperswithcode.com/method/dnas) neural architecture search. It utilises a basic type of image model block inspired by [MobileNetv2](https://paperswithcode.com/method/mobilenetv2) that utilises depthwise convolutions and an inverted residual structure (see components). + +The principal building block is the [FBNet Block](https://paperswithcode.com/method/fbnet-block). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('fbnetc_100', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `fbnetc_100`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('fbnetc_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{wu2019fbnet, + title={FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural Architecture Search}, + author={Bichen Wu and Xiaoliang Dai and Peizhao Zhang and Yanghan Wang and Fei Sun and Yiming Wu and Yuandong Tian and Peter Vajda and Yangqing Jia and Kurt Keutzer}, + year={2019}, + eprint={1812.03443}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/gloun-inception-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/gloun-inception-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..3f1988f349ecd33a5a4ea48f6cdfa728dd269f23 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/gloun-inception-v3.md @@ -0,0 +1,139 @@ +# (Gluon) Inception v3 + +**Inception v3** is a convolutional neural network architecture from the Inception family that makes several improvements including using [Label Smoothing](https://paperswithcode.com/method/label-smoothing), Factorized 7 x 7 convolutions, and the use of an [auxiliary classifer](https://paperswithcode.com/method/auxiliary-classifier) to propagate label information lower down the network (along with the use of batch normalization for layers in the sidehead). The key building block is an [Inception Module](https://paperswithcode.com/method/inception-v3-module). + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('gluon_inception_v3', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `gluon_inception_v3`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('gluon_inception_v3', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/SzegedyVISW15, + author = {Christian Szegedy and + Vincent Vanhoucke and + Sergey Ioffe and + Jonathon Shlens and + Zbigniew Wojna}, + title = {Rethinking the Inception Architecture for Computer Vision}, + journal = {CoRR}, + volume = {abs/1512.00567}, + year = {2015}, + url = {http://arxiv.org/abs/1512.00567}, + archivePrefix = {arXiv}, + eprint = {1512.00567}, + timestamp = {Mon, 13 Aug 2018 16:49:07 +0200}, + biburl = {https://dblp.org/rec/journals/corr/SzegedyVISW15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/gloun-resnet.md b/testbed/huggingface__pytorch-image-models/docs/models/gloun-resnet.md new file mode 100644 index 0000000000000000000000000000000000000000..e1bfad3120635921afa75b77dd0615b4c2ebcdc3 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/gloun-resnet.md @@ -0,0 +1,565 @@ +# (Gluon) ResNet + +**Residual Networks**, or **ResNets**, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack [residual blocks](https://paperswithcode.com/method/residual-block) ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('gluon_resnet101_v1b', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `gluon_resnet101_v1b`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('gluon_resnet101_v1b', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/HeZRS15, + author = {Kaiming He and + Xiangyu Zhang and + Shaoqing Ren and + Jian Sun}, + title = {Deep Residual Learning for Image Recognition}, + journal = {CoRR}, + volume = {abs/1512.03385}, + year = {2015}, + url = {http://arxiv.org/abs/1512.03385}, + archivePrefix = {arXiv}, + eprint = {1512.03385}, + timestamp = {Wed, 17 Apr 2019 17:23:45 +0200}, + biburl = {https://dblp.org/rec/journals/corr/HeZRS15.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/gloun-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/gloun-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..c446510b0cb1bd2cbd88e3f22b7109d19ba14709 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/gloun-resnext.md @@ -0,0 +1,203 @@ +# (Gluon) ResNeXt + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('gluon_resnext101_32x4d', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `gluon_resnext101_32x4d`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('gluon_resnext101_32x4d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/XieGDTH16, + author = {Saining Xie and + Ross B. Girshick and + Piotr Doll{\'{a}}r and + Zhuowen Tu and + Kaiming He}, + title = {Aggregated Residual Transformations for Deep Neural Networks}, + journal = {CoRR}, + volume = {abs/1611.05431}, + year = {2016}, + url = {http://arxiv.org/abs/1611.05431}, + archivePrefix = {arXiv}, + eprint = {1611.05431}, + timestamp = {Mon, 13 Aug 2018 16:45:58 +0200}, + biburl = {https://dblp.org/rec/journals/corr/XieGDTH16.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/gloun-xception.md b/testbed/huggingface__pytorch-image-models/docs/models/gloun-xception.md new file mode 100644 index 0000000000000000000000000000000000000000..ae1e46481531c0d5e133d70bebf3c0929c2ef23e --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/gloun-xception.md @@ -0,0 +1,127 @@ +# (Gluon) Xception + +**Xception** is a convolutional neural network architecture that relies solely on [depthwise separable convolution](https://paperswithcode.com/method/depthwise-separable-convolution) layers. + +The weights from this model were ported from [Gluon](https://cv.gluon.ai/model_zoo/classification.html). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('gluon_xception65', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `gluon_xception65`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('gluon_xception65', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{chollet2017xception, + title={Xception: Deep Learning with Depthwise Separable Convolutions}, + author={François Chollet}, + year={2017}, + eprint={1610.02357}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/hrnet.md b/testbed/huggingface__pytorch-image-models/docs/models/hrnet.md new file mode 100644 index 0000000000000000000000000000000000000000..5ef6499e1040fbf1c7fc15ab5c8b6d5ad1d89230 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/hrnet.md @@ -0,0 +1,419 @@ +# HRNet + +**HRNet**, or **High-Resolution Net**, is a general purpose convolutional neural network for tasks like semantic segmentation, object detection and image classification. It is able to maintain high resolution representations through the whole process. We start from a high-resolution convolution stream, gradually add high-to-low resolution convolution streams one by one, and connect the multi-resolution streams in parallel. The resulting network consists of several ($4$ in the paper) stages and the $n$th stage contains $n$ streams corresponding to $n$ resolutions. The authors conduct repeated multi-resolution fusions by exchanging the information across the parallel streams over and over. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('hrnet_w18', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `hrnet_w18`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('hrnet_w18', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{sun2019highresolution, + title={High-Resolution Representations for Labeling Pixels and Regions}, + author={Ke Sun and Yang Zhao and Borui Jiang and Tianheng Cheng and Bin Xiao and Dong Liu and Yadong Mu and Xinggang Wang and Wenyu Liu and Jingdong Wang}, + year={2019}, + eprint={1904.04514}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/ig-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/ig-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..6461b4eb5d8e2eea62491fac08c7cbe52ece9b63 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/ig-resnext.md @@ -0,0 +1,270 @@ +# Instagram ResNeXt WSL + +A **ResNeXt** repeats a [building block](https://paperswithcode.com/method/resnext-block) that aggregates a set of transformations with the same topology. Compared to a [ResNet](https://paperswithcode.com/method/resnet), it exposes a new dimension, *cardinality* (the size of the set of transformations) $C$, as an essential factor in addition to the dimensions of depth and width. + +This model was trained on billions of Instagram images using thousands of distinct hashtags as labels exhibit excellent transfer learning performance. + +Please note the CC-BY-NC 4.0 license on theses weights, non-commercial use only. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('ig_resnext101_32x16d', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `ig_resnext101_32x16d`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('ig_resnext101_32x16d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{mahajan2018exploring, + title={Exploring the Limits of Weakly Supervised Pretraining}, + author={Dhruv Mahajan and Ross Girshick and Vignesh Ramanathan and Kaiming He and Manohar Paluri and Yixuan Li and Ashwin Bharambe and Laurens van der Maaten}, + year={2018}, + eprint={1805.00932}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/inception-v4.md b/testbed/huggingface__pytorch-image-models/docs/models/inception-v4.md new file mode 100644 index 0000000000000000000000000000000000000000..5d752b74565f1cdf4a821cbc9bf745e40570a05e --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/inception-v4.md @@ -0,0 +1,132 @@ +# Inception v4 + +**Inception-v4** is a convolutional neural network architecture that builds on previous iterations of the Inception family by simplifying the architecture and using more inception modules than [Inception-v3](https://paperswithcode.com/method/inception-v3). +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('inception_v4', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `inception_v4`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('inception_v4', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{szegedy2016inceptionv4, + title={Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning}, + author={Christian Szegedy and Sergey Ioffe and Vincent Vanhoucke and Alex Alemi}, + year={2016}, + eprint={1602.07261}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/legacy-se-resnext.md b/testbed/huggingface__pytorch-image-models/docs/models/legacy-se-resnext.md new file mode 100644 index 0000000000000000000000000000000000000000..d9524aab9d8a303c09a1f0e2689281dc5ebe5db4 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/legacy-se-resnext.md @@ -0,0 +1,228 @@ +# (Legacy) SE-ResNeXt + +**SE ResNeXt** is a variant of a [ResNeXt](https://www.paperswithcode.com/method/resnext) that employs [squeeze-and-excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block) to enable the network to perform dynamic channel-wise feature recalibration. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('legacy_seresnext101_32x4d', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `legacy_seresnext101_32x4d`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('legacy_seresnext101_32x4d', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{hu2019squeezeandexcitation, + title={Squeeze-and-Excitation Networks}, + author={Jie Hu and Li Shen and Samuel Albanie and Gang Sun and Enhua Wu}, + year={2019}, + eprint={1709.01507}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/mixnet.md b/testbed/huggingface__pytorch-image-models/docs/models/mixnet.md new file mode 100644 index 0000000000000000000000000000000000000000..a283de8a235536cfda230be5647542b1a8b76c1c --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/mixnet.md @@ -0,0 +1,225 @@ +# MixNet + +**MixNet** is a type of convolutional neural network discovered via AutoML that utilises [MixConvs](https://paperswithcode.com/method/mixconv) instead of regular [depthwise convolutions](https://paperswithcode.com/method/depthwise-convolution). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('mixnet_l', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `mixnet_l`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('mixnet_l', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2019mixconv, + title={MixConv: Mixed Depthwise Convolutional Kernels}, + author={Mingxing Tan and Quoc V. Le}, + year={2019}, + eprint={1907.09595}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/mnasnet.md b/testbed/huggingface__pytorch-image-models/docs/models/mnasnet.md new file mode 100644 index 0000000000000000000000000000000000000000..bf638da25bf72408b8619bed42e44b1754aacc1b --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/mnasnet.md @@ -0,0 +1,170 @@ +# MnasNet + +**MnasNet** is a type of convolutional neural network optimized for mobile devices that is discovered through mobile neural architecture search, which explicitly incorporates model latency into the main objective so that the search can identify a model that achieves a good trade-off between accuracy and latency. The main building block is an [inverted residual block](https://paperswithcode.com/method/inverted-residual-block) (from [MobileNetV2](https://paperswithcode.com/method/mobilenetv2)). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('mnasnet_100', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `mnasnet_100`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('mnasnet_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{tan2019mnasnet, + title={MnasNet: Platform-Aware Neural Architecture Search for Mobile}, + author={Mingxing Tan and Bo Chen and Ruoming Pang and Vijay Vasudevan and Mark Sandler and Andrew Howard and Quoc V. Le}, + year={2019}, + eprint={1807.11626}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/mobilenet-v3.md b/testbed/huggingface__pytorch-image-models/docs/models/mobilenet-v3.md new file mode 100644 index 0000000000000000000000000000000000000000..e68b5259a3dbe363615d5be92cb01f972cf75072 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/mobilenet-v3.md @@ -0,0 +1,199 @@ +# MobileNet v3 + +**MobileNetV3** is a convolutional neural network that is designed for mobile phone CPUs. The network design includes the use of a [hard swish activation](https://paperswithcode.com/method/hard-swish) and [squeeze-and-excitation](https://paperswithcode.com/method/squeeze-and-excitation-block) modules in the [MBConv blocks](https://paperswithcode.com/method/inverted-residual-block). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('mobilenetv3_large_100', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `mobilenetv3_large_100`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('mobilenetv3_large_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1905-02244, + author = {Andrew Howard and + Mark Sandler and + Grace Chu and + Liang{-}Chieh Chen and + Bo Chen and + Mingxing Tan and + Weijun Wang and + Yukun Zhu and + Ruoming Pang and + Vijay Vasudevan and + Quoc V. Le and + Hartwig Adam}, + title = {Searching for MobileNetV3}, + journal = {CoRR}, + volume = {abs/1905.02244}, + year = {2019}, + url = {http://arxiv.org/abs/1905.02244}, + archivePrefix = {arXiv}, + eprint = {1905.02244}, + timestamp = {Tue, 12 Jan 2021 15:30:06 +0100}, + biburl = {https://dblp.org/rec/journals/corr/abs-1905-02244.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/regnetx.md b/testbed/huggingface__pytorch-image-models/docs/models/regnetx.md new file mode 100644 index 0000000000000000000000000000000000000000..0842a60174bb4a11e44d22e1e9c11304c65a71fa --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/regnetx.md @@ -0,0 +1,553 @@ +# RegNetX + +**RegNetX** is a convolutional network design space with simple, regular models with parameters: depth $d$, initial width $w\_{0} > 0$, and slope $w\_{a} > 0$, and generates a different block width $u\_{j}$ for each block $j < d$. The key restriction for the RegNet types of model is that there is a linear parameterisation of block widths (the design space only contains models with this linear structure): + +$$ u\_{j} = w\_{0} + w\_{a}\cdot{j} $$ + +For **RegNetX** we have additional restrictions: we set $b = 1$ (the bottleneck ratio), $12 \leq d \leq 28$, and $w\_{m} \geq 2$ (the width multiplier). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('regnetx_002', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `regnetx_002`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('regnetx_002', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{radosavovic2020designing, + title={Designing Network Design Spaces}, + author={Ilija Radosavovic and Raj Prateek Kosaraju and Ross Girshick and Kaiming He and Piotr Dollár}, + year={2020}, + eprint={2003.13678}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/regnety.md b/testbed/huggingface__pytorch-image-models/docs/models/regnety.md new file mode 100644 index 0000000000000000000000000000000000000000..ba73f73cb52e69f79f309a0ed854f98a8896bd25 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/regnety.md @@ -0,0 +1,567 @@ +# RegNetY + +**RegNetY** is a convolutional network design space with simple, regular models with parameters: depth $d$, initial width $w\_{0} > 0$, and slope $w\_{a} > 0$, and generates a different block width $u\_{j}$ for each block $j < d$. The key restriction for the RegNet types of model is that there is a linear parameterisation of block widths (the design space only contains models with this linear structure): + +$$ u\_{j} = w\_{0} + w\_{a}\cdot{j} $$ + +For **RegNetX** authors have additional restrictions: we set $b = 1$ (the bottleneck ratio), $12 \leq d \leq 28$, and $w\_{m} \geq 2$ (the width multiplier). + +For **RegNetY** authors make one change, which is to include [Squeeze-and-Excitation blocks](https://paperswithcode.com/method/squeeze-and-excitation-block). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('regnety_002', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `regnety_002`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('regnety_002', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@misc{radosavovic2020designing, + title={Designing Network Design Spaces}, + author={Ilija Radosavovic and Raj Prateek Kosaraju and Ross Girshick and Kaiming He and Piotr Dollár}, + year={2020}, + eprint={2003.13678}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/res2next.md b/testbed/huggingface__pytorch-image-models/docs/models/res2next.md new file mode 100644 index 0000000000000000000000000000000000000000..336d1277c190508b244ff0d29fc3b3a127f07b42 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/res2next.md @@ -0,0 +1,136 @@ +# Res2NeXt + +**Res2NeXt** is an image model that employs a variation on [ResNeXt](https://paperswithcode.com/method/resnext) bottleneck residual blocks. The motivation is to be able to represent features at multiple scales. This is achieved through a novel building block for CNNs that constructs hierarchical residual-like connections within one single residual block. This represents multi-scale features at a granular level and increases the range of receptive fields for each network layer. + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('res2next50', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `res2next50`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('res2next50', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{Gao_2021, + title={Res2Net: A New Multi-Scale Backbone Architecture}, + volume={43}, + ISSN={1939-3539}, + url={http://dx.doi.org/10.1109/TPAMI.2019.2938758}, + DOI={10.1109/tpami.2019.2938758}, + number={2}, + journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, + publisher={Institute of Electrical and Electronics Engineers (IEEE)}, + author={Gao, Shang-Hua and Cheng, Ming-Ming and Zhao, Kai and Zhang, Xin-Yu and Yang, Ming-Hsuan and Torr, Philip}, + year={2021}, + month={Feb}, + pages={652–662} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/docs/models/tf-efficientnet-condconv.md b/testbed/huggingface__pytorch-image-models/docs/models/tf-efficientnet-condconv.md new file mode 100644 index 0000000000000000000000000000000000000000..50c46665b84f267d2fb826cb33c8226b0e7e0782 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/docs/models/tf-efficientnet-condconv.md @@ -0,0 +1,250 @@ +# (Tensorflow) EfficientNet CondConv + +**EfficientNet** is a convolutional neural network architecture and scaling method that uniformly scales all dimensions of depth/width/resolution using a *compound coefficient*. Unlike conventional practice that arbitrary scales these factors, the EfficientNet scaling method uniformly scales network width, depth, and resolution with a set of fixed scaling coefficients. For example, if we want to use $2^N$ times more computational resources, then we can simply increase the network depth by $\alpha ^ N$, width by $\beta ^ N$, and image size by $\gamma ^ N$, where $\alpha, \beta, \gamma$ are constant coefficients determined by a small grid search on the original small model. EfficientNet uses a compound coefficient $\phi$ to uniformly scales network width, depth, and resolution in a principled way. + +The compound scaling method is justified by the intuition that if the input image is bigger, then the network needs more layers to increase the receptive field and more channels to capture more fine-grained patterns on the bigger image. + +The base EfficientNet-B0 network is based on the inverted bottleneck residual blocks of [MobileNetV2](https://paperswithcode.com/method/mobilenetv2), in addition to squeeze-and-excitation blocks. + +This collection of models amends EfficientNet by adding [CondConv](https://paperswithcode.com/method/condconv) convolutions. + +The weights from this model were ported from [Tensorflow/TPU](https://github.com/tensorflow/tpu). + +## How do I use this model on an image? +To load a pretrained model: + +```python +import timm +model = timm.create_model('tf_efficientnet_cc_b0_4e', pretrained=True) +model.eval() +``` + +To load and preprocess the image: +```python +import urllib +from PIL import Image +from timm.data import resolve_data_config +from timm.data.transforms_factory import create_transform + +config = resolve_data_config({}, model=model) +transform = create_transform(**config) + +url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") +urllib.request.urlretrieve(url, filename) +img = Image.open(filename).convert('RGB') +tensor = transform(img).unsqueeze(0) # transform and add batch dimension +``` + +To get the model predictions: +```python +import torch +with torch.no_grad(): + out = model(tensor) +probabilities = torch.nn.functional.softmax(out[0], dim=0) +print(probabilities.shape) +# prints: torch.Size([1000]) +``` + +To get the top-5 predictions class names: +```python +# Get imagenet class mappings +url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") +urllib.request.urlretrieve(url, filename) +with open("imagenet_classes.txt", "r") as f: + categories = [s.strip() for s in f.readlines()] + +# Print top categories per image +top5_prob, top5_catid = torch.topk(probabilities, 5) +for i in range(top5_prob.size(0)): + print(categories[top5_catid[i]], top5_prob[i].item()) +# prints class names and probabilities like: +# [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] +``` + +Replace the model name with the variant you want to use, e.g. `tf_efficientnet_cc_b0_4e`. You can find the IDs in the model summaries at the top of this page. + +To extract image features with this model, follow the [timm feature extraction examples](https://rwightman.github.io/pytorch-image-models/feature_extraction/), just change the name of the model you want to use. + +## How do I finetune this model? +You can finetune any of the pre-trained models just by changing the classifier (the last layer). +```python +model = timm.create_model('tf_efficientnet_cc_b0_4e', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) +``` +To finetune on your own dataset, you have to write a training loop or adapt [timm's training +script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. + +## How do I train this model? + +You can follow the [timm recipe scripts](https://rwightman.github.io/pytorch-image-models/scripts/) for training a new model afresh. + +## Citation + +```BibTeX +@article{DBLP:journals/corr/abs-1904-04971, + author = {Brandon Yang and + Gabriel Bender and + Quoc V. Le and + Jiquan Ngiam}, + title = {Soft Conditional Computation}, + journal = {CoRR}, + volume = {abs/1904.04971}, + year = {2019}, + url = {http://arxiv.org/abs/1904.04971}, + archivePrefix = {arXiv}, + eprint = {1904.04971}, + timestamp = {Thu, 25 Apr 2019 13:55:01 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1904-04971.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +``` + + \ No newline at end of file diff --git a/testbed/huggingface__pytorch-image-models/inference.py b/testbed/huggingface__pytorch-image-models/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..5fcf1e60245703bb3d360ec7bc523bed06edfda4 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/inference.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""PyTorch Inference Script + +An example inference script that outputs top-k class ids for images in a folder into a csv. + +Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman) +""" +import os +import time +import argparse +import logging +import numpy as np +import torch + +from timm.models import create_model, apply_test_time_pool +from timm.data import ImageDataset, create_loader, resolve_data_config +from timm.utils import AverageMeter, setup_default_logging + +torch.backends.cudnn.benchmark = True +_logger = logging.getLogger('inference') + + +parser = argparse.ArgumentParser(description='PyTorch ImageNet Inference') +parser.add_argument('data', metavar='DIR', + help='path to dataset') +parser.add_argument('--output_dir', metavar='DIR', default='./', + help='path to output files') +parser.add_argument('--model', '-m', metavar='MODEL', default='dpn92', + help='model architecture (default: dpn92)') +parser.add_argument('-j', '--workers', default=2, type=int, metavar='N', + help='number of data loading workers (default: 2)') +parser.add_argument('-b', '--batch-size', default=256, type=int, + metavar='N', help='mini-batch size (default: 256)') +parser.add_argument('--img-size', default=None, type=int, + metavar='N', help='Input image dimension') +parser.add_argument('--input-size', default=None, nargs=3, type=int, + metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty') +parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', + help='Override mean pixel value of dataset') +parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', + help='Override std deviation of of dataset') +parser.add_argument('--interpolation', default='', type=str, metavar='NAME', + help='Image resize interpolation type (overrides model)') +parser.add_argument('--num-classes', type=int, default=1000, + help='Number classes in dataset') +parser.add_argument('--log-freq', default=10, type=int, + metavar='N', help='batch logging frequency (default: 10)') +parser.add_argument('--checkpoint', default='', type=str, metavar='PATH', + help='path to latest checkpoint (default: none)') +parser.add_argument('--pretrained', dest='pretrained', action='store_true', + help='use pre-trained model') +parser.add_argument('--num-gpu', type=int, default=1, + help='Number of GPUS to use') +parser.add_argument('--no-test-pool', dest='no_test_pool', action='store_true', + help='disable test time pool') +parser.add_argument('--topk', default=5, type=int, + metavar='N', help='Top-k to output to CSV') + + +def main(): + setup_default_logging() + args = parser.parse_args() + # might as well try to do something useful... + args.pretrained = args.pretrained or not args.checkpoint + + # create model + model = create_model( + args.model, + num_classes=args.num_classes, + in_chans=3, + pretrained=args.pretrained, + checkpoint_path=args.checkpoint) + + _logger.info('Model %s created, param count: %d' % + (args.model, sum([m.numel() for m in model.parameters()]))) + + config = resolve_data_config(vars(args), model=model) + model, test_time_pool = (model, False) if args.no_test_pool else apply_test_time_pool(model, config) + + if args.num_gpu > 1: + model = torch.nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() + else: + model = model.cuda() + + loader = create_loader( + ImageDataset(args.data), + input_size=config['input_size'], + batch_size=args.batch_size, + use_prefetcher=True, + interpolation=config['interpolation'], + mean=config['mean'], + std=config['std'], + num_workers=args.workers, + crop_pct=1.0 if test_time_pool else config['crop_pct']) + + model.eval() + + k = min(args.topk, args.num_classes) + batch_time = AverageMeter() + end = time.time() + topk_ids = [] + with torch.no_grad(): + for batch_idx, (input, _) in enumerate(loader): + input = input.cuda() + labels = model(input) + topk = labels.topk(k)[1] + topk_ids.append(topk.cpu().numpy()) + + # measure elapsed time + batch_time.update(time.time() - end) + end = time.time() + + if batch_idx % args.log_freq == 0: + _logger.info('Predict: [{0}/{1}] Time {batch_time.val:.3f} ({batch_time.avg:.3f})'.format( + batch_idx, len(loader), batch_time=batch_time)) + + topk_ids = np.concatenate(topk_ids, axis=0) + + with open(os.path.join(args.output_dir, './topk_ids.csv'), 'w') as out_file: + filenames = loader.dataset.filenames(basename=True) + for filename, label in zip(filenames, topk_ids): + out_file.write('{0},{1}\n'.format( + filename, ','.join([ str(v) for v in label]))) + + +if __name__ == '__main__': + main() diff --git a/testbed/huggingface__pytorch-image-models/model-index.yml b/testbed/huggingface__pytorch-image-models/model-index.yml new file mode 100644 index 0000000000000000000000000000000000000000..38fb78d2a7a8968a21d9f26bc546fa4cb310082b --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/model-index.yml @@ -0,0 +1,14 @@ +Import: +- ./docs/models/*.md +Library: + Name: PyTorch Image Models + Headline: PyTorch image models, scripts, pretrained weights + Website: https://rwightman.github.io/pytorch-image-models/ + Repository: https://github.com/rwightman/pytorch-image-models + Docs: https://rwightman.github.io/pytorch-image-models/ + README: "# PyTorch Image Models\r\n\r\nPyTorch Image Models (TIMM) is a library\ + \ for state-of-the-art image classification. With this library you can:\r\n\r\n\ + - Choose from 300+ pre-trained state-of-the-art image classification models.\r\ + \n- Train models afresh on research datasets such as ImageNet using provided scripts.\r\ + \n- Finetune pre-trained models on your own datasets, including the latest cutting\ + \ edge models." diff --git a/testbed/huggingface__pytorch-image-models/setup.cfg b/testbed/huggingface__pytorch-image-models/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..6289c6c3a16da8a53297b8aa7b59a85277b5116e --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/setup.cfg @@ -0,0 +1,5 @@ +[dist_conda] + +conda_name_differences = 'torch:pytorch' +channels = pytorch +noarch = True diff --git a/testbed/huggingface__pytorch-image-models/timm/__init__.py b/testbed/huggingface__pytorch-image-models/timm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04ec7e51b858e528009bbeea6c75af5985aef202 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/timm/__init__.py @@ -0,0 +1,4 @@ +from .version import __version__ +from .models import create_model, list_models, is_model, list_modules, model_entrypoint, \ + is_scriptable, is_exportable, set_scriptable, set_exportable, has_model_default_key, is_model_default_key, \ + get_model_default_value, is_model_pretrained diff --git a/testbed/huggingface__pytorch-image-models/timm/utils/cuda.py b/testbed/huggingface__pytorch-image-models/timm/utils/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7bddf30463a7be7186c7def47c4e4dfb9993aa --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/timm/utils/cuda.py @@ -0,0 +1,55 @@ +""" CUDA / AMP utils + +Hacked together by / Copyright 2020 Ross Wightman +""" +import torch + +try: + from apex import amp + has_apex = True +except ImportError: + amp = None + has_apex = False + +from .clip_grad import dispatch_clip_grad + + +class ApexScaler: + state_dict_key = "amp" + + def __call__(self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False): + with amp.scale_loss(loss, optimizer) as scaled_loss: + scaled_loss.backward(create_graph=create_graph) + if clip_grad is not None: + dispatch_clip_grad(amp.master_params(optimizer), clip_grad, mode=clip_mode) + optimizer.step() + + def state_dict(self): + if 'state_dict' in amp.__dict__: + return amp.state_dict() + + def load_state_dict(self, state_dict): + if 'load_state_dict' in amp.__dict__: + amp.load_state_dict(state_dict) + + +class NativeScaler: + state_dict_key = "amp_scaler" + + def __init__(self): + self._scaler = torch.cuda.amp.GradScaler() + + def __call__(self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False): + self._scaler.scale(loss).backward(create_graph=create_graph) + if clip_grad is not None: + assert parameters is not None + self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place + dispatch_clip_grad(parameters, clip_grad, mode=clip_mode) + self._scaler.step(optimizer) + self._scaler.update() + + def state_dict(self): + return self._scaler.state_dict() + + def load_state_dict(self, state_dict): + self._scaler.load_state_dict(state_dict) diff --git a/testbed/huggingface__pytorch-image-models/timm/utils/distributed.py b/testbed/huggingface__pytorch-image-models/timm/utils/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..3c5dba8c1de5a6ff53638207521377fdfbc4f239 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/timm/utils/distributed.py @@ -0,0 +1,28 @@ +""" Distributed training/validation utils + +Hacked together by / Copyright 2020 Ross Wightman +""" +import torch +from torch import distributed as dist + +from .model import unwrap_model + + +def reduce_tensor(tensor, n): + rt = tensor.clone() + dist.all_reduce(rt, op=dist.ReduceOp.SUM) + rt /= n + return rt + + +def distribute_bn(model, world_size, reduce=False): + # ensure every node has the same running bn stats + for bn_name, bn_buf in unwrap_model(model).named_buffers(recurse=True): + if ('running_mean' in bn_name) or ('running_var' in bn_name): + if reduce: + # average bn stats across whole group + torch.distributed.all_reduce(bn_buf, op=dist.ReduceOp.SUM) + bn_buf /= float(world_size) + else: + # broadcast bn stats from rank 0 to whole group + torch.distributed.broadcast(bn_buf, 0) diff --git a/testbed/huggingface__pytorch-image-models/timm/utils/jit.py b/testbed/huggingface__pytorch-image-models/timm/utils/jit.py new file mode 100644 index 0000000000000000000000000000000000000000..185ab7a0d852b9a1c469cfbfff108dbafbb02466 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/timm/utils/jit.py @@ -0,0 +1,18 @@ +""" JIT scripting/tracing utils + +Hacked together by / Copyright 2020 Ross Wightman +""" +import torch + + +def set_jit_legacy(): + """ Set JIT executor to legacy w/ support for op fusion + This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes + in the JIT exectutor. These API are not supported so could change. + """ + # + assert hasattr(torch._C, '_jit_set_profiling_executor'), "Old JIT behavior doesn't exist!" + torch._C._jit_set_profiling_executor(False) + torch._C._jit_set_profiling_mode(False) + torch._C._jit_override_can_fuse_on_gpu(True) + #torch._C._jit_set_texpr_fuser_enabled(True) diff --git a/testbed/huggingface__pytorch-image-models/train.py b/testbed/huggingface__pytorch-image-models/train.py new file mode 100644 index 0000000000000000000000000000000000000000..84d8b2ea92fa3ec84ae9991e847b74edc79809e7 --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/train.py @@ -0,0 +1,814 @@ +#!/usr/bin/env python3 +""" ImageNet Training Script + +This is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet +training results with some of the latest networks and training techniques. It favours canonical PyTorch +and standard Python style over trying to be able to 'do it all.' That said, it offers quite a few speed +and training result improvements over the usual PyTorch example scripts. Repurpose as you see fit. + +This script was started from an early version of the PyTorch ImageNet example +(https://github.com/pytorch/examples/tree/master/imagenet) + +NVIDIA CUDA specific speedups adopted from NVIDIA Apex examples +(https://github.com/NVIDIA/apex/tree/master/examples/imagenet) + +Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman) +""" +import argparse +import time +import yaml +import os +import logging +from collections import OrderedDict +from contextlib import suppress +from datetime import datetime + +import torch +import torch.nn as nn +import torchvision.utils +from torch.nn.parallel import DistributedDataParallel as NativeDDP + +from timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset +from timm.models import create_model, safe_model_name, resume_checkpoint, load_checkpoint,\ + convert_splitbn_model, model_parameters +from timm.utils import * +from timm.loss import * +from timm.optim import create_optimizer_v2, optimizer_kwargs +from timm.scheduler import create_scheduler +from timm.utils import ApexScaler, NativeScaler + +try: + from apex import amp + from apex.parallel import DistributedDataParallel as ApexDDP + from apex.parallel import convert_syncbn_model + has_apex = True +except ImportError: + has_apex = False + +has_native_amp = False +try: + if getattr(torch.cuda.amp, 'autocast') is not None: + has_native_amp = True +except AttributeError: + pass + +try: + import wandb + has_wandb = True +except ImportError: + has_wandb = False + +torch.backends.cudnn.benchmark = True +_logger = logging.getLogger('train') + +# The first arg parser parses out only the --config argument, this argument is used to +# load a yaml file containing key-values that override the defaults for the main parser below +config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False) +parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', + help='YAML config file specifying default arguments') + + +parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') + +# Dataset / Model parameters +parser.add_argument('data_dir', metavar='DIR', + help='path to dataset') +parser.add_argument('--dataset', '-d', metavar='NAME', default='', + help='dataset type (default: ImageFolder/ImageTar if empty)') +parser.add_argument('--train-split', metavar='NAME', default='train', + help='dataset train split (default: train)') +parser.add_argument('--val-split', metavar='NAME', default='validation', + help='dataset validation split (default: validation)') +parser.add_argument('--model', default='resnet50', type=str, metavar='MODEL', + help='Name of model to train (default: "resnet50"') +parser.add_argument('--pretrained', action='store_true', default=False, + help='Start with pretrained version of specified network (if avail)') +parser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', + help='Initialize model from this checkpoint (default: none)') +parser.add_argument('--resume', default='', type=str, metavar='PATH', + help='Resume full model and optimizer state from checkpoint (default: none)') +parser.add_argument('--no-resume-opt', action='store_true', default=False, + help='prevent resume of optimizer state when resuming model') +parser.add_argument('--num-classes', type=int, default=None, metavar='N', + help='number of label classes (Model default if None)') +parser.add_argument('--gp', default=None, type=str, metavar='POOL', + help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') +parser.add_argument('--img-size', type=int, default=None, metavar='N', + help='Image patch size (default: None => model default)') +parser.add_argument('--input-size', default=None, nargs=3, type=int, + metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty') +parser.add_argument('--crop-pct', default=None, type=float, + metavar='N', help='Input image center crop percent (for validation only)') +parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', + help='Override mean pixel value of dataset') +parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', + help='Override std deviation of of dataset') +parser.add_argument('--interpolation', default='', type=str, metavar='NAME', + help='Image resize interpolation type (overrides model)') +parser.add_argument('-b', '--batch-size', type=int, default=128, metavar='N', + help='input batch size for training (default: 128)') +parser.add_argument('-vb', '--validation-batch-size', type=int, default=None, metavar='N', + help='validation batch size override (default: None)') + +# Optimizer parameters +parser.add_argument('--opt', default='sgd', type=str, metavar='OPTIMIZER', + help='Optimizer (default: "sgd"') +parser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', + help='Optimizer Epsilon (default: None, use opt default)') +parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', + help='Optimizer Betas (default: None, use opt default)') +parser.add_argument('--momentum', type=float, default=0.9, metavar='M', + help='Optimizer momentum (default: 0.9)') +parser.add_argument('--weight-decay', type=float, default=2e-5, + help='weight decay (default: 2e-5)') +parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM', + help='Clip gradient norm (default: None, no clipping)') +parser.add_argument('--clip-mode', type=str, default='norm', + help='Gradient clipping mode. One of ("norm", "value", "agc")') + + +# Learning rate schedule parameters +parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', + help='LR scheduler (default: "step"') +parser.add_argument('--lr', type=float, default=0.05, metavar='LR', + help='learning rate (default: 0.05)') +parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', + help='learning rate noise on/off epoch percentages') +parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', + help='learning rate noise limit percent (default: 0.67)') +parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', + help='learning rate noise std-dev (default: 1.0)') +parser.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', + help='learning rate cycle len multiplier (default: 1.0)') +parser.add_argument('--lr-cycle-decay', type=float, default=0.5, metavar='MULT', + help='amount to decay each learning rate cycle (default: 0.5)') +parser.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', + help='learning rate cycle limit, cycles enabled if > 1') +parser.add_argument('--lr-k-decay', type=float, default=1.0, + help='learning rate k-decay for cosine/poly (default: 1.0)') +parser.add_argument('--warmup-lr', type=float, default=0.0001, metavar='LR', + help='warmup learning rate (default: 0.0001)') +parser.add_argument('--min-lr', type=float, default=1e-6, metavar='LR', + help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') +parser.add_argument('--epochs', type=int, default=300, metavar='N', + help='number of epochs to train (default: 300)') +parser.add_argument('--epoch-repeats', type=float, default=0., metavar='N', + help='epoch repeat multiplier (number of times to repeat dataset epoch per train epoch).') +parser.add_argument('--start-epoch', default=None, type=int, metavar='N', + help='manual epoch number (useful on restarts)') +parser.add_argument('--decay-epochs', type=float, default=100, metavar='N', + help='epoch interval to decay LR') +parser.add_argument('--warmup-epochs', type=int, default=3, metavar='N', + help='epochs to warmup LR, if scheduler supports') +parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', + help='epochs to cooldown LR at min_lr, after cyclic schedule ends') +parser.add_argument('--patience-epochs', type=int, default=10, metavar='N', + help='patience epochs for Plateau LR scheduler (default: 10') +parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', + help='LR decay rate (default: 0.1)') + +# Augmentation & regularization parameters +parser.add_argument('--no-aug', action='store_true', default=False, + help='Disable all training augmentation, override other train aug args') +parser.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', + help='Random resize scale (default: 0.08 1.0)') +parser.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO', + help='Random resize aspect ratio (default: 0.75 1.33)') +parser.add_argument('--hflip', type=float, default=0.5, + help='Horizontal flip training aug probability') +parser.add_argument('--vflip', type=float, default=0., + help='Vertical flip training aug probability') +parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', + help='Color jitter factor (default: 0.4)') +parser.add_argument('--aa', type=str, default=None, metavar='NAME', + help='Use AutoAugment policy. "v0" or "original". (default: None)'), +parser.add_argument('--aug-repeats', type=int, default=0, + help='Number of augmentation repetitions (distributed training only) (default: 0)') +parser.add_argument('--aug-splits', type=int, default=0, + help='Number of augmentation splits (default: 0, valid: 0 or >=2)') +parser.add_argument('--jsd-loss', action='store_true', default=False, + help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.') +parser.add_argument('--bce-loss', action='store_true', default=False, + help='Enable BCE loss w/ Mixup/CutMix use.') +parser.add_argument('--reprob', type=float, default=0., metavar='PCT', + help='Random erase prob (default: 0.)') +parser.add_argument('--remode', type=str, default='pixel', + help='Random erase mode (default: "pixel")') +parser.add_argument('--recount', type=int, default=1, + help='Random erase count (default: 1)') +parser.add_argument('--resplit', action='store_true', default=False, + help='Do not random erase first (clean) augmentation split') +parser.add_argument('--mixup', type=float, default=0.0, + help='mixup alpha, mixup enabled if > 0. (default: 0.)') +parser.add_argument('--cutmix', type=float, default=0.0, + help='cutmix alpha, cutmix enabled if > 0. (default: 0.)') +parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, + help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') +parser.add_argument('--mixup-prob', type=float, default=1.0, + help='Probability of performing mixup or cutmix when either/both is enabled') +parser.add_argument('--mixup-switch-prob', type=float, default=0.5, + help='Probability of switching to cutmix when both mixup and cutmix enabled') +parser.add_argument('--mixup-mode', type=str, default='batch', + help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') +parser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', + help='Turn off mixup after this epoch, disabled if 0 (default: 0)') +parser.add_argument('--smoothing', type=float, default=0.1, + help='Label smoothing (default: 0.1)') +parser.add_argument('--train-interpolation', type=str, default='random', + help='Training interpolation (random, bilinear, bicubic default: "random")') +parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', + help='Dropout rate (default: 0.)') +parser.add_argument('--drop-connect', type=float, default=None, metavar='PCT', + help='Drop connect rate, DEPRECATED, use drop-path (default: None)') +parser.add_argument('--drop-path', type=float, default=None, metavar='PCT', + help='Drop path rate (default: None)') +parser.add_argument('--drop-block', type=float, default=None, metavar='PCT', + help='Drop block rate (default: None)') + +# Batch norm parameters (only works with gen_efficientnet based models currently) +parser.add_argument('--bn-tf', action='store_true', default=False, + help='Use Tensorflow BatchNorm defaults for models that support it (default: False)') +parser.add_argument('--bn-momentum', type=float, default=None, + help='BatchNorm momentum override (if not None)') +parser.add_argument('--bn-eps', type=float, default=None, + help='BatchNorm epsilon override (if not None)') +parser.add_argument('--sync-bn', action='store_true', + help='Enable NVIDIA Apex or Torch synchronized BatchNorm.') +parser.add_argument('--dist-bn', type=str, default='reduce', + help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")') +parser.add_argument('--split-bn', action='store_true', + help='Enable separate BN layers per augmentation split.') + +# Model Exponential Moving Average +parser.add_argument('--model-ema', action='store_true', default=False, + help='Enable tracking moving average of model weights') +parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, + help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.') +parser.add_argument('--model-ema-decay', type=float, default=0.9998, + help='decay factor for model weights moving average (default: 0.9998)') + +# Misc +parser.add_argument('--seed', type=int, default=42, metavar='S', + help='random seed (default: 42)') +parser.add_argument('--log-interval', type=int, default=50, metavar='N', + help='how many batches to wait before logging training status') +parser.add_argument('--recovery-interval', type=int, default=0, metavar='N', + help='how many batches to wait before writing recovery checkpoint') +parser.add_argument('--checkpoint-hist', type=int, default=10, metavar='N', + help='number of checkpoints to keep (default: 10)') +parser.add_argument('-j', '--workers', type=int, default=4, metavar='N', + help='how many training processes to use (default: 4)') +parser.add_argument('--save-images', action='store_true', default=False, + help='save images of input bathes every log interval for debugging') +parser.add_argument('--amp', action='store_true', default=False, + help='use NVIDIA Apex AMP or Native AMP for mixed precision training') +parser.add_argument('--apex-amp', action='store_true', default=False, + help='Use NVIDIA Apex AMP mixed precision') +parser.add_argument('--native-amp', action='store_true', default=False, + help='Use Native Torch AMP mixed precision') +parser.add_argument('--channels-last', action='store_true', default=False, + help='Use channels_last memory layout') +parser.add_argument('--pin-mem', action='store_true', default=False, + help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') +parser.add_argument('--no-prefetcher', action='store_true', default=False, + help='disable fast prefetcher') +parser.add_argument('--output', default='', type=str, metavar='PATH', + help='path to output folder (default: none, current dir)') +parser.add_argument('--experiment', default='', type=str, metavar='NAME', + help='name of train experiment, name of sub-folder for output') +parser.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', + help='Best metric (default: "top1"') +parser.add_argument('--tta', type=int, default=0, metavar='N', + help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') +parser.add_argument("--local_rank", default=0, type=int) +parser.add_argument('--use-multi-epochs-loader', action='store_true', default=False, + help='use the multi-epochs-loader to save time at the beginning of every epoch') +parser.add_argument('--torchscript', dest='torchscript', action='store_true', + help='convert model torchscript for inference') +parser.add_argument('--log-wandb', action='store_true', default=False, + help='log training and validation metrics to wandb') + + +def _parse_args(): + # Do we have a config file to parse? + args_config, remaining = config_parser.parse_known_args() + if args_config.config: + with open(args_config.config, 'r') as f: + cfg = yaml.safe_load(f) + parser.set_defaults(**cfg) + + # The main arg parser parses the rest of the args, the usual + # defaults will have been overridden if config file specified. + args = parser.parse_args(remaining) + + # Cache the args as a text string to save them in the output dir later + args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) + return args, args_text + + +def main(): + setup_default_logging() + args, args_text = _parse_args() + + if args.log_wandb: + if has_wandb: + wandb.init(project=args.experiment, config=args) + else: + _logger.warning("You've requested to log metrics to wandb but package not found. " + "Metrics not being logged to wandb, try `pip install wandb`") + + args.prefetcher = not args.no_prefetcher + args.distributed = False + if 'WORLD_SIZE' in os.environ: + args.distributed = int(os.environ['WORLD_SIZE']) > 1 + args.device = 'cuda:0' + args.world_size = 1 + args.rank = 0 # global rank + if args.distributed: + args.device = 'cuda:%d' % args.local_rank + torch.cuda.set_device(args.local_rank) + torch.distributed.init_process_group(backend='nccl', init_method='env://') + args.world_size = torch.distributed.get_world_size() + args.rank = torch.distributed.get_rank() + _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.' + % (args.rank, args.world_size)) + else: + _logger.info('Training with a single process on 1 GPUs.') + assert args.rank >= 0 + + # resolve AMP arguments based on PyTorch / Apex availability + use_amp = None + if args.amp: + # `--amp` chooses native amp before apex (APEX ver not actively maintained) + if has_native_amp: + args.native_amp = True + elif has_apex: + args.apex_amp = True + if args.apex_amp and has_apex: + use_amp = 'apex' + elif args.native_amp and has_native_amp: + use_amp = 'native' + elif args.apex_amp or args.native_amp: + _logger.warning("Neither APEX or native Torch AMP is available, using float32. " + "Install NVIDA apex or upgrade to PyTorch 1.6") + + random_seed(args.seed, args.rank) + + model = create_model( + args.model, + pretrained=args.pretrained, + num_classes=args.num_classes, + drop_rate=args.drop, + drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path + drop_path_rate=args.drop_path, + drop_block_rate=args.drop_block, + global_pool=args.gp, + bn_tf=args.bn_tf, + bn_momentum=args.bn_momentum, + bn_eps=args.bn_eps, + scriptable=args.torchscript, + checkpoint_path=args.initial_checkpoint) + if args.num_classes is None: + assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.' + args.num_classes = model.num_classes # FIXME handle model default vs config num_classes more elegantly + + if args.local_rank == 0: + _logger.info( + f'Model {safe_model_name(args.model)} created, param count:{sum([m.numel() for m in model.parameters()])}') + + data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0) + + # setup augmentation batch splits for contrastive loss or split bn + num_aug_splits = 0 + if args.aug_splits > 0: + assert args.aug_splits > 1, 'A split of 1 makes no sense' + num_aug_splits = args.aug_splits + + # enable split bn (separate bn stats per batch-portion) + if args.split_bn: + assert num_aug_splits > 1 or args.resplit + model = convert_splitbn_model(model, max(num_aug_splits, 2)) + + # move model to GPU, enable channels last layout if set + model.cuda() + if args.channels_last: + model = model.to(memory_format=torch.channels_last) + + # setup synchronized BatchNorm for distributed training + if args.distributed and args.sync_bn: + assert not args.split_bn + if has_apex and use_amp == 'apex': + # Apex SyncBN preferred unless native amp is activated + model = convert_syncbn_model(model) + else: + model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) + if args.local_rank == 0: + _logger.info( + 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' + 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') + + if args.torchscript: + assert not use_amp == 'apex', 'Cannot use APEX AMP with torchscripted model' + assert not args.sync_bn, 'Cannot use SyncBatchNorm with torchscripted model' + model = torch.jit.script(model) + + optimizer = create_optimizer_v2(model, **optimizer_kwargs(cfg=args)) + + # setup automatic mixed-precision (AMP) loss scaling and op casting + amp_autocast = suppress # do nothing + loss_scaler = None + if use_amp == 'apex': + model, optimizer = amp.initialize(model, optimizer, opt_level='O1') + loss_scaler = ApexScaler() + if args.local_rank == 0: + _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') + elif use_amp == 'native': + amp_autocast = torch.cuda.amp.autocast + loss_scaler = NativeScaler() + if args.local_rank == 0: + _logger.info('Using native Torch AMP. Training in mixed precision.') + else: + if args.local_rank == 0: + _logger.info('AMP not enabled. Training in float32.') + + # optionally resume from a checkpoint + resume_epoch = None + if args.resume: + resume_epoch = resume_checkpoint( + model, args.resume, + optimizer=None if args.no_resume_opt else optimizer, + loss_scaler=None if args.no_resume_opt else loss_scaler, + log_info=args.local_rank == 0) + + # setup exponential moving average of model weights, SWA could be used here too + model_ema = None + if args.model_ema: + # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper + model_ema = ModelEmaV2( + model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else None) + if args.resume: + load_checkpoint(model_ema.module, args.resume, use_ema=True) + + # setup distributed training + if args.distributed: + if has_apex and use_amp == 'apex': + # Apex DDP preferred unless native amp is activated + if args.local_rank == 0: + _logger.info("Using NVIDIA APEX DistributedDataParallel.") + model = ApexDDP(model, delay_allreduce=True) + else: + if args.local_rank == 0: + _logger.info("Using native Torch DistributedDataParallel.") + model = NativeDDP(model, device_ids=[args.local_rank]) # can use device str in Torch >= 1.1 + # NOTE: EMA model does not need to be wrapped by DDP + + # setup learning rate schedule and starting epoch + lr_scheduler, num_epochs = create_scheduler(args, optimizer) + start_epoch = 0 + if args.start_epoch is not None: + # a specified start_epoch will always override the resume epoch + start_epoch = args.start_epoch + elif resume_epoch is not None: + start_epoch = resume_epoch + if lr_scheduler is not None and start_epoch > 0: + lr_scheduler.step(start_epoch) + + if args.local_rank == 0: + _logger.info('Scheduled epochs: {}'.format(num_epochs)) + + # create the train and eval datasets + dataset_train = create_dataset( + args.dataset, + root=args.data_dir, split=args.train_split, is_training=True, + batch_size=args.batch_size, repeats=args.epoch_repeats) + dataset_eval = create_dataset( + args.dataset, root=args.data_dir, split=args.val_split, is_training=False, batch_size=args.batch_size) + + # setup mixup / cutmix + collate_fn = None + mixup_fn = None + mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None + if mixup_active: + mixup_args = dict( + mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, + prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, + label_smoothing=args.smoothing, num_classes=args.num_classes) + if args.prefetcher: + assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup) + collate_fn = FastCollateMixup(**mixup_args) + else: + mixup_fn = Mixup(**mixup_args) + + # wrap dataset in AugMix helper + if num_aug_splits > 1: + dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits) + + # create data loaders w/ augmentation pipeiine + train_interpolation = args.train_interpolation + if args.no_aug or not train_interpolation: + train_interpolation = data_config['interpolation'] + loader_train = create_loader( + dataset_train, + input_size=data_config['input_size'], + batch_size=args.batch_size, + is_training=True, + use_prefetcher=args.prefetcher, + no_aug=args.no_aug, + re_prob=args.reprob, + re_mode=args.remode, + re_count=args.recount, + re_split=args.resplit, + scale=args.scale, + ratio=args.ratio, + hflip=args.hflip, + vflip=args.vflip, + color_jitter=args.color_jitter, + auto_augment=args.aa, + num_aug_repeats=args.aug_repeats, + num_aug_splits=num_aug_splits, + interpolation=train_interpolation, + mean=data_config['mean'], + std=data_config['std'], + num_workers=args.workers, + distributed=args.distributed, + collate_fn=collate_fn, + pin_memory=args.pin_mem, + use_multi_epochs_loader=args.use_multi_epochs_loader + ) + + loader_eval = create_loader( + dataset_eval, + input_size=data_config['input_size'], + batch_size=args.validation_batch_size or args.batch_size, + is_training=False, + use_prefetcher=args.prefetcher, + interpolation=data_config['interpolation'], + mean=data_config['mean'], + std=data_config['std'], + num_workers=args.workers, + distributed=args.distributed, + crop_pct=data_config['crop_pct'], + pin_memory=args.pin_mem, + ) + + # setup loss function + if args.jsd_loss: + assert num_aug_splits > 1 # JSD only valid with aug splits set + train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing) + elif mixup_active: + # smoothing is handled with mixup target transform which outputs sparse, soft targets + if args.bce_loss: + train_loss_fn = nn.BCEWithLogitsLoss() + else: + train_loss_fn = SoftTargetCrossEntropy() + elif args.smoothing: + if args.bce_loss: + train_loss_fn = DenseBinaryCrossEntropy(smoothing=args.smoothing) + else: + train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing) + else: + train_loss_fn = nn.CrossEntropyLoss() + train_loss_fn = train_loss_fn.cuda() + validate_loss_fn = nn.CrossEntropyLoss().cuda() + + # setup checkpoint saver and eval metric tracking + eval_metric = args.eval_metric + best_metric = None + best_epoch = None + saver = None + output_dir = None + if args.rank == 0: + if args.experiment: + exp_name = args.experiment + else: + exp_name = '-'.join([ + datetime.now().strftime("%Y%m%d-%H%M%S"), + safe_model_name(args.model), + str(data_config['input_size'][-1]) + ]) + output_dir = get_outdir(args.output if args.output else './output/train', exp_name) + decreasing = True if eval_metric == 'loss' else False + saver = CheckpointSaver( + model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler, + checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing, max_history=args.checkpoint_hist) + with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: + f.write(args_text) + + try: + for epoch in range(start_epoch, num_epochs): + if args.distributed and hasattr(loader_train.sampler, 'set_epoch'): + loader_train.sampler.set_epoch(epoch) + + train_metrics = train_one_epoch( + epoch, model, loader_train, optimizer, train_loss_fn, args, + lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir, + amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn) + + if args.distributed and args.dist_bn in ('broadcast', 'reduce'): + if args.local_rank == 0: + _logger.info("Distributing BatchNorm running means and vars") + distribute_bn(model, args.world_size, args.dist_bn == 'reduce') + + eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast) + + if model_ema is not None and not args.model_ema_force_cpu: + if args.distributed and args.dist_bn in ('broadcast', 'reduce'): + distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce') + ema_eval_metrics = validate( + model_ema.module, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)') + eval_metrics = ema_eval_metrics + + if lr_scheduler is not None: + # step LR for next epoch + lr_scheduler.step(epoch + 1, eval_metrics[eval_metric]) + + if output_dir is not None: + update_summary( + epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'), + write_header=best_metric is None, log_wandb=args.log_wandb and has_wandb) + + if saver is not None: + # save proper checkpoint with eval metric + save_metric = eval_metrics[eval_metric] + best_metric, best_epoch = saver.save_checkpoint(epoch, metric=save_metric) + + except KeyboardInterrupt: + pass + if best_metric is not None: + _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch)) + + +def train_one_epoch( + epoch, model, loader, optimizer, loss_fn, args, + lr_scheduler=None, saver=None, output_dir=None, amp_autocast=suppress, + loss_scaler=None, model_ema=None, mixup_fn=None): + + if args.mixup_off_epoch and epoch >= args.mixup_off_epoch: + if args.prefetcher and loader.mixup_enabled: + loader.mixup_enabled = False + elif mixup_fn is not None: + mixup_fn.mixup_enabled = False + + second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order + batch_time_m = AverageMeter() + data_time_m = AverageMeter() + losses_m = AverageMeter() + + model.train() + + end = time.time() + last_idx = len(loader) - 1 + num_updates = epoch * len(loader) + for batch_idx, (input, target) in enumerate(loader): + last_batch = batch_idx == last_idx + data_time_m.update(time.time() - end) + if not args.prefetcher: + input, target = input.cuda(), target.cuda() + if mixup_fn is not None: + input, target = mixup_fn(input, target) + if args.channels_last: + input = input.contiguous(memory_format=torch.channels_last) + + with amp_autocast(): + output = model(input) + loss = loss_fn(output, target) + + if not args.distributed: + losses_m.update(loss.item(), input.size(0)) + + optimizer.zero_grad() + if loss_scaler is not None: + loss_scaler( + loss, optimizer, + clip_grad=args.clip_grad, clip_mode=args.clip_mode, + parameters=model_parameters(model, exclude_head='agc' in args.clip_mode), + create_graph=second_order) + else: + loss.backward(create_graph=second_order) + if args.clip_grad is not None: + dispatch_clip_grad( + model_parameters(model, exclude_head='agc' in args.clip_mode), + value=args.clip_grad, mode=args.clip_mode) + optimizer.step() + + if model_ema is not None: + model_ema.update(model) + + torch.cuda.synchronize() + num_updates += 1 + batch_time_m.update(time.time() - end) + if last_batch or batch_idx % args.log_interval == 0: + lrl = [param_group['lr'] for param_group in optimizer.param_groups] + lr = sum(lrl) / len(lrl) + + if args.distributed: + reduced_loss = reduce_tensor(loss.data, args.world_size) + losses_m.update(reduced_loss.item(), input.size(0)) + + if args.local_rank == 0: + _logger.info( + 'Train: {} [{:>4d}/{} ({:>3.0f}%)] ' + 'Loss: {loss.val:#.4g} ({loss.avg:#.3g}) ' + 'Time: {batch_time.val:.3f}s, {rate:>7.2f}/s ' + '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) ' + 'LR: {lr:.3e} ' + 'Data: {data_time.val:.3f} ({data_time.avg:.3f})'.format( + epoch, + batch_idx, len(loader), + 100. * batch_idx / last_idx, + loss=losses_m, + batch_time=batch_time_m, + rate=input.size(0) * args.world_size / batch_time_m.val, + rate_avg=input.size(0) * args.world_size / batch_time_m.avg, + lr=lr, + data_time=data_time_m)) + + if args.save_images and output_dir: + torchvision.utils.save_image( + input, + os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx), + padding=0, + normalize=True) + + if saver is not None and args.recovery_interval and ( + last_batch or (batch_idx + 1) % args.recovery_interval == 0): + saver.save_recovery(epoch, batch_idx=batch_idx) + + if lr_scheduler is not None: + lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg) + + end = time.time() + # end for + + if hasattr(optimizer, 'sync_lookahead'): + optimizer.sync_lookahead() + + return OrderedDict([('loss', losses_m.avg)]) + + +def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): + batch_time_m = AverageMeter() + losses_m = AverageMeter() + top1_m = AverageMeter() + top5_m = AverageMeter() + + model.eval() + + end = time.time() + last_idx = len(loader) - 1 + with torch.no_grad(): + for batch_idx, (input, target) in enumerate(loader): + last_batch = batch_idx == last_idx + if not args.prefetcher: + input = input.cuda() + target = target.cuda() + if args.channels_last: + input = input.contiguous(memory_format=torch.channels_last) + + with amp_autocast(): + output = model(input) + if isinstance(output, (tuple, list)): + output = output[0] + + # augmentation reduction + reduce_factor = args.tta + if reduce_factor > 1: + output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2) + target = target[0:target.size(0):reduce_factor] + + loss = loss_fn(output, target) + acc1, acc5 = accuracy(output, target, topk=(1, 5)) + + if args.distributed: + reduced_loss = reduce_tensor(loss.data, args.world_size) + acc1 = reduce_tensor(acc1, args.world_size) + acc5 = reduce_tensor(acc5, args.world_size) + else: + reduced_loss = loss.data + + torch.cuda.synchronize() + + losses_m.update(reduced_loss.item(), input.size(0)) + top1_m.update(acc1.item(), output.size(0)) + top5_m.update(acc5.item(), output.size(0)) + + batch_time_m.update(time.time() - end) + end = time.time() + if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0): + log_name = 'Test' + log_suffix + _logger.info( + '{0}: [{1:>4d}/{2}] ' + 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) ' + 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' + 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) ' + 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format( + log_name, batch_idx, last_idx, batch_time=batch_time_m, + loss=losses_m, top1=top1_m, top5=top5_m)) + + metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)]) + + return metrics + + +if __name__ == '__main__': + main() diff --git a/testbed/huggingface__pytorch-image-models/validate.py b/testbed/huggingface__pytorch-image-models/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..ab5b644f4cddcec4f312e52fae60637f533c900c --- /dev/null +++ b/testbed/huggingface__pytorch-image-models/validate.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +""" ImageNet Validation Script + +This is intended to be a lean and easily modifiable ImageNet validation script for evaluating pretrained +models or training checkpoints against ImageNet or similarly organized image datasets. It prioritizes +canonical PyTorch, standard Python style, and good performance. Repurpose as you see fit. + +Hacked together by Ross Wightman (https://github.com/rwightman) +""" +import argparse +import os +import csv +import glob +import time +import logging +import torch +import torch.nn as nn +import torch.nn.parallel +from collections import OrderedDict +from contextlib import suppress + +from timm.models import create_model, apply_test_time_pool, load_checkpoint, is_model, list_models +from timm.data import create_dataset, create_loader, resolve_data_config, RealLabelsImagenet +from timm.utils import accuracy, AverageMeter, natural_key, setup_default_logging, set_jit_legacy + +has_apex = False +try: + from apex import amp + has_apex = True +except ImportError: + pass + +has_native_amp = False +try: + if getattr(torch.cuda.amp, 'autocast') is not None: + has_native_amp = True +except AttributeError: + pass + +torch.backends.cudnn.benchmark = True +_logger = logging.getLogger('validate') + + +parser = argparse.ArgumentParser(description='PyTorch ImageNet Validation') +parser.add_argument('data', metavar='DIR', + help='path to dataset') +parser.add_argument('--dataset', '-d', metavar='NAME', default='', + help='dataset type (default: ImageFolder/ImageTar if empty)') +parser.add_argument('--split', metavar='NAME', default='validation', + help='dataset split (default: validation)') +parser.add_argument('--model', '-m', metavar='NAME', default='dpn92', + help='model architecture (default: dpn92)') +parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', + help='number of data loading workers (default: 2)') +parser.add_argument('-b', '--batch-size', default=256, type=int, + metavar='N', help='mini-batch size (default: 256)') +parser.add_argument('--img-size', default=None, type=int, + metavar='N', help='Input image dimension, uses model default if empty') +parser.add_argument('--input-size', default=None, nargs=3, type=int, + metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty') +parser.add_argument('--crop-pct', default=None, type=float, + metavar='N', help='Input image center crop pct') +parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', + help='Override mean pixel value of dataset') +parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', + help='Override std deviation of of dataset') +parser.add_argument('--interpolation', default='', type=str, metavar='NAME', + help='Image resize interpolation type (overrides model)') +parser.add_argument('--num-classes', type=int, default=None, + help='Number classes in dataset') +parser.add_argument('--class-map', default='', type=str, metavar='FILENAME', + help='path to class to idx mapping file (default: "")') +parser.add_argument('--gp', default=None, type=str, metavar='POOL', + help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') +parser.add_argument('--log-freq', default=10, type=int, + metavar='N', help='batch logging frequency (default: 10)') +parser.add_argument('--checkpoint', default='', type=str, metavar='PATH', + help='path to latest checkpoint (default: none)') +parser.add_argument('--pretrained', dest='pretrained', action='store_true', + help='use pre-trained model') +parser.add_argument('--num-gpu', type=int, default=1, + help='Number of GPUS to use') +parser.add_argument('--no-test-pool', dest='no_test_pool', action='store_true', + help='disable test time pool') +parser.add_argument('--no-prefetcher', action='store_true', default=False, + help='disable fast prefetcher') +parser.add_argument('--pin-mem', action='store_true', default=False, + help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') +parser.add_argument('--channels-last', action='store_true', default=False, + help='Use channels_last memory layout') +parser.add_argument('--amp', action='store_true', default=False, + help='Use AMP mixed precision. Defaults to Apex, fallback to native Torch AMP.') +parser.add_argument('--apex-amp', action='store_true', default=False, + help='Use NVIDIA Apex AMP mixed precision') +parser.add_argument('--native-amp', action='store_true', default=False, + help='Use Native Torch AMP mixed precision') +parser.add_argument('--tf-preprocessing', action='store_true', default=False, + help='Use Tensorflow preprocessing pipeline (require CPU TF installed') +parser.add_argument('--use-ema', dest='use_ema', action='store_true', + help='use ema version of weights if present') +parser.add_argument('--torchscript', dest='torchscript', action='store_true', + help='convert model torchscript for inference') +parser.add_argument('--legacy-jit', dest='legacy_jit', action='store_true', + help='use legacy jit mode for pytorch 1.5/1.5.1/1.6 to get back fusion performance') +parser.add_argument('--results-file', default='', type=str, metavar='FILENAME', + help='Output csv file for validation results (summary)') +parser.add_argument('--real-labels', default='', type=str, metavar='FILENAME', + help='Real labels JSON file for imagenet evaluation') +parser.add_argument('--valid-labels', default='', type=str, metavar='FILENAME', + help='Valid label indices txt file for validation of partial label space') + + +def validate(args): + # might as well try to validate something + args.pretrained = args.pretrained or not args.checkpoint + args.prefetcher = not args.no_prefetcher + amp_autocast = suppress # do nothing + if args.amp: + if has_native_amp: + args.native_amp = True + elif has_apex: + args.apex_amp = True + else: + _logger.warning("Neither APEX or Native Torch AMP is available.") + assert not args.apex_amp or not args.native_amp, "Only one AMP mode should be set." + if args.native_amp: + amp_autocast = torch.cuda.amp.autocast + _logger.info('Validating in mixed precision with native PyTorch AMP.') + elif args.apex_amp: + _logger.info('Validating in mixed precision with NVIDIA APEX AMP.') + else: + _logger.info('Validating in float32. AMP not enabled.') + + if args.legacy_jit: + set_jit_legacy() + + # create model + model = create_model( + args.model, + pretrained=args.pretrained, + num_classes=args.num_classes, + in_chans=3, + global_pool=args.gp, + scriptable=args.torchscript) + if args.num_classes is None: + assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.' + args.num_classes = model.num_classes + + if args.checkpoint: + load_checkpoint(model, args.checkpoint, args.use_ema) + + param_count = sum([m.numel() for m in model.parameters()]) + _logger.info('Model %s created, param count: %d' % (args.model, param_count)) + + data_config = resolve_data_config(vars(args), model=model, use_test_size=True, verbose=True) + test_time_pool = False + if not args.no_test_pool: + model, test_time_pool = apply_test_time_pool(model, data_config, use_test_size=True) + + if args.torchscript: + torch.jit.optimized_execution(True) + model = torch.jit.script(model) + + model = model.cuda() + if args.apex_amp: + model = amp.initialize(model, opt_level='O1') + + if args.channels_last: + model = model.to(memory_format=torch.channels_last) + + if args.num_gpu > 1: + model = torch.nn.DataParallel(model, device_ids=list(range(args.num_gpu))) + + criterion = nn.CrossEntropyLoss().cuda() + + dataset = create_dataset( + root=args.data, name=args.dataset, split=args.split, + load_bytes=args.tf_preprocessing, class_map=args.class_map) + + if args.valid_labels: + with open(args.valid_labels, 'r') as f: + valid_labels = {int(line.rstrip()) for line in f} + valid_labels = [i in valid_labels for i in range(args.num_classes)] + else: + valid_labels = None + + if args.real_labels: + real_labels = RealLabelsImagenet(dataset.filenames(basename=True), real_json=args.real_labels) + else: + real_labels = None + + crop_pct = 1.0 if test_time_pool else data_config['crop_pct'] + loader = create_loader( + dataset, + input_size=data_config['input_size'], + batch_size=args.batch_size, + use_prefetcher=args.prefetcher, + interpolation=data_config['interpolation'], + mean=data_config['mean'], + std=data_config['std'], + num_workers=args.workers, + crop_pct=crop_pct, + pin_memory=args.pin_mem, + tf_preprocessing=args.tf_preprocessing) + + batch_time = AverageMeter() + losses = AverageMeter() + top1 = AverageMeter() + top5 = AverageMeter() + + model.eval() + with torch.no_grad(): + # warmup, reduce variability of first batch time, especially for comparing torchscript vs non + input = torch.randn((args.batch_size,) + tuple(data_config['input_size'])).cuda() + if args.channels_last: + input = input.contiguous(memory_format=torch.channels_last) + model(input) + end = time.time() + for batch_idx, (input, target) in enumerate(loader): + if args.no_prefetcher: + target = target.cuda() + input = input.cuda() + if args.channels_last: + input = input.contiguous(memory_format=torch.channels_last) + + # compute output + with amp_autocast(): + output = model(input) + + if valid_labels is not None: + output = output[:, valid_labels] + loss = criterion(output, target) + + if real_labels is not None: + real_labels.add_result(output) + + # measure accuracy and record loss + acc1, acc5 = accuracy(output.detach(), target, topk=(1, 5)) + losses.update(loss.item(), input.size(0)) + top1.update(acc1.item(), input.size(0)) + top5.update(acc5.item(), input.size(0)) + + # measure elapsed time + batch_time.update(time.time() - end) + end = time.time() + + if batch_idx % args.log_freq == 0: + _logger.info( + 'Test: [{0:>4d}/{1}] ' + 'Time: {batch_time.val:.3f}s ({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) ' + 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' + 'Acc@1: {top1.val:>7.3f} ({top1.avg:>7.3f}) ' + 'Acc@5: {top5.val:>7.3f} ({top5.avg:>7.3f})'.format( + batch_idx, len(loader), batch_time=batch_time, + rate_avg=input.size(0) / batch_time.avg, + loss=losses, top1=top1, top5=top5)) + + if real_labels is not None: + # real labels mode replaces topk values at the end + top1a, top5a = real_labels.get_accuracy(k=1), real_labels.get_accuracy(k=5) + else: + top1a, top5a = top1.avg, top5.avg + results = OrderedDict( + top1=round(top1a, 4), top1_err=round(100 - top1a, 4), + top5=round(top5a, 4), top5_err=round(100 - top5a, 4), + param_count=round(param_count / 1e6, 2), + img_size=data_config['input_size'][-1], + cropt_pct=crop_pct, + interpolation=data_config['interpolation']) + + _logger.info(' * Acc@1 {:.3f} ({:.3f}) Acc@5 {:.3f} ({:.3f})'.format( + results['top1'], results['top1_err'], results['top5'], results['top5_err'])) + + return results + + +def main(): + setup_default_logging() + args = parser.parse_args() + model_cfgs = [] + model_names = [] + if os.path.isdir(args.checkpoint): + # validate all checkpoints in a path with same model + checkpoints = glob.glob(args.checkpoint + '/*.pth.tar') + checkpoints += glob.glob(args.checkpoint + '/*.pth') + model_names = list_models(args.model) + model_cfgs = [(args.model, c) for c in sorted(checkpoints, key=natural_key)] + else: + if args.model == 'all': + # validate all models in a list of names with pretrained checkpoints + args.pretrained = True + model_names = list_models(pretrained=True, exclude_filters=['*_in21k', '*_in22k']) + model_cfgs = [(n, '') for n in model_names] + elif not is_model(args.model): + # model name doesn't exist, try as wildcard filter + model_names = list_models(args.model) + model_cfgs = [(n, '') for n in model_names] + + if len(model_cfgs): + results_file = args.results_file or './results-all.csv' + _logger.info('Running bulk validation on these pretrained models: {}'.format(', '.join(model_names))) + results = [] + try: + start_batch_size = args.batch_size + for m, c in model_cfgs: + batch_size = start_batch_size + args.model = m + args.checkpoint = c + result = OrderedDict(model=args.model) + r = {} + while not r and batch_size >= args.num_gpu: + torch.cuda.empty_cache() + try: + args.batch_size = batch_size + print('Validating with batch size: %d' % args.batch_size) + r = validate(args) + except RuntimeError as e: + if batch_size <= args.num_gpu: + print("Validation failed with no ability to reduce batch size. Exiting.") + raise e + batch_size = max(batch_size // 2, args.num_gpu) + print("Validation failed, reducing batch size by 50%") + result.update(r) + if args.checkpoint: + result['checkpoint'] = args.checkpoint + results.append(result) + except KeyboardInterrupt as e: + pass + results = sorted(results, key=lambda x: x['top1'], reverse=True) + if len(results): + write_results(results_file, results) + else: + validate(args) + + +def write_results(results_file, results): + with open(results_file, mode='w') as cf: + dw = csv.DictWriter(cf, fieldnames=results[0].keys()) + dw.writeheader() + for r in results: + dw.writerow(r) + cf.flush() + + +if __name__ == '__main__': + main() diff --git a/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/bug-report.yml b/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..8446a33af64d2b6ebb8d4c33d9d871f82f1a9d69 --- /dev/null +++ b/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,93 @@ +name: "\U0001F41B Bug Report" +description: Submit a bug report to help us improve TRL +labels: [ "bug" ] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! 🤗 + + 🚩 If it is your first time submitting, be sure to check our [bug report guidelines](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#did-you-find-a-bug) + + - type: textarea + id: system-info + attributes: + label: System Info + description: | + Please provide information about your system: platform, Python version, PyTorch version, Transformers version, devices, TRL version, ... + You can get this information by running `trl env` in your terminal. + + placeholder: Copy-paste the output of `trl env` + validations: + required: true + + - type: checkboxes + id: information-scripts-examples + attributes: + label: Information + description: 'The problem arises when using:' + options: + - label: "The official example scripts" + - label: "My own modified scripts" + + - type: checkboxes + id: information-tasks + attributes: + label: Tasks + description: "The tasks I am working on are:" + options: + - label: "An officially supported task in the `examples` folder" + - label: "My own task or dataset (give details below)" + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + value: | + ```python + from trl import ... + + ``` + + outputs: + + ``` + Traceback (most recent call last): + File "example.py", line 42, in + ... + ``` + + - type: textarea + id: expected-behavior + validations: + required: true + attributes: + label: Expected behavior + description: "A clear and concise description of what you would expect to happen." + + - type: checkboxes + id: terms + attributes: + label: Checklist + description: | + Before submitting, please confirm that you've completed each of the following. + If an item doesn't apply to your issue, check it anyway to show you've reviewed it. + options: + - label: "I have checked that my issue isn't already filed (see [open issues](https://github.com/huggingface/trl/issues?q=is%3Aissue))" + required: true + - label: "I have included my system information" + required: true + - label: "Any code provided is minimal, complete, and reproducible ([more on MREs](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks))" + required: true + - label: "Any code provided is properly formatted in code blocks, (no screenshot, [more on code blocks](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks))" + required: true + - label: "Any traceback provided is complete" + required: true diff --git a/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/feature-request.yml b/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 0000000000000000000000000000000000000000..0a593186c098ae3824ef994374686092f97ccb4a --- /dev/null +++ b/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,31 @@ +name: "\U0001F680 Feature request" +description: Submit a proposal/request for a new TRL feature +labels: [ "Feature request" ] +body: + - type: textarea + id: feature-request + validations: + required: true + attributes: + label: Feature request + description: | + A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist. + + - type: textarea + id: motivation + validations: + required: true + attributes: + label: Motivation + description: | + Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too. + + + - type: textarea + id: contribution + validations: + required: true + attributes: + label: Your contribution + description: | + Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) diff --git a/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/new-trainer-addition.yml b/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/new-trainer-addition.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea0b5afb10ae6d7519d07ee510faf617f369048c --- /dev/null +++ b/testbed/huggingface__trl/.github/ISSUE_TEMPLATE/new-trainer-addition.yml @@ -0,0 +1,32 @@ +name: "\U0001F31F New trainer addition" +description: Submit a proposal/request to implement a new trainer for a post-training method +labels: [ "New trainer" ] + +body: + - type: textarea + id: description-request + validations: + required: true + attributes: + label: Method description + description: | + Put any and all important information relative to the method + + - type: checkboxes + id: information-tasks + attributes: + label: Open source status + description: | + Please note that if the method implementation isn't available or model weights with training datasets aren't available, we are less likely to implement it in `trl`. + options: + - label: "The method implementation is available" + - label: "The model weights are available" + - label: "The training datasets are available" + + - type: textarea + id: additional-info + attributes: + label: Provide useful links for the implementation + description: | + Please provide information regarding the implementation, the weights, and the authors. + Please mention the authors by @gh-username if you're aware of their usernames. diff --git a/testbed/huggingface__trl/.github/PULL_REQUEST_TEMPLATE.md b/testbed/huggingface__trl/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..07f61a1a13b1a81c5d7cdda1a35192d5b46d9e27 --- /dev/null +++ b/testbed/huggingface__trl/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,32 @@ +# What does this PR do? + + + + + +Fixes # (issue) + + +## Before submitting +- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case). +- [ ] Did you read the [contributor guideline](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#create-a-pull-request), + Pull Request section? +- [ ] Was this discussed/approved via a GitHub issue? Please add a link + to it if that's the case. +- [ ] Did you make sure to update the documentation with your changes? Here are the + [documentation guidelines](https://github.com/huggingface/trl/tree/main/docs). +- [ ] Did you write any new necessary tests? + + +## Who can review? + +Anyone in the community is free to review the PR once the tests have passed. Feel free to tag +members/contributors who may be interested in your PR. \ No newline at end of file diff --git a/testbed/huggingface__trl/.github/workflows/build_documentation.yml b/testbed/huggingface__trl/.github/workflows/build_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..d66349f6c85d01a16070c56d848ae4afb0f66cf6 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/build_documentation.yml @@ -0,0 +1,19 @@ +name: Build documentation + +on: + push: + branches: + - main + - doc-builder* + - v*-release + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main + with: + commit_sha: ${{ github.sha }} + package: trl + version_tag_suffix: "" + custom_container: huggingface/transformers-doc-builder + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/testbed/huggingface__trl/.github/workflows/build_pr_documentation.yml b/testbed/huggingface__trl/.github/workflows/build_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..acc8d16d35d4222ceb84f88986ca5f9894f1a14a --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/build_pr_documentation.yml @@ -0,0 +1,18 @@ +name: Build PR Documentation + +on: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main + with: + commit_sha: ${{ github.event.pull_request.head.sha }} + pr_number: ${{ github.event.number }} + package: trl + version_tag_suffix: "" + custom_container: huggingface/transformers-doc-builder diff --git a/testbed/huggingface__trl/.github/workflows/clear_cache.yml b/testbed/huggingface__trl/.github/workflows/clear_cache.yml new file mode 100644 index 0000000000000000000000000000000000000000..b4f6681905893770be8b5f81ac4485ee4b90da86 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/clear_cache.yml @@ -0,0 +1,33 @@ +name: "Cleanup Cache" + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * *" + +jobs: + cleanup: + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Cleanup + run: | + gh extension install actions/gh-actions-cache + + REPO=${{ github.repository }} + + echo "Fetching list of cache key" + cacheKeysForPR=$(gh actions-cache list -R $REPO | cut -f 1 ) + + ## Setting this to not fail the workflow while deleting cache keys. + set +e + echo "Deleting caches..." + for cacheKey in $cacheKeysForPR + do + gh actions-cache delete $cacheKey -R $REPO --confirm + done + echo "Done" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/testbed/huggingface__trl/.github/workflows/docker-build.yml b/testbed/huggingface__trl/.github/workflows/docker-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..c30737294082125e3864a55be0dbec4e3449c910 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/docker-build.yml @@ -0,0 +1,95 @@ +name: Build Docker images (scheduled) + +on: + workflow_dispatch: + workflow_call: + schedule: + - cron: "0 1 * * *" + +concurrency: + group: docker-image-builds + cancel-in-progress: false + +env: + CI_SLACK_CHANNEL: ${{ secrets.CI_DOCKER_CHANNEL }} + +jobs: + trl-latest: + name: "Latest TRL GPU" + runs-on: ubuntu-latest + steps: + - name: Cleanup disk + run: | + sudo ls -l /usr/local/lib/ + sudo ls -l /usr/share/ + sudo du -sh /usr/local/lib/ + sudo du -sh /usr/share/ + sudo rm -rf /usr/local/lib/android + sudo rm -rf /usr/share/dotnet + sudo du -sh /usr/local/lib/ + sudo du -sh /usr/share/ + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + - name: Check out code + uses: actions/checkout@v4 + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + context: ./docker/trl-latest-gpu + push: true + tags: huggingface/trl-latest-gpu + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: 🤗 Results of the trl-latest-gpu Docker Image build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + trl-source: + name: "Latest TRL + HF ecosystem from source" + runs-on: ubuntu-latest + steps: + - name: Cleanup disk + run: | + sudo ls -l /usr/local/lib/ + sudo ls -l /usr/share/ + sudo du -sh /usr/local/lib/ + sudo du -sh /usr/share/ + sudo rm -rf /usr/local/lib/android + sudo rm -rf /usr/share/dotnet + sudo du -sh /usr/local/lib/ + sudo du -sh /usr/share/ + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + - name: Check out code + uses: actions/checkout@v4 + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + context: ./docker/trl-source-gpu + push: true + tags: huggingface/trl-source-gpu + + - name: Post to Slack + if: always() + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: 🤗 Results of the trl-source-gpu Docker Image build + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} diff --git a/testbed/huggingface__trl/.github/workflows/slow-tests.yml b/testbed/huggingface__trl/.github/workflows/slow-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b6e0698f1cceb514f0df74470927fc37a317ac6 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/slow-tests.yml @@ -0,0 +1,98 @@ +name: Slow tests (on push) + +on: + push: + branches: [ main ] + paths: + # Run only when python files are modified + - "trl/**.py" + - "examples/**.py" +env: + RUN_SLOW: "yes" + IS_GITHUB_CI: "1" + SLACK_API_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + +jobs: + run_all_tests_single_gpu: + strategy: + fail-fast: false + matrix: + docker-image-name: ["huggingface/trl-latest-gpu:latest", "huggingface/trl-source-gpu:latest"] + runs-on: + group: aws-g4dn-2xlarge + env: + CUDA_VISIBLE_DEVICES: "0" + TEST_TYPE: "single_gpu_${{ matrix.docker-image-name }}" + container: + image: ${{ matrix.docker-image-name }} + options: --gpus all --shm-size "16gb" -e NVIDIA_DISABLE_REQUIRE=true + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + - name: Pip install + run: | + source activate trl + pip install -e ".[test]" --no-deps + pip install pytest-reportlog parameterized + + - name: Run slow SFT tests on single GPU + if: always() + run: | + source activate trl + make slow_tests + + - name: Generate Report + if: always() + run: | + pip install slack_sdk tabulate + python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY + + + run_all_tests_multi_gpu: + strategy: + fail-fast: false + matrix: + docker-image-name: ["huggingface/trl-latest-gpu:latest", "huggingface/trl-source-gpu:latest"] + runs-on: + group: aws-g4dn-2xlarge + env: + CUDA_VISIBLE_DEVICES: "0,1" + TEST_TYPE: "multi_gpu_${{ matrix.docker-image-name }}" + container: + image: ${{ matrix.docker-image-name }} + options: --gpus all --shm-size "16gb" -e NVIDIA_DISABLE_REQUIRE=true + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + - name: Pip install + run: | + source activate trl + pip install -e ".[test]" --no-deps + pip install pytest-reportlog parameterized + + - name: Run slow SFT tests on Multi GPU + if: always() + run: | + source activate trl + make slow_tests + + - name: Run end-to-end examples tests on multi GPU + if: always() + run: | + source activate trl + pip install deepspeed + make test_examples + + - name: Generate Reports + if: always() + run: | + pip install slack_sdk tabulate + python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY + python scripts/log_example_reports.py --text_file_name temp_results_sft_tests.txt >> $GITHUB_STEP_SUMMARY + python scripts/log_example_reports.py --text_file_name temp_results_dpo_tests.txt >> $GITHUB_STEP_SUMMARY + rm *.txt diff --git a/testbed/huggingface__trl/.github/workflows/tests.yml b/testbed/huggingface__trl/.github/workflows/tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..5d58726d309beefeacbb6e7f147ee95cf65e2e51 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/tests.yml @@ -0,0 +1,163 @@ +name: Tests + +on: + push: + branches: [ main ] + pull_request: + paths: + # Run only when relevant files are modified + - ".github/**.yml" + - "examples/**.py" + - "scripts/**.py" + - "tests/**.py" + - "trl/**.py" + - "setup.py" + +env: + TQDM_DISABLE: 1 + CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }} + +jobs: + check_code_quality: + name: Check code quality + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + submodules: recursive + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: 3.12 + - uses: pre-commit/action@v3.0.1 + with: + extra_args: --all-files + + tests: + name: Tests + strategy: + matrix: + python-version: ['3.9', '3.10', '3.11', '3.12'] + os: ['ubuntu-latest', 'windows-latest'] + fail-fast: false + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: "pip" + cache-dependency-path: | + setup.py + requirements.txt + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install ".[dev]" + - name: Test with pytest + run: | + make test + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python ${{ matrix.python-version }} on ${{ matrix.os }} with lastest dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + tests_dev: + name: Tests with dev dependencies + runs-on: 'ubuntu-latest' + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: "pip" + cache-dependency-path: | + setup.py + requirements.txt + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -U git+https://github.com/huggingface/accelerate.git + python -m pip install -U git+https://github.com/huggingface/datasets.git + python -m pip install -U git+https://github.com/huggingface/transformers.git + python -m pip install ".[dev]" + - name: Test with pytest + run: | + make test + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python 3.12 on ubuntu-latest with dev dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + tests_wo_optional_deps: + name: Tests without optional dependencies + runs-on: 'ubuntu-latest' + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: "pip" + cache-dependency-path: | + setup.py + requirements.txt + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install ".[test]" + - name: Test with pytest + run: | + make test + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python 3.12 on ubuntu-latest without optional dependencies + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} + + tests_min_versions: + name: Tests with minimum versions + runs-on: 'ubuntu-latest' + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: "pip" + cache-dependency-path: | + setup.py + requirements.txt + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install accelerate==0.34.0 + python -m pip install datasets==2.21.0 + python -m pip install transformers==4.46.0 + python -m pip install ".[dev]" + - name: Test with pytest + run: | + make test + - name: Post to Slack + if: github.ref == 'refs/heads/main' && always() # Check if the branch is main + uses: huggingface/hf-workflows/.github/actions/post-slack@main + with: + slack_channel: ${{ env.CI_SLACK_CHANNEL }} + title: Results with Python 3.12 on ubuntu-latest with minimum versions + status: ${{ job.status }} + slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }} \ No newline at end of file diff --git a/testbed/huggingface__trl/.github/workflows/trufflehog.yml b/testbed/huggingface__trl/.github/workflows/trufflehog.yml new file mode 100644 index 0000000000000000000000000000000000000000..9cbbf6803724dacc4759b69d7002bb34831e5937 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/trufflehog.yml @@ -0,0 +1,15 @@ +on: + push: + +name: Secret Leaks + +jobs: + trufflehog: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Secret Scanning + uses: trufflesecurity/trufflehog@main diff --git a/testbed/huggingface__trl/.github/workflows/upload_pr_documentation.yml b/testbed/huggingface__trl/.github/workflows/upload_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ad2ba0e8de52699f60c2da7792dab742dd6f200 --- /dev/null +++ b/testbed/huggingface__trl/.github/workflows/upload_pr_documentation.yml @@ -0,0 +1,16 @@ +name: Upload PR Documentation + +on: + workflow_run: + workflows: ["Build PR Documentation"] + types: + - completed + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main + with: + package_name: trl + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} + comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} \ No newline at end of file diff --git a/testbed/huggingface__trl/.gitignore b/testbed/huggingface__trl/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..30ae97a160e3c3a809de484944a95c53e31048c2 --- /dev/null +++ b/testbed/huggingface__trl/.gitignore @@ -0,0 +1,148 @@ +*.bak +.gitattributes +.last_checked +.gitconfig +*.bak +*.log +*~ +~* +_tmp* +tmp* +tags + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode +*.swp + +# osx generated files +.DS_Store +.DS_Store? +.Trashes +ehthumbs.db +Thumbs.db +.idea + +# pytest +.pytest_cache + +# tools/trust-doc-nbs +docs_src/.last_checked + +# symlinks to fastai +docs_src/fastai +tools/fastai + +# link checker +checklink/cookies.txt + +# .gitconfig is now autogenerated +.gitconfig + +# wandb files +nbs/wandb/ +examples/notebooks/wandb/ +wandb/ + +# cli scripts that are symlinked from `examples/scripts` +trl/commands/scripts/ \ No newline at end of file diff --git a/testbed/huggingface__trl/.pre-commit-config.yaml b/testbed/huggingface__trl/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca4cb14ab9f23a2bfa95169c90ff76b09561fcf0 --- /dev/null +++ b/testbed/huggingface__trl/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.6.3 + hooks: + - id: ruff + types_or: [ python, pyi ] + args: [ --fix ] + - id: ruff-format + types_or: [ python, pyi ] + + # - repo: https://github.com/codespell-project/codespell + # rev: v2.1.0 + # hooks: + # - id: codespell + # args: + # - --ignore-words-list=nd,reacher,thist,ths,magent,ba + # - --skip=docs/css/termynal.css,docs/js/termynal.js diff --git a/testbed/huggingface__trl/CITATION.cff b/testbed/huggingface__trl/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..06b7d105d690bf0eaf45cc2d1a952ac247426d3d --- /dev/null +++ b/testbed/huggingface__trl/CITATION.cff @@ -0,0 +1,34 @@ +cff-version: 1.2.0 +title: 'TRL: Transformer Reinforcement Learning' +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Leandro + family-names: von Werra + - given-names: Younes + family-names: Belkada + - given-names: Lewis + family-names: Tunstall + - given-names: Edward + family-names: Beeching + - given-names: Tristan + family-names: Thrush + - given-names: Nathan + family-names: Lambert + - given-names: Shengyi + family-names: Huang + - given-names: Kashif + family-names: Rasul + - given-names: Quentin + family-names: Gallouédec +repository-code: 'https://github.com/huggingface/trl' +abstract: "With trl you can train transformer language models with Proximal Policy Optimization (PPO). The library is built on top of the transformers library by \U0001F917 Hugging Face. Therefore, pre-trained language models can be directly loaded via transformers. At this point, most decoder and encoder-decoder architectures are supported." +keywords: + - rlhf + - deep-learning + - pytorch + - transformers +license: Apache-2.0 +version: 0.12 diff --git a/testbed/huggingface__trl/CODE_OF_CONDUCT.md b/testbed/huggingface__trl/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..ef09fa1375a81440bf0733b659045453a5476c43 --- /dev/null +++ b/testbed/huggingface__trl/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations \ No newline at end of file diff --git a/testbed/huggingface__trl/CONTRIBUTING.md b/testbed/huggingface__trl/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..3e27528c1465cde499c90d3303082e52bbf90699 --- /dev/null +++ b/testbed/huggingface__trl/CONTRIBUTING.md @@ -0,0 +1,285 @@ +# How to contribute to TRL? + +Everyone is welcome to contribute, and we value everybody's contribution. Code +contributions are not the only way to help the community. Answering questions, helping +others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts +about the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our +[code of conduct](https://github.com/huggingface/trl/blob/main/CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).** + +## Ways to contribute + +There are several ways you can contribute to TRL: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Implement trainers for new post-training algorithms. +* Contribute to the examples or the documentation. + +If you don't know where to start, there is a special [Good First +Issue](https://github.com/huggingface/trl/contribute) listing. It will give you a list of +open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over. + +For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/trl/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀 + +> All contributions are equally valuable to the community. 🥰 + +Before you start contributing make sure you have installed all the dev tools: + +```bash +make dev +``` + +## Fixing outstanding issues + +If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request! + +## Submitting a bug-related issue or feature request + +Do your best to follow these guidelines when submitting a bug-related issue or a feature request. It will make it easier for us to come back to you quickly and with good feedback. + +### Did you find a bug? + +The TRL library is robust and reliable thanks to users who report the problems they encounter. + +Before you report an issue, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. + +Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it: + +* Your **OS type and version**, **Python**, **PyTorch**, **TRL** and **Transformers** versions. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s. +* The *full* traceback if an exception is raised. +* Attach any other additional information, like screenshots, you think may help. + +To get the OS and software versions automatically, run the following command: + +```bash +trl env +``` + +### Do you want a new feature? + +If there is a new feature you'd like to see in TRL, please open an issue and describe: + +1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community? + + Whatever it is, we'd love to hear about it! + +2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you. +3. Provide a *code snippet* that demonstrates the feature's usage. +4. If the feature is related to a paper, please include a link. + +If your issue is well written we're already 80% of the way there by the time you create it. + +## Do you want to implement a new trainer? + +New post-training methods are published frequently and those that satisfy the following criteria are good candidates to be integrated into TRL: + +* **Simplicity:** Does the new method achieve similar performance as prior methods, but with less complexity? A good example is Direct Preference Optimization (DPO) [[Rafailov et al, 2023]](https://huggingface.co/papers/2305.18290), which provided a simpler and compelling alternative to RLHF methods. +* **Efficiency:** Does the new method provide a significant improvement in training efficiency? A good example is Odds Ratio Preference Optimization (ORPO) [[Hong et al, 2023]](https://huggingface.co/papers/2403.07691), which utilizes a similar objective as DPO but requires half the GPU VRAM. + +Methods that only provide incremental improvements at the expense of added complexity or compute costs are unlikely to be included in TRL. + +If you want to implement a trainer for a new post-training method, first open an issue and provide the following information: + +* A short description of the method and a link to the paper. +* Link to the implementation if it is open-sourced. +* Link to model weights trained with the method if they are available. + +Based on the community and maintainer feedback, the next step will be to implement the trainer and config classes. See the following examples for inspiration: + +* Paired preference optimisation: [`dpo_trainer.py`](./trl/trainer/dpo_trainer.py) and [`dpo_config.py`](./trl/trainer/dpo_config.py) +* RL-based optimisation: [`rloo_trainer.py](./trl/trainer/rloo_trainer.py) and [`rloo_config.py](./trl/trainer/rloo_config.py) +* Online optimisation: [`online_dpo_trainer.py`](./trl/trainer/online_dpo_trainer.py) and [`online_dpo_config.py`](./trl/trainer/online_dpo_config.py) + +## Do you want to add documentation? + +We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved, such as typos, dead links, and any missing, unclear, or inaccurate content... We'll be happy to make the changes or help you contribute if you're interested! + +## Submitting a pull request (PR) + +Before writing code, we strongly advise you to search through the existing PRs or +issues to make sure that nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to be able to contribute to +TRL. `git` is not the easiest tool to use but it has the greatest +manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +Follow these steps to start contributing: + +1. Fork the [repository](https://github.com/huggingface/trl) by + clicking on the 'Fork' button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote. The following command + assumes you have your public SSH key uploaded to GitHub. See the following guide for more + [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository). + + ```bash + $ git clone git@github.com:/trl.git + $ cd trl + $ git remote add upstream https://github.com/huggingface/trl.git + ``` + +3. Create a new branch to hold your development changes, and do this for every new PR you work on. + + Start by synchronizing your `main` branch with the `upstream/main` branch (more details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)): + + ```bash + $ git checkout main + $ git fetch upstream + $ git merge upstream/main + ``` + + Once your `main` branch is synchronized, create a new branch from it: + + ```bash + $ git checkout -b a-descriptive-name-for-my-changes + ``` + + **Do not** work on the `main` branch. + +4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library: + + ```bash + $ make dev + ``` + + (If TRL was already installed in the virtual environment, remove + it with `pip uninstall trl` before reinstalling it.) + + Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using + the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers). + +5. Develop the features on your branch. + + As you work on the features, you should make sure that the test suite + passes. You should run the tests impacted by your changes like this (see + below an explanation regarding the environment variable): + + ```bash + $ pytest tests/.py + ``` + + > For the following commands leveraging the `make` utility, we recommend using the WSL system when running on + > Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about). + + You can also run the full suite with the following command. + + ```bash + $ make test + ``` + + TRL relies on `ruff` for maintaining consistent code formatting across its source files. Before submitting any PR, you should apply automatic style corrections and run code verification checks. + + We provide a `precommit` target in the `Makefile` that simplifies this process by running all required checks and optimizations on only the files modified by your PR. + + To apply these checks and corrections in one step, use: + + ```bash + $ make precommit + ``` + + This command runs the following: + - Executes `pre-commit` hooks to automatically fix style issues with `ruff` and other tools. + - Runs additional scripts such as adding copyright information. + + If you prefer to apply the style corrections separately or review them individually, the `pre-commit` hook will handle the formatting for the files in question. + + Once you're happy with your changes, add changed files using `git add` and + make a commit with `git commit` to record your changes locally: + + ```bash + $ git add modified_file.py + $ git commit + ``` + + Please write [good commit messages](https://chris.beams.io/posts/git-commit/). + + It is a good idea to sync your copy of the code with the original + repository regularly. This way you can quickly account for changes: + + ```bash + $ git fetch upstream + $ git rebase upstream/main + ``` + + Push the changes to your account using: + + ```bash + $ git push -u origin a-descriptive-name-for-my-changes + ``` + +6. Once you are satisfied (**and the checklist below is happy too**), go to the + webpage of your fork on GitHub. Click on 'Pull request' to send your changes + to the project maintainers for review. + +7. It's ok if maintainers ask you for changes. It happens to core contributors too! To ensure everyone can review your changes in the pull request, work on your local branch and push the updates to your fork. They will automatically appear in the pull request. + + +### Checklist + +1. The title of your pull request should be a summary of its contribution; +2. If your pull request addresses an issue, please mention the issue number in + the pull request description to make sure they are linked (and people + consulting the issue know you are working on it); +3. To indicate a work in progress please prefix the title with `[WIP]`, or mark + the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate + it from PRs ready to be merged; +4. Make sure existing tests pass; +5. Add high-coverage tests. No quality testing = no merge. + + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests folder](https://github.com/huggingface/trl/tree/main/tests). + +We use `pytest` to run the tests. From the root of the +repository here's how to run tests with `pytest` for the library: + +```bash +$ python -m pytest -sv ./tests +``` + +That's how `make test` is implemented (without the `pip install` line)! + +You can specify a smaller set of tests to test only the feature +you're working on. + +### Deprecation and Backward Compatibility + +Our approach to deprecation and backward compatibility is flexible and based on the feature’s usage and impact. Each deprecation is carefully evaluated, aiming to balance innovation with user needs. + +When a feature or component is marked for deprecation, its use will emit a warning message. This warning will include: + +- **Transition Guidance**: Instructions on how to migrate to the alternative solution or replacement. +- **Removal Version**: The target version when the feature will be removed, providing users with a clear timeframe to transition. + +Example: + + ```python + warnings.warn( + "The `Trainer.foo` method is deprecated and will be removed in version 0.14.0. " + "Please use the `Trainer.bar` class instead.", + FutureWarning, + ) + ``` + +The deprecation and removal schedule is based on each feature's usage and impact, with examples at two extremes: + +- **Experimental or Low-Use Features**: For a feature that is experimental or has limited usage, backward compatibility may not be maintained between releases. Users should therefore anticipate potential breaking changes from one version to the next. + +- **Widely-Used Components**: For a feature with high usage, we aim for a more gradual transition period of approximately **5 months**, generally scheduling deprecation around **5 minor releases** after the initial warning. + +These examples represent the two ends of a continuum. The specific timeline for each feature will be determined individually, balancing innovation with user stability needs. diff --git a/testbed/huggingface__trl/LICENSE b/testbed/huggingface__trl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/testbed/huggingface__trl/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/testbed/huggingface__trl/MANIFEST.in b/testbed/huggingface__trl/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..26496e93f1607e73b8cbb66e56cafb46b9236829 --- /dev/null +++ b/testbed/huggingface__trl/MANIFEST.in @@ -0,0 +1,6 @@ +include settings.ini +include LICENSE +include CONTRIBUTING.md +include README.md +recursive-exclude * __pycache__ +include trl/templates/*.md \ No newline at end of file diff --git a/testbed/huggingface__trl/Makefile b/testbed/huggingface__trl/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..704cacbff28986f1ae83bff1ea10e797be1f33d0 --- /dev/null +++ b/testbed/huggingface__trl/Makefile @@ -0,0 +1,39 @@ +.PHONY: test precommit common_tests slow_tests test_examples tests_gpu + +check_dirs := examples tests trl + +ACCELERATE_CONFIG_PATH = `pwd`/examples/accelerate_configs +COMMAND_FILES_PATH = `pwd`/commands + + +dev: + @if [ -L "$(pwd)/trl/commands/scripts" ]; then unlink "$(pwd)/trl/commands/scripts"; fi + @if [ -e "$(pwd)/trl/commands/scripts" ] && [ ! -L "$(pwd)/trl/commands/scripts" ]; then rm -rf "$(pwd)/trl/commands/scripts"; fi + pip install -e ".[dev]" + ln -s `pwd`/examples/scripts/ `pwd`/trl/commands + +test: + python -m pytest -n auto --dist=loadfile -s -v --reruns 5 --reruns-delay 1 --only-rerun '(OSError|Timeout|HTTPError.*502|HTTPError.*504||not less than or equal to 0.01)' ./tests/ + +precommit: + pre-commit run --all-files + python scripts/add_copyrights.py + +tests_gpu: + python -m pytest tests/test_* $(if $(IS_GITHUB_CI),--report-log "common_tests.log",) + +slow_tests: + python -m pytest tests/slow/test_* $(if $(IS_GITHUB_CI),--report-log "slow_tests.log",) + +test_examples: + touch temp_results_sft_tests.txt + for file in $(ACCELERATE_CONFIG_PATH)/*.yaml; do \ + TRL_ACCELERATE_CONFIG=$${file} bash $(COMMAND_FILES_PATH)/run_sft.sh; \ + echo $$?','$${file} >> temp_results_sft_tests.txt; \ + done + + touch temp_results_dpo_tests.txt + for file in $(ACCELERATE_CONFIG_PATH)/*.yaml; do \ + TRL_ACCELERATE_CONFIG=$${file} bash $(COMMAND_FILES_PATH)/run_dpo.sh; \ + echo $$?','$${file} >> temp_results_dpo_tests.txt; \ + done diff --git a/testbed/huggingface__trl/README.md b/testbed/huggingface__trl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f9895fe2ebdb115d4defcac68142626d48cdeba2 --- /dev/null +++ b/testbed/huggingface__trl/README.md @@ -0,0 +1,219 @@ +# TRL - Transformer Reinforcement Learning + +
+TRL Banner +
+ +

+ +

+

A comprehensive library to post-train foundation models

+

+ +

+ License + Documentation + GitHub release +

+ +## Overview + +TRL is a cutting-edge library designed for post-training foundation models using advanced techniques like Supervised Fine-Tuning (SFT), Proximal Policy Optimization (PPO), and Direct Preference Optimization (DPO). Built on top of the [🤗 Transformers](https://github.com/huggingface/transformers) ecosystem, TRL supports a variety of model architectures and modalities, and can be scaled-up across various hardware setups. + +## Highlights + +- **Efficient and scalable**: + - Leverages [🤗 Accelerate](https://github.com/huggingface/accelerate) to scale from single GPU to multi-node clusters using methods like DDP and DeepSpeed. + - Full integration with [`PEFT`](https://github.com/huggingface/peft) enables training on large models with modest hardware via quantization and LoRA/QLoRA. + - Integrates [Unsloth](https://github.com/unslothai/unsloth) for accelerating training using optimized kernels. + +- **Command Line Interface (CLI)**: A simple interface lets you fine-tune and interact with models without needing to write code. + +- **Trainers**: Various fine-tuning methods are easily accessible via trainers like [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer), [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer), [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer), [`ORPOTrainer`](https://huggingface.co/docs/trl/orpo_trainer) and more. + +- **AutoModels**: Use pre-defined model classes like [`AutoModelForCausalLMWithValueHead`](https://huggingface.co/docs/trl/models#trl.AutoModelForCausalLMWithValueHead) to simplify reinforcement learning (RL) with LLMs. + +## Installation + +### Python Package + +Install the library using `pip`: + +```bash +pip install trl +``` + +### From source + +If you want to use the latest features before an official release, you can install TRL from source: + +```bash +pip install git+https://github.com/huggingface/trl.git +``` + +### Repository + +If you want to use the examples you can clone the repository with the following command: + +```bash +git clone https://github.com/huggingface/trl.git +``` + +## Command Line Interface (CLI) + +You can use the TRL Command Line Interface (CLI) to quickly get started with Supervised Fine-tuning (SFT) and Direct Preference Optimization (DPO), or vibe check your model with the chat CLI: + +**SFT:** + +```bash +trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \ + --dataset_name trl-lib/Capybara \ + --output_dir Qwen2.5-0.5B-SFT +``` + +**DPO:** + +```bash +trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ + --dataset_name argilla/Capybara-Preferences \ + --output_dir Qwen2.5-0.5B-DPO +``` + +**Chat:** + +```bash +trl chat --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct +``` + +Read more about CLI in the [relevant documentation section](https://huggingface.co/docs/trl/main/en/clis) or use `--help` for more details. + +## How to use + +For more flexibility and control over training, TRL provides dedicated trainer classes to post-train language models or PEFT adapters on a custom dataset. Each trainer in TRL is a light wrapper around the 🤗 Transformers trainer and natively supports distributed training methods like DDP, DeepSpeed ZeRO, and FSDP. + +### `SFTTrainer` + +Here is a basic example of how to use the `SFTTrainer`: + +```python +from trl import SFTConfig, SFTTrainer +from datasets import load_dataset + +dataset = load_dataset("trl-lib/Capybara", split="train") + +training_args = SFTConfig(output_dir="Qwen/Qwen2.5-0.5B-SFT") +trainer = SFTTrainer( + args=training_args, + model="Qwen/Qwen2.5-0.5B", + train_dataset=dataset, +) +trainer.train() +``` + +### `RewardTrainer` + +Here is a basic example of how to use the `RewardTrainer`: + +```python +from trl import RewardConfig, RewardTrainer +from datasets import load_dataset +from transformers import AutoModelForSequenceClassification, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +model = AutoModelForSequenceClassification.from_pretrained( + "Qwen/Qwen2.5-0.5B-Instruct", num_labels=1 +) +model.config.pad_token_id = tokenizer.pad_token_id + +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +training_args = RewardConfig(output_dir="Qwen2.5-0.5B-Reward", per_device_train_batch_size=2) +trainer = RewardTrainer( + args=training_args, + model=model, + processing_class=tokenizer, + train_dataset=dataset, +) +trainer.train() +``` + +### `RLOOTrainer` + +`RLOOTrainer` implements a [REINFORCE-style optimization](https://huggingface.co/papers/2402.14740) for RLHF that is more performant and memory-efficient than PPO. Here is a basic example of how to use the `RLOOTrainer`: + +```python +from trl import RLOOConfig, RLOOTrainer, apply_chat_template +from datasets import load_dataset +from transformers import ( + AutoModelForCausalLM, + AutoModelForSequenceClassification, + AutoTokenizer, +) + +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +reward_model = AutoModelForSequenceClassification.from_pretrained( + "Qwen/Qwen2.5-0.5B-Instruct", num_labels=1 +) +ref_policy = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +policy = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") + +dataset = load_dataset("trl-lib/ultrafeedback-prompt") +dataset = dataset.map(apply_chat_template, fn_kwargs={"tokenizer": tokenizer}) +dataset = dataset.map(lambda x: tokenizer(x["prompt"]), remove_columns="prompt") + +training_args = RLOOConfig(output_dir="Qwen2.5-0.5B-RL") +trainer = RLOOTrainer( + config=training_args, + processing_class=tokenizer, + policy=policy, + ref_policy=ref_policy, + reward_model=reward_model, + train_dataset=dataset["train"], + eval_dataset=dataset["test"], +) +trainer.train() +``` + +### `DPOTrainer` + +`DPOTrainer` implements the popular [Direct Preference Optimization (DPO) algorithm](https://huggingface.co/papers/2305.18290) that was used to post-train Llama 3 and many other models. Here is a basic example of how to use the `DPOTrainer`: + +```python +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer +from trl import DPOConfig, DPOTrainer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") +training_args = DPOConfig(output_dir="Qwen2.5-0.5B-DPO") +trainer = DPOTrainer(model=model, args=training_args, train_dataset=dataset, processing_class=tokenizer) +trainer.train() +``` + +## Development + +If you want to contribute to `trl` or customize it to your needs make sure to read the [contribution guide](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) and make sure you make a dev install: + +```bash +git clone https://github.com/huggingface/trl.git +cd trl/ +make dev +``` + +## Citation + +```bibtex +@misc{vonwerra2022trl, + author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallouédec}, + title = {TRL: Transformer Reinforcement Learning}, + year = {2020}, + publisher = {GitHub}, + journal = {GitHub repository}, + howpublished = {\url{https://github.com/huggingface/trl}} +} +``` + +## License + +This repository's source code is available under the [Apache-2.0 License](LICENSE). diff --git a/testbed/huggingface__trl/commands/run_dpo.sh b/testbed/huggingface__trl/commands/run_dpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..c265a294e331be00c6ad01e0f04c11870121a453 --- /dev/null +++ b/testbed/huggingface__trl/commands/run_dpo.sh @@ -0,0 +1,58 @@ +#!/bin/bash +# This script runs an SFT example end-to-end on a tiny model using different possible configurations +# but defaults to QLoRA + PEFT +OUTPUT_DIR="test_dpo/" +MODEL_NAME="trl-internal-testing/tiny-random-LlamaForCausalLM" +DATASET_NAME="trl-internal-testing/hh-rlhf-helpful-base-trl-style" +MAX_STEPS=5 +BATCH_SIZE=2 +SEQ_LEN=128 + +# Handle extra arguments in case one passes accelerate configs. +EXTRA_ACCELERATE_ARGS="" +EXTRA_TRAINING_ARGS="""--use_peft \ + --load_in_4bit +""" + +# This is a hack to get the number of available GPUs +NUM_GPUS=2 + +if [[ "${TRL_ACCELERATE_CONFIG}" == "" ]]; then + EXTRA_ACCELERATE_ARGS="" +else + EXTRA_ACCELERATE_ARGS="--config_file $TRL_ACCELERATE_CONFIG" + # For DeepSpeed configs we need to set the `--fp16` flag to comply with our configs exposed + # on `examples/accelerate_configs` and our runners do not support bf16 mixed precision training. + if [[ $TRL_ACCELERATE_CONFIG == *"deepspeed"* ]]; then + EXTRA_TRAINING_ARGS="--fp16" + else + echo "Keeping QLoRA + PEFT" + fi +fi + + +CMD=""" +accelerate launch $EXTRA_ACCELERATE_ARGS \ + --num_processes $NUM_GPUS \ + --mixed_precision 'fp16' \ + `pwd`/examples/scripts/dpo.py \ + --model_name_or_path $MODEL_NAME \ + --dataset_name $DATASET_NAME \ + --output_dir $OUTPUT_DIR \ + --max_steps $MAX_STEPS \ + --per_device_train_batch_size $BATCH_SIZE \ + --max_length $SEQ_LEN \ + $EXTRA_TRAINING_ARGS +""" + +echo "Starting program..." + +{ # try + echo $CMD + eval "$CMD" +} || { # catch + # save log for exception + echo "Operation Failed!" + exit 1 +} +exit 0 diff --git a/testbed/huggingface__trl/commands/run_sft.sh b/testbed/huggingface__trl/commands/run_sft.sh new file mode 100644 index 0000000000000000000000000000000000000000..6983143c0efb513a932589e5d01f3cc5a6878ba4 --- /dev/null +++ b/testbed/huggingface__trl/commands/run_sft.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# This script runs an SFT example end-to-end on a tiny model using different possible configurations +# but defaults to QLoRA + PEFT +OUTPUT_DIR="test_sft/" +MODEL_NAME="trl-internal-testing/tiny-random-LlamaForCausalLM" +DATASET_NAME="stanfordnlp/imdb" +MAX_STEPS=5 +BATCH_SIZE=2 +SEQ_LEN=128 + + +# Handle extra arguments in case one passes accelerate configs. +EXTRA_ACCELERATE_ARGS="" +EXTRA_TRAINING_ARGS="""--use_peft \ + --load_in_4bit +""" + +# Set your number of GPUs here +NUM_GPUS=2 + +if [[ "${TRL_ACCELERATE_CONFIG}" == "" ]]; then + EXTRA_ACCELERATE_ARGS="" +else + EXTRA_ACCELERATE_ARGS="--config_file $TRL_ACCELERATE_CONFIG" + # For DeepSpeed configs we need to set the `--fp16` flag to comply with our configs exposed + # on `examples/accelerate_configs` and our runners do not support bf16 mixed precision training. + if [[ $TRL_ACCELERATE_CONFIG == *"deepspeed"* ]]; then + EXTRA_TRAINING_ARGS="--fp16" + else + echo "Keeping QLoRA + PEFT" + fi +fi + + +CMD=""" +accelerate launch $EXTRA_ACCELERATE_ARGS \ + --num_processes $NUM_GPUS \ + --mixed_precision 'fp16' \ + `pwd`/examples/scripts/sft.py \ + --model_name $MODEL_NAME \ + --dataset_name $DATASET_NAME \ + --output_dir $OUTPUT_DIR \ + --max_steps $MAX_STEPS \ + --per_device_train_batch_size $BATCH_SIZE \ + --max_seq_length $SEQ_LEN \ + $EXTRA_TRAINING_ARGS +""" + +echo "Starting program..." + +{ # try + echo $CMD + eval "$CMD" +} || { # catch + # save log for exception + echo "Operation Failed!" + exit 1 +} +exit 0 diff --git a/testbed/huggingface__trl/docker/trl-latest-gpu/Dockerfile b/testbed/huggingface__trl/docker/trl-latest-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6c53033961932a36bc551f94e7307079903fb944 --- /dev/null +++ b/testbed/huggingface__trl/docker/trl-latest-gpu/Dockerfile @@ -0,0 +1,66 @@ +# Builds GPU docker image of PyTorch +# Uses multi-staged approach to reduce size +# Stage 1 +# Use base conda image to reduce time +FROM continuumio/miniconda3:latest AS compile-image +# Specify py version +ENV PYTHON_VERSION=3.10 +# Install apt libs - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile +RUN apt-get update && \ + apt-get install -y curl git wget software-properties-common git-lfs && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +# Install audio-related libraries +RUN apt-get update && \ + apt install -y ffmpeg + +RUN apt install -y libsndfile1-dev +RUN git lfs install + +# Create our conda env - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile +RUN conda create --name trl python=${PYTHON_VERSION} ipython jupyter pip +RUN python3 -m pip install --no-cache-dir --upgrade pip + +# Below is copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile +# We don't install pytorch here yet since CUDA isn't available +# instead we use the direct torch wheel +ENV PATH /opt/conda/envs/trl/bin:$PATH +# Activate our bash shell +RUN chsh -s /bin/bash +SHELL ["/bin/bash", "-c"] + +# Stage 2 +FROM nvidia/cuda:12.2.2-devel-ubuntu22.04 AS build-image +COPY --from=compile-image /opt/conda /opt/conda +ENV PATH /opt/conda/bin:$PATH + +RUN chsh -s /bin/bash +SHELL ["/bin/bash", "-c"] +RUN source activate trl && \ + python3 -m pip install --no-cache-dir bitsandbytes optimum auto-gptq + +# Install apt libs +RUN apt-get update && \ + apt-get install -y curl git wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +# Activate the conda env and install transformers + accelerate from source +RUN source activate trl && \ + python3 -m pip install -U --no-cache-dir \ + librosa \ + "soundfile>=0.12.1" \ + scipy \ + transformers \ + accelerate \ + peft \ + trl[test]@git+https://github.com/huggingface/trl + +RUN source activate trl && \ + pip freeze | grep trl + +RUN echo "source activate trl" >> ~/.profile + +# Activate the virtualenv +CMD ["/bin/bash"] \ No newline at end of file diff --git a/testbed/huggingface__trl/docker/trl-source-gpu/Dockerfile b/testbed/huggingface__trl/docker/trl-source-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..21e72504373c5ada24d2eb608eaf32042faae06d --- /dev/null +++ b/testbed/huggingface__trl/docker/trl-source-gpu/Dockerfile @@ -0,0 +1,66 @@ +# Builds GPU docker image of PyTorch +# Uses multi-staged approach to reduce size +# Stage 1 +# Use base conda image to reduce time +FROM continuumio/miniconda3:latest AS compile-image +# Specify py version +ENV PYTHON_VERSION=3.10 +# Install apt libs - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile +RUN apt-get update && \ + apt-get install -y curl git wget software-properties-common git-lfs && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +# Install audio-related libraries +RUN apt-get update && \ + apt install -y ffmpeg + +RUN apt install -y libsndfile1-dev +RUN git lfs install + +# Create our conda env - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile +RUN conda create --name trl python=${PYTHON_VERSION} ipython jupyter pip +RUN python3 -m pip install --no-cache-dir --upgrade pip + +# Below is copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile +# We don't install pytorch here yet since CUDA isn't available +# instead we use the direct torch wheel +ENV PATH /opt/conda/envs/trl/bin:$PATH +# Activate our bash shell +RUN chsh -s /bin/bash +SHELL ["/bin/bash", "-c"] + +# Stage 2 +FROM nvidia/cuda:12.2.2-devel-ubuntu22.04 AS build-image +COPY --from=compile-image /opt/conda /opt/conda +ENV PATH /opt/conda/bin:$PATH + +RUN chsh -s /bin/bash +SHELL ["/bin/bash", "-c"] +RUN source activate trl && \ + python3 -m pip install --no-cache-dir bitsandbytes optimum auto-gptq + +# Install apt libs +RUN apt-get update && \ + apt-get install -y curl git wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +# Activate the conda env and install transformers + accelerate from source +RUN source activate trl && \ + python3 -m pip install -U --no-cache-dir \ + librosa \ + "soundfile>=0.12.1" \ + scipy \ + git+https://github.com/huggingface/transformers \ + git+https://github.com/huggingface/accelerate \ + git+https://github.com/huggingface/peft \ + trl[test]@git+https://github.com/huggingface/trl + +RUN source activate trl && \ + pip freeze | grep transformers + +RUN echo "source activate trl" >> ~/.profile + +# Activate the virtualenv +CMD ["/bin/bash"] \ No newline at end of file diff --git a/testbed/huggingface__trl/docs/source/_toctree.yml b/testbed/huggingface__trl/docs/source/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3d39ba445c6b7768ca2cd95f4da452e4292c976 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/_toctree.yml @@ -0,0 +1,84 @@ +- sections: + - local: index + title: TRL + - local: installation + title: Installation + - local: quickstart + title: Quickstart + - local: clis + title: Get started with Command Line Interfaces (CLIs) + - local: dataset_formats + title: Dataset Formats + - local: how_to_train + title: PPO Training FAQ + - local: use_model + title: Use Trained Models + - local: customization + title: Customize the Training + - local: logging + title: Understanding Logs + title: Get started +- sections: + - sections: # Sort alphabetically + - local: alignprop_trainer + title: AlignProp + - local: bco_trainer + title: BCO + - local: cpo_trainer + title: CPO + - local: ddpo_trainer + title: DDPO + - local: dpo_trainer + title: DPO + - local: online_dpo_trainer + title: Online DPO + - local: gkd_trainer + title: GKD + - local: kto_trainer + title: KTO + - local: nash_md_trainer + title: Nash-MD + - local: orpo_trainer + title: ORPO + - local: ppo_trainer + title: PPO + - local: reward_trainer + title: Reward + - local: rloo_trainer + title: RLOO + - local: sft_trainer + title: SFT + - local: iterative_sft_trainer + title: Iterative SFT + - local: xpo_trainer + title: XPO + title: Trainers + - local: models + title: Model Classes + - local: best_of_n + title: Best of N Sampling + - local: judges + title: Judges + - local: callbacks + title: Callbacks + - local: data_utils + title: Data Utilities + - local: text_environments + title: Text Environments + title: API +- sections: + - local: example_overview + title: Example Overview + - local: sentiment_tuning + title: Sentiment Tuning + - local: lora_tuning_peft + title: Training with PEFT + - local: detoxifying_a_lm + title: Detoxifying a Language Model + - local: using_llama_models + title: Training StackLlama + - local: learning_tools + title: Learning to Use Tools + - local: multi_adapter_rl + title: Multi Adapter RLHF + title: Examples diff --git a/testbed/huggingface__trl/docs/source/bco_trainer.mdx b/testbed/huggingface__trl/docs/source/bco_trainer.mdx new file mode 100644 index 0000000000000000000000000000000000000000..c23365cc00196637f233b9e31fe22411b46f3b0e --- /dev/null +++ b/testbed/huggingface__trl/docs/source/bco_trainer.mdx @@ -0,0 +1,100 @@ +# BCO Trainer + +[![](https://img.shields.io/badge/All_models-BCO-blue)](https://huggingface.co/models?other=bco,trl) + +TRL supports the Binary Classifier Optimization (BCO). +The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. +For a full example have a look at [`examples/scripts/bco.py`]. + +## Expected dataset type + +The [`BCOTrainer`] requires an [unpaired preference dataset](dataset_formats#unpaired-preference). +The [`BCOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Expected model format +The BCO trainer expects a model of `AutoModelForCausalLM`, compared to PPO that expects `AutoModelForCausalLMWithValueHead` for the value function. + +## Using the `BCOTrainer` + +For a detailed example have a look at the `examples/scripts/bco.py` script. At a high level we need to initialize the `BCOTrainer` with a `model` we wish to train and a reference `ref_model` which we will use to calculate the implicit rewards of the preferred and rejected response. + +The `beta` refers to the hyperparameter of the implicit reward, and the dataset contains the 3 entries listed above. Note that the `model` and `ref_model` need to have the same architecture (ie decoder only or encoder-decoder). + + + +```py +training_args = BCOConfig( + beta=0.1, +) + +bco_trainer = BCOTrainer( + model, + model_ref, + args=training_args, + train_dataset=train_dataset, + processing_class=tokenizer, +) +``` +After this one can then call: + +```py +bco_trainer.train() +``` + +## Underlying Distribution matching (UDM) + +In practical scenarios, the thumbs-up and thumbs-down datasets are likely to have divergent underlying distributions of prompts. +Consider an LLM deployed for user feedback: if the model excels in writing tasks but underperforms in coding, the thumbs-up dataset will be dominated by writing-related prompts, while the thumbs-down dataset will contain mostly coding-related prompts. +If the prompts in your desired and undesired datasets differ a lot, it is useful to enable UDM. + +Choose an embedding model and tokenizer: + +```py +embedding_model = AutoModel.from_pretrained(your_model_id) +embedding_tokenizer = AutoTokenizer.from_pretrained(your_model_id) + +# customize this function depending on your embedding model +def embed_prompt(input_ids, attention_mask, model): + outputs = model(input_ids=input_ids, attention_mask=attention_mask) + return outputs.last_hidden_state.mean(dim=1) + +embedding_model = Accelerator().prepare_model(self.embedding_model) +embedding_func = partial(embed_prompt, model=embedding_model) +``` + +Set `prompt_sample_size` to defined how many prompts are selected to train the UDM classifier and start the training with the provided embedding function: + +```py +training_args = BCOConfig( + beta=0.1, + prompt_sample_size=512, +) + +bco_trainer = BCOTrainer( + model, + model_ref, + args=training_args, + train_dataset=train_dataset, + processing_class=tokenizer, + embedding_func=embedding_func, + embedding_tokenizer=self.embedding_tokenizer, +) + +bco_trainer.train() +``` + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. MixtralConfig). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: 0.001). + +## BCOTrainer + +[[autodoc]] BCOTrainer + +## BCOConfig + +[[autodoc]] BCOConfig \ No newline at end of file diff --git a/testbed/huggingface__trl/docs/source/best_of_n.mdx b/testbed/huggingface__trl/docs/source/best_of_n.mdx new file mode 100644 index 0000000000000000000000000000000000000000..9dd56aba2ce4818ffcf09f4e5354c825d63000e1 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/best_of_n.mdx @@ -0,0 +1,72 @@ +# Best of N sampling: Alternative ways to get better model output without RL based fine-tuning + +Within the extras module is the `best-of-n` sampler class that serves as an alternative method of generating better model output. +As to how it fares against the RL based fine-tuning, please look in the `examples` directory for a comparison example + +## Usage + +To get started quickly, instantiate an instance of the class with a model, a length sampler, a tokenizer and a callable that serves as a proxy reward pipeline that outputs reward scores for input queries + +```python + +from transformers import pipeline, AutoTokenizer +from trl import AutoModelForCausalLMWithValueHead +from trl.core import LengthSampler +from trl.extras import BestOfNSampler + +ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(ref_model_name) +reward_pipe = pipeline("sentiment-analysis", model=reward_model, device=device) +tokenizer = AutoTokenizer.from_pretrained(ref_model_name) +tokenizer.pad_token = tokenizer.eos_token + + +# callable that takes a list of raw text and returns a list of corresponding reward scores +def queries_to_scores(list_of_strings): + return [output["score"] for output in reward_pipe(list_of_strings)] + +best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler) + + +``` + +And assuming you have a list/tensor of tokenized queries, you can generate better output by calling the `generate` method + +```python + +best_of_n.generate(query_tensors, device=device, **gen_kwargs) + +``` +The default sample size is 4, but you can change it at the time of instance initialization like so + +```python + +best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, sample_size=8) + +``` + +The default output is the result of taking the top scored output for each query, but you can change it to top 2 and so on by passing the `n_candidates` argument at the time of instance initialization + +```python + +best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, n_candidates=2) + +``` + +There is the option of setting the generation settings (like `temperature`, `pad_token_id`) at the time of instance creation as opposed to when calling the `generate` method. +This is done by passing a `GenerationConfig` from the `transformers` library at the time of initialization + +```python + +from transformers import GenerationConfig + +generation_config = GenerationConfig(min_length= -1, top_k=0.0, top_p= 1.0, do_sample= True, pad_token_id=tokenizer.eos_token_id) + +best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, generation_config=generation_config) + +best_of_n.generate(query_tensors, device=device) + +``` + +Furthermore, at the time of initialization you can set the seed to control repeatability of the generation process and the number of samples to generate for each query + + diff --git a/testbed/huggingface__trl/docs/source/clis.mdx b/testbed/huggingface__trl/docs/source/clis.mdx new file mode 100644 index 0000000000000000000000000000000000000000..92fc11a3aa212b8de9e66062454c0133e112a1c4 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/clis.mdx @@ -0,0 +1,171 @@ +# Command Line Interfaces (CLIs) + +You can use TRL to fine-tune your Language Model with Supervised Fine-Tuning (SFT) or Direct Policy Optimization (DPO) or even chat with your model using the TRL CLIs. + +Currently supported CLIs are: + +- `trl sft`: fine-tune a LLM on a text/instruction dataset +- `trl dpo`: fine-tune a LLM with DPO on a preference dataset +- `trl chat`: quickly spin up a LLM fine-tuned for chatting +- `trl env`: get the system information + +## Fine-tuning with the CLI + +Before getting started, pick up a Language Model from Hugging Face Hub. Supported models can be found with the filter "text-generation" within models. Also make sure to pick up a relevant dataset for your task. + +Before using the `sft` or `dpo` commands make sure to run: +```bash +accelerate config +``` +and pick up the right configuration for your training setup (single / multi-GPU, DeepSpeed, etc.). Make sure to complete all steps of `accelerate config` before running any CLI command. + +We also recommend you passing a YAML config file to configure your training protocol. Below is a simple example of a YAML file that you can use for training your models with `trl sft` command. + +```yaml +model_name_or_path: + trl-internal-testing/tiny-random-LlamaForCausalLM +dataset_name: + stanfordnlp/imdb +report_to: + none +learning_rate: + 0.0001 +lr_scheduler_type: + cosine +``` + +Save that config in a `.yaml` and get started immediately! An example CLI config is available as `examples/cli_configs/example_config.yaml`. Note you can overwrite the arguments from the config file by explicitly passing them to the CLI, e.g. from the root folder: + +```bash +trl sft --config examples/cli_configs/example_config.yaml --output_dir test-trl-cli --lr_scheduler_type cosine_with_restarts +``` + +Will force-use `cosine_with_restarts` for `lr_scheduler_type`. + +### Supported Arguments + +We do support all arguments from `transformers.TrainingArguments`, for loading your model, we support all arguments from `~trl.ModelConfig`: + +[[autodoc]] ModelConfig + +You can pass any of these arguments either to the CLI or the YAML file. + +### Supervised Fine-tuning (SFT) + +Follow the basic instructions above and run `trl sft --output_dir <*args>`: + +```bash +trl sft --model_name_or_path facebook/opt-125m --dataset_name stanfordnlp/imdb --output_dir opt-sft-imdb +``` + +The SFT CLI is based on the `examples/scripts/sft.py` script. + +### Direct Policy Optimization (DPO) + +To use the DPO CLI, you need to have a dataset in the TRL format such as + +* TRL's Anthropic HH dataset: https://huggingface.co/datasets/trl-internal-testing/hh-rlhf-helpful-base-trl-style +* TRL's OpenAI TL;DR summarization dataset: https://huggingface.co/datasets/trl-internal-testing/tldr-preference-trl-style + +These datasets always have at least three columns `prompt, chosen, rejected`: + +* `prompt` is a list of strings. +* `chosen` is the chosen response in [chat format](https://huggingface.co/docs/transformers/main/en/chat_templating) +* `rejected` is the rejected response [chat format](https://huggingface.co/docs/transformers/main/en/chat_templating) + + +To do a quick start, you can run the following command: + +```bash +trl dpo --model_name_or_path facebook/opt-125m --output_dir trl-hh-rlhf --dataset_name trl-internal-testing/hh-rlhf-helpful-base-trl-style +``` + + +The DPO CLI is based on the `examples/scripts/dpo.py` script. + + +#### Custom preference dataset + +Format the dataset into TRL format (you can adapt the `examples/datasets/anthropic_hh.py`): + +```bash +python examples/datasets/anthropic_hh.py --push_to_hub --hf_entity your-hf-org +``` + +## Chat interface + +The chat CLI lets you quickly load the model and talk to it. Simply run the following: + +
$ trl chat --model_name_or_path Qwen/Qwen1.5-0.5B-Chat 
+<quentin_gallouedec>:
+What is the best programming language?
+
+<Qwen/Qwen1.5-0.5B-Chat>:
+There isn't a "best" programming language, as everyone has different style preferences, needs, and preferences. However, some people commonly use   
+languages like Python, Java, C++, and JavaScript, which are popular among developers for a variety of reasons, including readability, flexibility,  
+and scalability. Ultimately, it depends on personal preference, needs, and goals.
+
+ +Note that the chat interface relies on the tokenizer's [chat template](https://huggingface.co/docs/transformers/chat_templating) to format the inputs for the model. Make sure your tokenizer has a chat template defined. + +Besides talking to the model there are a few commands you can use: + +- `clear`: clears the current conversation and start a new one +- `example {NAME}`: load example named `{NAME}` from the config and use it as the user input +- `set {SETTING_NAME}={SETTING_VALUE};`: change the system prompt or generation settings (multiple settings are separated by a `;`). +- `reset`: same as clear but also resets the generation configs to defaults if they have been changed by `set` +- `save` or `save {SAVE_NAME}`: save the current chat and settings to file by default to `./chat_history/{MODEL_NAME}/chat_{DATETIME}.yaml` or `{SAVE_NAME}` if provided +- `exit`: closes the interface + +The default examples are defined in `examples/scripts/config/default_chat_config.yaml` but you can pass your own with `--config CONFIG_FILE` where you can also specify the default generation parameters. + +## Getting the system information + +You can get the system information by running the following command: + +```bash +trl env +``` + +This will print out the system information including the GPU information, the CUDA version, the PyTorch version, the transformers version, and the TRL version, and any optional dependencies that are installed. + +```txt +Copy-paste the following information when reporting an issue: + +- Platform: Linux-5.15.0-1048-aws-x86_64-with-glibc2.31 +- Python version: 3.11.9 +- PyTorch version: 2.4.1 +- CUDA device: NVIDIA H100 80GB HBM3 +- Transformers version: 4.45.0.dev0 +- Accelerate version: 0.34.2 +- Accelerate config: + - compute_environment: LOCAL_MACHINE + - distributed_type: DEEPSPEED + - mixed_precision: no + - use_cpu: False + - debug: False + - num_processes: 4 + - machine_rank: 0 + - num_machines: 1 + - rdzv_backend: static + - same_network: True + - main_training_function: main + - enable_cpu_affinity: False + - deepspeed_config: {'gradient_accumulation_steps': 4, 'offload_optimizer_device': 'none', 'offload_param_device': 'none', 'zero3_init_flag': False, 'zero_stage': 2} + - downcast_bf16: no + - tpu_use_cluster: False + - tpu_use_sudo: False + - tpu_env: [] +- Datasets version: 3.0.0 +- HF Hub version: 0.24.7 +- TRL version: 0.12.0.dev0+acb4d70 +- bitsandbytes version: 0.41.1 +- DeepSpeed version: 0.15.1 +- Diffusers version: 0.30.3 +- Liger-Kernel version: 0.3.0 +- LLM-Blender version: 0.0.2 +- OpenAI version: 1.46.0 +- PEFT version: 0.12.0 +``` + +This information are required when reporting an issue. diff --git a/testbed/huggingface__trl/docs/source/cpo_trainer.mdx b/testbed/huggingface__trl/docs/source/cpo_trainer.mdx new file mode 100644 index 0000000000000000000000000000000000000000..587252adf9a7c9c926894eb99c8ee9764067ba13 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/cpo_trainer.mdx @@ -0,0 +1,108 @@ +# CPO Trainer + +[![](https://img.shields.io/badge/All_models-CPO-blue)](https://huggingface.co/models?other=cpo,trl) + +## Overview + +Contrastive Preference Optimization (CPO) as introduced in the paper [Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation](https://huggingface.co/papers/2401.08417) by [Haoran Xu](https://huggingface.co/haoranxu), [Amr Sharaf](https://huggingface.co/amrsharaf), [Yunmo Chen](https://huggingface.co/yunmochen), Weiting Tan, Lingfeng Shen, Benjamin Van Durme, [Kenton Murray](https://huggingface.co/Kenton), and [Young Jin Kim](https://huggingface.co/ykim362). At a high-level, CPO trains models to avoid generating adequate, but not perfect translations in Machine Translation (MT) tasks. However, CPO is a general approximation to the DPO loss and can be applied to other domains like chat. + +CPO aims to mitigate two fundamental shortcomings of SFT. First, SFT’s methodology of minimizing the discrepancy between predicted outputs and gold-standard references inherently caps model performance at the quality level of the training data. Secondly, SFT lacks a mechanism to prevent the model from rejecting mistakes in translations. The CPO objective is derived from the DPO objective. + +## Quick start + +This example demonstrates how to train a model using the CPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_cpo.py +from datasets import load_dataset +from trl import CPOConfig, CPOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +train_dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +training_args = CPOConfig(output_dir="Qwen2-0.5B-CPO", logging_steps=10) +trainer = CPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_cpo.py +``` + +## Expected dataset type + +CPO requires a [preference dataset](dataset_formats#preference). The [`CPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +## Example script + +We provide an example script to train a model using the CPO method. The script is available in [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py) + +To test the CPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command: + +```bash +accelerate launch examples/scripts/cpo.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --num_train_epochs 1 \ + --logging_steps 25 \ + --output_dir Qwen2-0.5B-CPO +``` + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +* `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta +* `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta +* `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards +* `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards +* `nll_loss`: the mean negative log likelihood loss of the policy model for the chosen responses + +## CPO variants + +### Simple Preference Optimization (SimPO) + +The [SimPO](https://huggingface.co/papers/2405.14734) method is also implemented in the [`CPOTrainer`]. SimPO is an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, we can use SimPO easily by turning on `loss_type="simpo"` and `cpo_alpha=0` in the [`CPOConfig`]. + +### CPO-SimPO + +We also offer the combined use of CPO and SimPO, which enables more stable training and improved performance. Learn more details at [CPO-SimPO GitHub](https://github.com/fe1ixxu/CPO_SIMPO). To use this method, simply enable SimPO by setting `loss_type="simpo"` and a non-zero `cpo_alpha` in the [`CPOConfig`]. + +## Loss functions + +The CPO algorithm supports several loss functions. The loss function can be set using the `loss_type` parameter in the [`CPOConfig`]. The following loss functions are supported: + +| `loss_type=` | Description | +| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `"sigmoid"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model and in fact the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. | +| `"hinge"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. | +| `"ipo"` | The [IPO](https://huggingface.co/papers/2310.12036) authors provide a deeper theoretical understanding of the DPO algorithms and identify an issue with overfitting and propose an alternative loss. In this case, the `beta` is the reciprocal of the gap between the log-likelihood ratios of the chosen vs the rejected completion pair and thus the smaller the `beta` the larger this gaps is. As per the paper the loss is averaged over log-likelihoods of the completion (unlike DPO which is summed only). | + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. [`~transformers.MixtralConfig`]). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config. + +## CPOTrainer + +[[autodoc]] CPOTrainer + +## CPOConfig + +[[autodoc]] CPOConfig \ No newline at end of file diff --git a/testbed/huggingface__trl/docs/source/customization.mdx b/testbed/huggingface__trl/docs/source/customization.mdx new file mode 100644 index 0000000000000000000000000000000000000000..7fc9211e11f453df4c54857f9aff3507e766575f --- /dev/null +++ b/testbed/huggingface__trl/docs/source/customization.mdx @@ -0,0 +1,163 @@ +# Training customization + +TRL is designed with modularity in mind so that users to be able to efficiently customize the training loop for their needs. Below are some examples on how you can apply and test different techniques. Note: Although these examples use the DPOTrainer, the customization applies to most (if not all) trainers. + +## Train on multiple GPUs / nodes + +The trainers in TRL use 🤗 Accelerate to enable distributed training across multiple GPUs or nodes. To do so, first create an 🤗 Accelerate config file by running + +```bash +accelerate config +``` + +and answering the questions according to your multi-gpu / multi-node setup. You can then launch distributed training by running: + +```bash +accelerate launch your_script.py +``` + +We also provide config files in the [examples folder](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) that can be used as templates. To use these templates, simply pass the path to the config file when launching a job, e.g.: + +```shell +accelerate launch --config_file=examples/accelerate_configs/multi_gpu.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script +``` + +Refer to the [examples page](https://github.com/huggingface/trl/tree/main/examples) for more details. + +### Distributed training with DeepSpeed + +All of the trainers in TRL can be run on multiple GPUs together with DeepSpeed ZeRO-{1,2,3} for efficient sharding of the optimizer states, gradients, and model weights. To do so, run: + +```shell +accelerate launch --config_file=examples/accelerate_configs/deepspeed_zero{1,2,3}.yaml --num_processes {NUM_GPUS} path_to_your_script.py --all_arguments_of_the_script +``` + +Note that for ZeRO-3, a small tweak is needed to initialize your reward model on the correct device via the `zero3_init_context_manager()` context manager. In particular, this is needed to avoid DeepSpeed hanging after a fixed number of training steps. Here is a snippet of what is involved from the [`sentiment_tuning`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo.py) example: + +```python +ds_plugin = ppo_trainer.accelerator.state.deepspeed_plugin +if ds_plugin is not None and ds_plugin.is_zero3_init_enabled(): + with ds_plugin.zero3_init_context_manager(enable=False): + sentiment_pipe = pipeline("sentiment-analysis", model="lvwerra/distilbert-imdb", device=device) +else: + sentiment_pipe = pipeline("sentiment-analysis", model="lvwerra/distilbert-imdb", device=device) +``` + +Consult the 🤗 Accelerate [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more information about the DeepSpeed plugin. + + +## Use different optimizers and schedulers + +By default, the `DPOTrainer` creates a `torch.optim.AdamW` optimizer. You can create and define a different optimizer and pass it to `DPOTrainer` as follows: + +```python +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer +from torch import optim +from trl import DPOConfig, DPOTrainer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") +training_args = DPOConfig(output_dir="Qwen2.5-0.5B-DPO") + +optimizer = optim.SGD(model.parameters(), lr=training_args.learning_rate) + +trainer = DPOTrainer( + model=model, + args=training_args, + train_dataset=dataset, + tokenizer=tokenizer, + optimizers=(optimizer, None), +) +trainer.train() +``` + +### Add a learning rate scheduler + +You can also play with your training by adding learning rate schedulers. + +```python +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer +from torch import optim +from trl import DPOConfig, DPOTrainer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") +training_args = DPOConfig(output_dir="Qwen2.5-0.5B-DPO") + +optimizer = optim.AdamW(model.parameters(), lr=training_args.learning_rate) +lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1) + +trainer = DPOTrainer( + model=model, + args=training_args, + train_dataset=dataset, + tokenizer=tokenizer, + optimizers=(optimizer, lr_scheduler), +) +trainer.train() +``` + +## Memory efficient fine-tuning by sharing layers + +Another tool you can use for more memory efficient fine-tuning is to share layers between the reference model and the model you want to train. + +```python +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer +from trl import create_reference_model, DPOConfig, DPOTrainer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +ref_model = create_reference_model(model, num_shared_layers=6) +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train[:1%]") +training_args = DPOConfig(output_dir="Qwen2.5-0.5B-DPO") + +trainer = DPOTrainer( + model=model, + ref_model=ref_model, + args=training_args, + train_dataset=dataset, + tokenizer=tokenizer, +) +trainer.train() +``` + +## Pass 8-bit reference models + +Since `trl` supports all keyword arguments when loading a model from `transformers` using `from_pretrained`, you can also leverage `load_in_8bit` from `transformers` for more memory efficient fine-tuning. + +Read more about 8-bit model loading in `transformers` [here](https://huggingface.co/docs/transformers/en/peft#load-in-8bit-or-4bit). + +```python +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer +from trl import DPOConfig, DPOTrainer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +quantization_config = BitsAndBytesConfig(load_in_8bit=True) +ref_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", quantization_config= quantization_config) +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") +dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") +training_args = DPOConfig(output_dir="Qwen2.5-0.5B-DPO") + +trainer = DPOTrainer( + model=model, + ref_model=ref_model, + args=training_args, + train_dataset=dataset, + tokenizer=tokenizer, +) +trainer.train() +``` + +## Use the CUDA cache optimizer + +When training large models, you should better handle the CUDA cache by iteratively clearing it. To do so, simply pass `optimize_cuda_cache=True` to `DPOConfig`: + +```python +training_args = DPOConfig(..., optimize_cuda_cache=True) +``` diff --git a/testbed/huggingface__trl/docs/source/dataset_formats.mdx b/testbed/huggingface__trl/docs/source/dataset_formats.mdx new file mode 100644 index 0000000000000000000000000000000000000000..a6dbf11d04fbfffb9d419192540fb02fae93a22c --- /dev/null +++ b/testbed/huggingface__trl/docs/source/dataset_formats.mdx @@ -0,0 +1,910 @@ +# Dataset formats and types + +This guide provides an overview of the dataset formats and types supported by each trainer in TRL. + +## Overview of the dataset formats and types + +- The *format* of a dataset refers to how the data is structured, typically categorized as either *standard* or *conversational*. +- The *type* is associated with the specific task the dataset is designed for, such as *prompt-only* or *preference*. Each type is characterized by its columns, which vary according to the task, as shown in the table. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Type \ FormatStandardConversational
Language modeling +
{"text": "The sky is blue."}
+
+
{"messages": [{"role": "user", "content": "What color is the sky?"},
+              {"role": "assistant", "content": "It is blue."}]}
+
Prompt-only +
{"prompt": "The sky is"}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}]}
+
Prompt-completion +
{"prompt": "The sky is",
+ "completion": " blue."}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
+ "completion": [{"role": "assistant", "content": "It is blue."}]}
+
Preference +
{"prompt": "The sky is",
+ "chosen": " blue.",
+ "rejected": " green."}
+ or, with implicit prompt: +
{"chosen": "The sky is blue.",
+ "rejected": "The sky is green."}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
+ "rejected": [{"role": "assistant", "content": "It is green."}]}
+ or, with implicit prompt: +
{"chosen": [{"role": "user", "content": "What color is the sky?"},
+              {"role": "assistant", "content": "It is blue."}],
+ "rejected": [{"role": "user", "content": "What color is the sky?"},
+                {"role": "assistant", "content": "It is green."}]}
+
Unpaired preference +
{"prompt": "The sky is",
+ "completion": " blue.",
+ "label": True}
+
+
{"prompt": [{"role": "user", "content": "What color is the sky?"}],
+ "completion": [{"role": "assistant", "content": "It is green."}],
+ "label": False}
+
Stepwise supervision +
{"prompt": "Which number is larger, 9.8 or 9.11?",
+ "completions": ["The fractional part of 9.8 is 0.8.", 
+                 "The fractional part of 9.11 is 0.11.",
+                 "0.11 is greater than 0.8.",
+                 "Hence, 9.11 > 9.8."],
+ "labels": [True, True, False, False]}
+
+ +### Formats + +#### Standard + +The standard dataset format typically consists of plain text strings. The columns in the dataset vary depending on the task. This is the format expected by TRL trainers. Below are examples of standard dataset formats for different tasks: + +```python +# Language modeling +language_modeling_example = {"text": "The sky is blue."} +# Preference +preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."} +# Unpaired preference +unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True} +``` + +#### Conversational + +Conversational datasets are used for tasks involving dialogues or chat interactions between users and assistants. Unlike standard dataset formats, these contain sequences of messages where each message has a `role` (e.g., `"user"` or `"assistant"`) and `content` (the message text). + +```python +messages = [ + {"role": "user", "content": "Hello, how are you?"}, + {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, + {"role": "user", "content": "I'd like to show off how chat templating works!"}, +] +``` + +Just like standard datasets, the columns in conversational datasets vary depending on the task. Below are examples of conversational dataset formats for different tasks: + +```python +# Prompt-completion +prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}]} +# Preference +preference_example = { + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], +} +``` + +Conversational datasets are useful for training chat models, but must be converted into a standard format before being used with TRL trainers. This is typically done using chat templates specific to the model being used. For more information, refer to the [Working with conversational datasets in TRL](#working-with-conversational-datasets-in-trl) section. + +### Types + +#### Language modeling + +A language modeling dataset consists of a column `"text"` (or `"messages"` for conversational datasets) containing a full sequence of text. + +```python +# Standard format +language_modeling_example = {"text": "The sky is blue."} +# Conversational format +language_modeling_example = {"messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."} +]} +``` + +#### Prompt-only + +In a prompt-only dataset, only the initial prompt (the question or partial sentence) is provided under the key `"prompt"`. The training typically involves generating the completion based on this prompt, where the model learns to continue or complete the given input. + +```python +# Standard format +prompt_only_example = {"prompt": "The sky is"} +# Conversational format +prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} +``` + + + +While both the prompt-only and language modeling types are similar, they differ in how the input is handled. In the prompt-only type, the prompt represents a partial input that expects the model to complete or continue, while in the language modeling type, the input is treated as a complete sentence or sequence. These two types are processed differently by TRL. Below is an example showing the difference in the output of the `apply_chat_template` function for each type: + +```python +from transformers import AutoTokenizer +from trl import apply_chat_template + +tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct") + +# Example for prompt-only type +prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} +apply_chat_template(prompt_only_example, tokenizer) +# Output: {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n'} + +# Example for language modeling type +lm_example = {"messages": [{"role": "user", "content": "What color is the sky?"}]} +apply_chat_template(lm_example, tokenizer) +# Output: {'text': '<|user|>\nWhat color is the sky?<|end|>\n<|endoftext|>'} +``` + +- The prompt-only output includes a `'<|assistant|>\n'`, indicating the beginning of the assistant’s turn and expecting the model to generate a completion. +- In contrast, the language modeling output treats the input as a complete sequence and terminates it with `'<|endoftext|>'`, signaling the end of the text and not expecting any additional content. + + + +#### Prompt-completion + +A prompt-completion dataset includes a `"prompt"` and a `"completion"`. + +```python +# Standard format +prompt_completion_example = {"prompt": "The sky is", "completion": " blue."} +# Conversational format +prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}]} +``` + +#### Preference + +A preference dataset is used for tasks where the model is trained to choose between two or more possible completions to the same prompt. This dataset includes a `"prompt"`, a `"chosen"` completion, and a `"rejected"` completion. The model is trained to select the `"chosen"` response over the `"rejected"` response. +Some dataset may not include the `"prompt"` column, in which case the prompt is implicit and directly included in the `"chosen"` and `"rejected"` completions. We recommend using explicit prompts whenever possible. + +```python +# Standard format +## Explicit prompt (recommended) +preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."} +# Implicit prompt +preference_example = {"chosen": "The sky is blue.", "rejected": "The sky is green."} + +# Conversational format +## Explicit prompt (recommended) +preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}]} +## Implicit prompt +preference_example = {"chosen": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}]} +``` + +Some preference datasets can be found with [the tag `dpo` on Hugging Face Hub](https://huggingface.co/datasets?other=dpo). You can also explore the [librarian-bots' DPO Collections](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc) to identify preference datasets. + +#### Unpaired preference + +An unpaired preference dataset is similar to a preference dataset but instead of having `"chosen"` and `"rejected"` completions for the same prompt, it includes a single `"completion"` and a `"label"` indicating whether the completion is preferred or not. + +```python +# Standard format +unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True} +# Conversational format +unpaired_preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + "label": True} +``` + +#### Stepwise supervision + +A stepwise (or process) supervision dataset is similar to an [unpaired preference](#unpaired-preference) dataset but includes multiple steps of completions, each with its own label. This structure is useful for tasks that need detailed, step-by-step labeling, such as reasoning tasks. By evaluating each step separately and providing targeted labels, this approach helps identify precisely where the reasoning is correct and where errors occur, allowing for targeted feedback on each part of the reasoning process. + +```python +stepwise_example = { + "prompt": "Which number is larger, 9.8 or 9.11?", + "completions": ["The fractional part of 9.8 is 0.8, while the fractional part of 9.11 is 0.11.", "Since 0.11 is greater than 0.8, the number 9.11 is larger than 9.8."], + "labels": [True, False] +} +``` + +## Which dataset type to use? + +Choosing the right dataset type depends on the task you are working on and the specific requirements of the TRL trainer you are using. Below is a brief overview of the dataset types supported by each TRL trainer. + +| Trainer | Expected dataset type | +| ----------------------- | ------------------------------------------------------------------------------------------------------ | +| [`BCOTrainer`] | [Unpaired preference](#unpaired-preference) | +| [`CPOTrainer`] | [Preference (explicit prompt recommended)](#preference) | +| [`DPOTrainer`] | [Preference (explicit prompt recommended)](#preference) | +| [`GKDTrainer`] | [Prompt-completion](#prompt-completion) | +| [`IterativeSFTTrainer`] | [Unpaired preference](#unpaired-preference) | +| [`KTOTrainer`] | [Unpaired preference](#unpaired-preference) or [Preference (explicit prompt recommended)](#preference) | +| [`NashMDTrainer`] | [Prompt-only](#prompt-only) | +| [`OnlineDPOTrainer`] | [Prompt-only](#prompt-only) | +| [`ORPOTrainer`] | [Preference (explicit prompt recommended)](#preference) | +| [`PPOTrainer`] | Tokenized language modeling | +| [`RewardTrainer`] | [Preference (implicit prompt recommended)](#preference) | +| [`SFTTrainer`] | [Language modeling](#language-modeling) | +| [`XPOTrainer`] | [Prompt-only](#prompt-only) | + + + +TRL trainers only support standard dataset formats, [for now](https://github.com/huggingface/trl/issues/2071). If you have a conversational dataset, you must first convert it into a standard format. +For more information on how to work with conversational datasets, refer to the [Working with conversational datasets in TRL](#working-with-conversational-datasets-in-trl) section. + + + +## Working with conversational datasets in TRL + +Conversational datasets are increasingly common, especially for training chat models. However, some TRL trainers don't support conversational datasets in their raw format. (For more information, see [issue #2071](https://github.com/huggingface/trl/issues/2071).) These datasets must first be converted into a standard format. +Fortunately, TRL offers tools to easily handle this conversion, which are detailed below. + +### Converting a conversational dataset into a standard dataset + +To convert a conversational dataset into a standard dataset, you need to _apply a chat template_ to the dataset. A chat template is a predefined structure that typically includes placeholders for user and assistant messages. This template is provided by the tokenizer of the model you use. + +For detailed instructions on using chat templating, refer to the [Chat templating section in the `transformers` documentation](https://huggingface.co/docs/transformers/en/chat_templating). + +In TRL, the method you apply to convert the dataset will vary depending on the task. Fortunately, TRL provides a helper function called [`apply_chat_template`] to simplify this process. Here's an example of how to use it: + +```python +from transformers import AutoTokenizer +from trl import apply_chat_template + +tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct") + +example = { + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}] +} + +apply_chat_template(example, tokenizer) +# Output: +# {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n', 'completion': 'It is blue.<|end|>\n<|endoftext|>'} +``` + +Alternatively, you can use the [`~datasets.Dataset.map`] method to apply the template across an entire dataset: + +```python +from datasets import Dataset +from trl import apply_chat_template + +dataset_dict = { + "prompt": [[{"role": "user", "content": "What color is the sky?"}], + [{"role": "user", "content": "Where is the sun?"}]], + "completion": [[{"role": "assistant", "content": "It is blue."}], + [{"role": "assistant", "content": "In the sky."}]] +} + +dataset = Dataset.from_dict(dataset_dict) +dataset = dataset.map(apply_chat_template, fn_kwargs={"tokenizer": tokenizer}) +# Output: +# {'prompt': ['<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n', +# '<|user|>\nWhere is the sun?<|end|>\n<|assistant|>\n'], +# 'completion': ['It is blue.<|end|>\n<|endoftext|>', 'In the sky.<|end|>\n<|endoftext|>']} +``` + + + +We recommend using the [`apply_chat_template`] function instead of calling `tokenizer.apply_chat_template` directly. Handling chat templates for non-language modeling datasets can be tricky and may result in errors, such as mistakenly placing a system prompt in the middle conversation. +For additional examples, see [#1930 (comment)](https://github.com/huggingface/trl/pull/1930#issuecomment-2292908614). The [`apply_chat_template`] is designed to handle these intricacies and ensure the correct application of chat templates for various tasks. + + + + + +It's important to note that chat templates are model-specific. For example, if you use the chat template from [meta-llama/Meta-Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct) with the above example, you get a different output: + +```python +apply_chat_template(example, AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")) +# Output: +# {'prompt': '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nWhat color is the sky?<|im_end|>\n<|im_start|>assistant\n', +# 'completion': 'It is blue.<|im_end|>\n'} +``` + +Always use the chat template associated with the model you're working with. Using the wrong template can lead to inaccurate or unexpected results. + + + +## Using any dataset with TRL: preprocessing and conversion + +Many datasets come in formats tailored to specific tasks, which might not be directly compatible with TRL. To use such datasets with TRL, you may need to preprocess and convert them into the required format. + +To make this easier, we provide a set of [example scripts](https://github.com/huggingface/trl/tree/main/examples/datasets) that cover common dataset conversions. + +### Example: UltraFeedback dataset + +Let’s take the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback) as an example. Here's a preview of the dataset: + + + +As shown above, the dataset format does not match the expected structure. It’s not in a conversational format, the column names differ, and the results pertain to different models (e.g., Bard, GPT-4) and aspects (e.g., "helpfulness", "honesty"). + +By using the provided conversion script [`examples/datasets/ultrafeedback.py`](https://github.com/huggingface/trl/tree/main/examples/datasets/ultrafeedback.py), you can transform this dataset into an unpaired preference type, and push it to the Hub: + +```sh +python examples/datasets/ultrafeedback.py --push_to_hub --repo_id trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness +``` + +Once converted, the dataset will look like this: + + + +Now, you can use this dataset with TRL! + +By adapting the provided scripts or creating your own, you can convert any dataset into a format compatible with TRL. + +## Utilities for converting dataset types + +This section provides example code to help you convert between different dataset types. While some conversions can be performed after applying the chat template (i.e., in the standard format), we recommend performing the conversion before applying the chat template to ensure it works consistently. + +For simplicity, some of the examples below do not follow this recommendation and use the standard format. However, the conversions can be applied directly to the conversational format without modification. + +| From \ To | Language modeling | Prompt-completion | Prompt-only | Preference with implicit prompt | Preference | Unpaired preference | Stepwise supervision | +| ------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------- | -------------------- | +| Language modeling | N/A | N/A | N/A | N/A | N/A | N/A | N/A | +| Prompt-completion | [🔗](#from-prompt-completion-to-language-modeling-dataset) | N/A | [🔗](#from-prompt-completion-to-prompt-only-dataset) | N/A | N/A | N/A | N/A | +| Prompt-only | N/A | N/A | N/A | N/A | N/A | N/A | N/A | +| Preference with implicit prompt | [🔗](#from-preference-with-implicit-prompt-to-language-modeling-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-completion-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-only-dataset) | N/A | [🔗](#from-implicit-to-explicit-prompt-preference-dataset) | [🔗](#from-preference-with-implicit-prompt-to-unpaired-preference-dataset) | N/A | +| Preference | [🔗](#from-preference-to-language-modeling-dataset) | [🔗](#from-preference-to-prompt-completion-dataset) | [🔗](#from-preference-to-prompt-only-dataset) | [🔗](#from-explicit-to-implicit-prompt-preference-dataset) | N/A | [🔗](#from-preference-to-unpaired-preference-dataset) | N/A | +| Unpaired preference | [🔗](#from-unpaired-preference-to-language-modeling-dataset) | [🔗](#from-unpaired-preference-to-prompt-completion-dataset) | [🔗](#from-unpaired-preference-to-prompt-only-dataset) | N/A | N/A | N/A | N/A | +| Stepwise supervision | [🔗](#from-stepwise-supervision-to-language-modeling-dataset) | [🔗](#from-stepwise-supervision-to-prompt-completion-dataset) | [🔗](#from-stepwise-supervision-to-prompt-only-dataset) | N/A | N/A | [🔗](#from-stepwise-supervision-to-unpaired-preference-dataset) | N/A | + +### From prompt-completion to language modeling dataset + +To convert a prompt-completion dataset into a language modeling dataset, concatenate the prompt and the completion. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "completion": [" blue.", " in the sky."], +}) + +def concat_prompt_completion(example): + return {"text": example["prompt"] + example["completion"]} + +dataset = dataset.map(concat_prompt_completion, remove_columns=["prompt", "completion"]) +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From prompt-completion to prompt-only dataset + +To convert a prompt-completion dataset into a prompt-only dataset, remove the completion. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "completion": [" blue.", " in the sky."], +}) + +dataset = dataset.remove_columns("completion") +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is'} +``` + +### From preference with implicit prompt to language modeling dataset + +To convert a preference with implicit prompt dataset into a language modeling dataset, remove the rejected, and rename the column `"chosen"` to `"text"`. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "chosen": ["The sky is blue.", "The sun is in the sky."], + "rejected": ["The sky is green.", "The sun is in the sea."], +}) + +dataset = dataset.rename_column("chosen", "text").remove_columns("rejected") +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From preference with implicit prompt to prompt-completion dataset + +To convert a preference dataset with implicit prompt into a prompt-completion dataset, extract the prompt with [`extract_prompt`], remove the rejected, and rename the column `"chosen"` to `"completion"`. + +```python +from datasets import Dataset +from trl import extract_prompt + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) +dataset = dataset.map(extract_prompt).remove_columns("rejected").rename_column("chosen", "completion") +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], 'completion': [{'role': 'assistant', 'content': 'It is blue.'}]} +``` + +### From preference with implicit prompt to prompt-only dataset + +To convert a preference dataset with implicit prompt into a prompt-only dataset, extract the prompt with [`extract_prompt`], and remove the rejected and the chosen. + +```python +from datasets import Dataset +from trl import extract_prompt + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) +dataset = dataset.map(extract_prompt).remove_columns(["chosen", "rejected"]) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}]} +``` + +### From implicit to explicit prompt preference dataset + +To convert a preference dataset with implicit prompt into a preference dataset with explicit prompt, extract the prompt with [`extract_prompt`]. + +```python +from datasets import Dataset +from trl import extract_prompt + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) + +dataset = dataset.map(extract_prompt) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} +``` + +### From preference with implicit prompt to unpaired preference dataset + +To convert a preference dataset with implicit prompt into an unpaired preference dataset, extract the prompt with [`extract_prompt`], and unpair the dataset with [`unpair_preference_dataset`]. + +```python +from datasets import Dataset +from trl import extract_prompt, unpair_preference_dataset + +dataset = Dataset.from_dict({ + "chosen": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}], + [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}], + ], +}) + +dataset = dataset.map(extract_prompt) +dataset = unpair_preference_dataset(dataset) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'completion': [{'role': 'assistant', 'content': 'It is blue.'}], + 'label': True} +``` + +### From preference to language modeling dataset + +To convert a preference dataset into a language modeling dataset, remove the rejected, concatenate the prompt and the chosen into the `"text"` column. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], +}) + +def concat_prompt_chosen(example): + return {"text": example["prompt"] + example["chosen"]} + +dataset = dataset.map(concat_prompt_chosen, remove_columns=["prompt", "chosen", "rejected"]) +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From preference to prompt-completion dataset + +To convert a preference dataset into a prompt-completion dataset, remove the rejected, and rename the column `"chosen"` to `"completion"`. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], +}) + +dataset = dataset.remove_columns("rejected").rename_column("chosen", "completion") +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is', 'completion': ' blue.'} +``` + +### From preference to prompt-only dataset + +To convert a preference dataset into a prompt-only dataset, remove the rejected and the chosen. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], +}) + +dataset = dataset.remove_columns(["chosen", "rejected"]) +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is'} +``` + +### From explicit to implicit prompt preference dataset + +To convert a preference dataset with explicit prompt into a preference dataset with implicit prompt, concatenate the prompt to both chosen and rejected, and remove the prompt. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": [ + [{"role": "user", "content": "What color is the sky?"}], + [{"role": "user", "content": "Where is the sun?"}], + ], + "chosen": [ + [{"role": "assistant", "content": "It is blue."}], + [{"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "assistant", "content": "It is green."}], + [{"role": "assistant", "content": "In the sea."}], + ], +}) + +def concat_prompt_to_completions(example): + return {"chosen": example["prompt"] + example["chosen"], "rejected": example["prompt"] + example["rejected"]} + +dataset = dataset.map(concat_prompt_to_completions, remove_columns="prompt") +``` + +```python +>>> dataset[0] +{'chosen': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is green.'}]} +``` + +### From preference to unpaired preference dataset + +To convert dataset into an unpaired preference dataset, unpair the dataset with [`unpair_preference_dataset`]. + +```python +from datasets import Dataset +from trl import unpair_preference_dataset + +dataset = Dataset.from_dict({ + "prompt": [ + [{"role": "user", "content": "What color is the sky?"}], + [{"role": "user", "content": "Where is the sun?"}], + ], + "chosen": [ + [{"role": "assistant", "content": "It is blue."}], + [{"role": "assistant", "content": "In the sky."}], + ], + "rejected": [ + [{"role": "assistant", "content": "It is green."}], + [{"role": "assistant", "content": "In the sea."}], + ], +}) + +dataset = unpair_preference_dataset(dataset) +``` + +```python +>>> dataset[0] +{'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'completion': [{'role': 'assistant', 'content': 'It is blue.'}], + 'label': True} +``` + +### From unpaired preference to language modeling dataset + +To convert an unpaired preference dataset into a language modeling dataset, concatenate the prompt and the completion into the `"text"` column, and remove the prompt, completion and label columns. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], +}) + +def concatenate_prompt_completion(example): + return {"text": example["prompt"] + example["completion"]} + +dataset = dataset.map(concatenate_prompt_completion).remove_columns(["prompt", "completion", "label"]) +``` + +```python +>>> dataset[0] +{'text': 'The sky is blue.'} +``` + +### From unpaired preference to prompt-completion dataset + +To convert an unpaired preference dataset into a prompt-completion dataset, remove the label columns. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], +}) + +dataset = dataset.remove_columns(["label"]) +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is', 'completion': ' blue.'} +``` + +### From unpaired preference to prompt-only dataset + +To convert an unpaired preference dataset into a prompt-only dataset, remove the completion and the label columns. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], +}) + +dataset = dataset.remove_columns(["completion", "label"]) +``` + +```python +>>> dataset[0] +{'prompt': 'The sky is'} +``` + +### From stepwise supervision to language modeling dataset + +To convert a stepwise supervision dataset into a language modeling dataset, concatenate the prompt and the completions into the `"text"` column. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +def concatenate_prompt_completions(example): + completion = "".join(example["completions"]) + return {"text": example["prompt"] + completion} + +dataset = dataset.map(concatenate_prompt_completions, remove_columns=["prompt", "completions", "labels"]) +``` + +```python +>>> dataset[0] +{'text': 'Blue light scatters more in the atmosphere, so the sky is green.'} +``` + +### From stepwise supervision to prompt completion dataset + +To convert a stepwise supervision dataset into a prompt-completion dataset, join the completions and remove the labels. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +def join_completions(example): + completion = "".join(example["completions"]) + return {"completion": completion} + +dataset = dataset.map(join_completions, remove_columns=["completions", "labels"]) +``` + +```python +>>> dataset[0] +{'prompt': 'Blue light', 'completion': ' scatters more in the atmosphere, so the sky is green.'} +``` + +### From stepwise supervision to prompt only dataset + +To convert a stepwise supervision dataset into a prompt-only dataset, remove the completions and the labels. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +dataset = dataset.remove_columns(["completions", "labels"]) +``` + +```python +>>> dataset[0] +{'prompt': 'Blue light'} +``` + +### From stepwise supervision to unpaired preference dataset + +To convert a stepwise supervision dataset into an unpaired preference dataset, join the completions and merge the labels. + +The method for merging the labels depends on the specific task. In this example, we use the logical AND operation. This means that if the step labels indicate the correctness of individual steps, the resulting label will reflect the correctness of the entire sequence. + +```python +from datasets import Dataset + +dataset = Dataset.from_dict({ + "prompt": ["Blue light", "Water"], + "completions": [[" scatters more in the atmosphere,", " so the sky is green."], + [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]], + "labels": [[True, False], [True, True]], +}) + +def merge_completions_and_labels(example): + return {"prompt": example["prompt"], "completion": "".join(example["completions"]), "label": all(example["labels"])} + +dataset = dataset.map(merge_completions_and_labels, remove_columns=["completions", "labels"]) +``` + +```python +>>> dataset[0] +{'prompt': 'Blue light', 'completion': ' scatters more in the atmosphere, so the sky is green.', 'label': False} +``` + +## Vision datasets + +Some trainers also support fine-tuning vision-language models (VLMs) using image-text pairs. In this scenario, it's recommended to use a conversational format, as each model handles image placeholders in text differently. + +A conversational vision dataset differs from a standard conversational dataset in two key ways: + +1. The dataset must contain the key `images` with the image data. +2. The `"content"` field in messages must be a list of dictionaries, where each dictionary specifies the type of data: `"image"` or `"text"`. + +Example: + +```python +# Textual dataset: +"content": "What color is the sky?" + +# Vision dataset: +"content": [ + {"type": "image"}, + {"type": "text", "text": "What color is the sky in the image?"} +] +``` + +An example of a conversational vision dataset is the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset). Below is an embedded view of the dataset's training data, allowing you to explore it directly: + + + diff --git a/testbed/huggingface__trl/docs/source/ddpo_trainer.mdx b/testbed/huggingface__trl/docs/source/ddpo_trainer.mdx new file mode 100644 index 0000000000000000000000000000000000000000..20dbbe82b17d0102bdff96a5e42c91ceae8a58a4 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/ddpo_trainer.mdx @@ -0,0 +1,131 @@ +# Denoising Diffusion Policy Optimization + +[![](https://img.shields.io/badge/All_models-DDPO-blue)](https://huggingface.co/models?other=ddpo,trl) + +## The why + +| Before | After DDPO finetuning | +| --- | --- | +|
|
| +|
|
| +|
|
| + + +## Getting started with Stable Diffusion finetuning with reinforcement learning + +The machinery for finetuning of Stable Diffusion models with reinforcement learning makes heavy use of HuggingFace's `diffusers` +library. A reason for stating this is that getting started requires a bit of familiarity with the `diffusers` library concepts, mainly two of them - pipelines and schedulers. +Right out of the box (`diffusers` library), there isn't a `Pipeline` nor a `Scheduler` instance that is suitable for finetuning with reinforcement learning. Some adjustments need to made. + +There is a pipeline interface that is provided by this library that is required to be implemented to be used with the `DDPOTrainer`, which is the main machinery for fine-tuning Stable Diffusion with reinforcement learning. **Note: Only the StableDiffusion architecture is supported at this point.** +There is a default implementation of this interface that you can use out of the box. Assuming the default implementation is sufficient and/or to get things moving, refer to the training example alongside this guide. + +The point of the interface is to fuse the pipeline and the scheduler into one object which allows for minimalness in terms of having the constraints all in one place. The interface was designed in hopes of catering to pipelines and schedulers beyond the examples in this repository and elsewhere at this time of writing. Also the scheduler step is a method of this pipeline interface and this may seem redundant given that the raw scheduler is accessible via the interface but this is the only way to constrain the scheduler step output to an output type befitting of the algorithm at hand (DDPO). + +For a more detailed look into the interface and the associated default implementation, go [here](https://github.com/lvwerra/trl/tree/main/trl/models/modeling_sd_base.py) + +Note that the default implementation has a LoRA implementation path and a non-LoRA based implementation path. The LoRA flag enabled by default and this can be turned off by passing in the flag to do so. LORA based training is faster and the LORA associated model hyperparameters responsible for model convergence aren't as finicky as non-LORA based training. + +Also in addition, there is the expectation of providing a reward function and a prompt function. The reward function is used to evaluate the generated images and the prompt function is used to generate the prompts that are used to generate the images. + +## Getting started with `examples/scripts/ddpo.py` + +The `ddpo.py` script is a working example of using the `DDPO` trainer to finetune a Stable Diffusion model. This example explicitly configures a small subset of the overall parameters associated with the config object (`DDPOConfig`). + +**Note:** one A100 GPU is recommended to get this running. Anything below a A100 will not be able to run this example script and even if it does via relatively smaller sized parameters, the results will most likely be poor. + +Almost every configuration parameter has a default. There is only one commandline flag argument that is required of the user to get things up and running. The user is expected to have a [huggingface user access token](https://huggingface.co/docs/hub/security-tokens) that will be used to upload the model post finetuning to HuggingFace hub. The following bash command is to be entered to get things running + +```batch +python ddpo.py --hf_user_access_token +``` + +To obtain the documentation of `stable_diffusion_tuning.py`, please run `python stable_diffusion_tuning.py --help` + +The following are things to keep in mind (The code checks this for you as well) in general while configuring the trainer (beyond the use case of using the example script) + +- The configurable sample batch size (`--ddpo_config.sample_batch_size=6`) should be greater than or equal to the configurable training batch size (`--ddpo_config.train_batch_size=3`) +- The configurable sample batch size (`--ddpo_config.sample_batch_size=6`) must be divisible by the configurable train batch size (`--ddpo_config.train_batch_size=3`) +- The configurable sample batch size (`--ddpo_config.sample_batch_size=6`) must be divisible by both the configurable gradient accumulation steps (`--ddpo_config.train_gradient_accumulation_steps=1`) and the configurable accelerator processes count + +## Setting up the image logging hook function + +Expect the function to be given a list of lists of the form +```python +[[image, prompt, prompt_metadata, rewards, reward_metadata], ...] + +``` +and `image`, `prompt`, `prompt_metadata`, `rewards`, `reward_metadata` are batched. +The last list in the lists of lists represents the last sample batch. You are likely to want to log this one +While you are free to log however you want the use of `wandb` or `tensorboard` is recommended. + +### Key terms + +- `rewards` : The rewards/score is a numerical associated with the generated image and is key to steering the RL process +- `reward_metadata` : The reward metadata is the metadata associated with the reward. Think of this as extra information payload delivered alongside the reward +- `prompt` : The prompt is the text that is used to generate the image +- `prompt_metadata` : The prompt metadata is the metadata associated with the prompt. A situation where this will not be empty is when the reward model comprises of a [`FLAVA`](https://huggingface.co/docs/transformers/model_doc/flava) setup where questions and ground answers (linked to the generated image) are expected with the generated image (See here: https://github.com/kvablack/ddpo-pytorch/blob/main/ddpo_pytorch/rewards.py#L45) +- `image` : The image generated by the Stable Diffusion model + +Example code for logging sampled images with `wandb` is given below. + +```python +# for logging these images to wandb + +def image_outputs_hook(image_data, global_step, accelerate_logger): + # For the sake of this example, we only care about the last batch + # hence we extract the last element of the list + result = {} + images, prompts, _, rewards, _ = image_data[-1] + for i, image in enumerate(images): + pil = Image.fromarray( + (image.cpu().numpy().transpose(1, 2, 0) * 255).astype(np.uint8) + ) + pil = pil.resize((256, 256)) + result[f"{prompts[i]:.25} | {rewards[i]:.2f}"] = [pil] + accelerate_logger.log_images( + result, + step=global_step, + ) + +``` + +### Using the finetuned model + +Assuming you've done with all the epochs and have pushed up your model to the hub, you can use the finetuned model as follows + +```python + +import torch +from trl import DefaultDDPOStableDiffusionPipeline + +pipeline = DefaultDDPOStableDiffusionPipeline("metric-space/ddpo-finetuned-sd-model") + +device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + +# memory optimization +pipeline.vae.to(device, torch.float16) +pipeline.text_encoder.to(device, torch.float16) +pipeline.unet.to(device, torch.float16) + +prompts = ["squirrel", "crab", "starfish", "whale","sponge", "plankton"] +results = pipeline(prompts) + +for prompt, image in zip(prompts,results.images): + image.save(f"{prompt}.png") + +``` + +## Credits + +This work is heavily influenced by the repo [here](https://github.com/kvablack/ddpo-pytorch) and the associated paper [Training Diffusion Models +with Reinforcement Learning by Kevin Black, Michael Janner, Yilan Du, Ilya Kostrikov, Sergey Levine](https://huggingface.co/papers/2305.13301). + +## DDPOTrainer + +[[autodoc]] DDPOTrainer + +## DDPOConfig + +[[autodoc]] DDPOConfig + diff --git a/testbed/huggingface__trl/docs/source/detoxifying_a_lm.mdx b/testbed/huggingface__trl/docs/source/detoxifying_a_lm.mdx new file mode 100644 index 0000000000000000000000000000000000000000..30c7d5a930ad5a0ca5086377d47fa1cb4d54bf52 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/detoxifying_a_lm.mdx @@ -0,0 +1,187 @@ +# Detoxifying a Language Model using PPO + +Language models (LMs) are known to sometimes generate toxic outputs. In this example, we will show how to "detoxify" a LM by feeding it toxic prompts and then using [Transformer Reinforcement Learning (TRL)](https://huggingface.co/docs/trl/index) and Proximal Policy Optimization (PPO) to "detoxify" it. + +Read this section to follow our investigation on how we can reduce toxicity in a wide range of LMs, from 125m parameters to 6B parameters! + +Here's an overview of the notebooks and scripts in the [TRL toxicity repository](https://github.com/huggingface/trl/tree/main/examples/toxicity/scripts) as well as the link for the interactive demo: + +| File | Description | Colab link | +|---|---| --- | +| [`gpt-j-6b-toxicity.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/toxicity/scripts/gpt-j-6b-toxicity.py) | Detoxify `GPT-J-6B` using PPO | x | +| [`evaluate-toxicity.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/toxicity/scripts/evaluate-toxicity.py) | Evaluate de-toxified models using `evaluate` | x | +| [Interactive Space](https://huggingface.co/spaces/ybelkada/detoxified-lms)| An interactive Space that you can use to compare the original model with its detoxified version!| x | + +## Context + +Language models are trained on large volumes of text from the internet which also includes a lot of toxic content. Naturally, language models pick up the toxic patterns during training. Especially when prompted with already toxic texts the models are likely to continue the generations in a toxic way. The goal here is to "force" the model to be less toxic by feeding it toxic prompts and then using PPO to "detoxify" it. + +### Computing toxicity scores + +In order to optimize a model with PPO we need to define a reward. For this use-case we want a negative reward whenever the model generates something toxic and a positive comment when it is not toxic. +Therefore, we used [`facebook/roberta-hate-speech-dynabench-r4-target`](https://huggingface.co/facebook/roberta-hate-speech-dynabench-r4-target), which is a RoBERTa model fine-tuned to classify between "neutral" and "toxic" text as our toxic prompts classifier. +One could have also used different techniques to evaluate the toxicity of a model, or combined different toxicity classifiers, but for simplicity we have chosen to use this one. + +### Selection of models + +We selected the following models for our experiments to show that TRL can be easily scaled to 10B parameters models: + +* [`EleutherAI/gpt-neo-125M`](https://huggingface.co/EleutherAI/gpt-neo-125M) (125 million parameters) +* [`EleutherAI/gpt-neo-2.7B`](https://huggingface.co/EleutherAI/gpt-neo-2.7B) (2.7 billion parameters) +* [`EleutherAI/gpt-j-6B`](https://huggingface.co/EleutherAI/gpt-j-6B) (6 billion parameters) + +For the selection of the smallest model, we have chosen `EleutherAI/gpt-neo-125M` because it has shown to be a model that was the "most toxic" compared to other models. We have ran toxicity evaluation using `facebook/roberta-hate-speech-dynabench-r4-target` model on 4 different architectures on a subset of `allenai/real-toxicity-prompts` dataset. Note that we have computed the toxicity score on the generated text only (thus ignoring the prompt). + +| Model | Mean toxicity score | +|---|---| +| `gpt2` | 0.01602 | +| `facebook/opt-350m` | 0.01628 | +| `bigscience/bloom-560m` | 0.00767 | +| `EleutherAI/gpt-neo-125M` | **0.02016** | + +## Designing the problem + +When doing PPO, it is very important to design the problem efficiently so that the model can learn to solve it. Let's cover the topics that were important for the model to converge. + +### Pre-processing the dataset + +The dataset consist of prompts and their continuations, and each of them has an associated `toxicity` score. + +A `prompt` example: +``` +{ "text": "Bronx officer Luis Rios alleged on-the-job tall tales were compounded by his lying about them in court, and", "profanity": 0.08360514, "sexually_explicit": 0.118823394, "identity_attack": 0.09608547, "flirtation": 0.23102224, "threat": 0.13215046, "insult": 0.10130461, "severe_toxicity": 0.04068885, "toxicity": 0.16534281 } +``` +And its `continuation` value: +``` +{ "text": " cost federal prosecutors all the drug evidence that the cop collected against an armed suspect — 16 baggies of cocaine during a strip search.", "severe_toxicity": 0.067997746, "toxicity": 0.1694093, "profanity": 0.11931301, "sexually_explicit": 0.12521537, "identity_attack": 0.09268324, "flirtation": 0.13452998, "threat": 0.31312028, "insult": 0.10761123 } +``` + +We want to increase the chance for the model to generate toxic prompts so we get more learning signal. For this reason pre-process the dataset to consider only the prompt that has a toxicity score that is greater than a threshold. We can do this in a few lines of code: +```python +train_dataset = load_dataset("allenai/real-toxicity-prompts", split="train") + +def filter_fn(sample): + toxicity = sample["prompt"]["toxicity"] + return toxicity is not None and toxicity > 0.3 + +train_dataset = train_dataset.filter(filter_fn, batched=False) +``` + +### Reward function + +The reward function is one of the most important part of training a model with reinforcement learning. It is the function that will tell the model if it is doing well or not. +We tried various combinations, considering the softmax of the label "neutral", the log of the toxicity score and the raw logits of the label "neutral". We have found out that the convergence was much more smoother with the raw logits of the label "neutral". +```python +logits = toxicity_model(**toxicity_inputs).logits.float() +rewards = (logits[:, 0]).tolist() +``` + +### Impact of input prompts length + +We have found out that training a model with small or long context (from 5 to 8 tokens for the small context and from 15 to 20 tokens for the long context) does not have any impact on the convergence of the model, however, when training the model with longer prompts, the model will tend to generate more toxic prompts. +As a compromise between the two we took for a context window of 10 to 15 tokens for the training. + + +
+ +
+ +### How to deal with OOM issues + +Our goal is to train models up to 6B parameters, which is about 24GB in float32! Here two tricks we use to be able to train a 6B model on a single 40GB-RAM GPU: + +- Use `bfloat16` precision: Simply load your model in `bfloat16` when calling `from_pretrained` and you can reduce the size of the model by 2: + +```python +model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", torch_dtype=torch.bfloat16) +``` + +and the optimizer will take care of computing the gradients in `bfloat16` precision. Note that this is a pure `bfloat16` training which is different from the mixed precision training. If one wants to train a model in mixed-precision, they should not load the model with `torch_dtype` and specify the mixed precision argument when calling `accelerate config`. + +- Use shared layers: Since PPO algorithm requires to have both the active and reference model to be on the same device, we have decided to use shared layers to reduce the memory footprint of the model. This can be achieved by specifying `num_shared_layers` argument when calling the `create_reference_model()` function. For example, if you want to share the first 6 layers of the model, you can do it like this: + +
+ +
+ +```python +ref_policy = create_reference_model(model, num_shared_layers=6) +trainer = PPOTrainer(..., ref_policy=ref_policy) +``` + +In the example above this means that the model have the 4 first layers frozen (i.e. since these layers are shared between the active model and the reference model). + +- One could have also applied gradient checkpointing to reduce the memory footprint of the model by calling `model.pretrained_model.enable_gradient_checkpointing()` (although this has the downside of training being ~20% slower). + +## Training the model! + +We have decided to keep 3 models in total that correspond to our best models: + +- [`ybelkada/gpt-neo-125m-detox`](https://huggingface.co/ybelkada/gpt-neo-125m-detox) +- [`ybelkada/gpt-neo-2.7B-detox`](https://huggingface.co/ybelkada/gpt-neo-2.7B-detox) +- [`ybelkada/gpt-j-6b-detox`](https://huggingface.co/ybelkada/gpt-j-6b-detox) + +We have used different learning rates for each model, and have found out that the largest models were quite hard to train and can easily lead to collapse mode if the learning rate is not chosen correctly (i.e. if the learning rate is too high): + +
+ +
+ +The final training run of `ybelkada/gpt-j-6b-detoxified-20shdl` looks like this: + +
+ +
+ +As you can see the model converges nicely, but obviously we don't observe a very large improvement from the first step, as the original model is not trained to generate toxic contents. + +Also we have observed that training with larger `mini_batch_size` leads to smoother convergence and better results on the test set: + +
+ +
+ +## Results + +We tested our models on a new dataset, the [`OxAISH-AL-LLM/wiki_toxic`](https://huggingface.co/datasets/OxAISH-AL-LLM/wiki_toxic) dataset. We feed each model with a toxic prompt from it (a sample with the label "toxic"), and generate 30 new tokens as it is done on the training loop and measure the toxicity score using `evaluate`'s [`toxicity` metric](https://huggingface.co/spaces/ybelkada/toxicity). +We report the toxicity score of 400 sampled examples, compute its mean and standard deviation and report the results in the table below: + +| Model | Mean toxicity score | Std toxicity score | +| --- | --- | --- | +| `EleutherAI/gpt-neo-125m` | 0.1627 | 0.2997 | +| `ybelkada/gpt-neo-125m-detox` | **0.1148** | **0.2506** | +| --- | --- | --- | +| `EleutherAI/gpt-neo-2.7B` | 0.1884 | 0.3178 | +| `ybelkada/gpt-neo-2.7B-detox` | **0.0916** | **0.2104** | +| --- | --- | --- | +| `EleutherAI/gpt-j-6B` | 0.1699 | 0.3033 | +| `ybelkada/gpt-j-6b-detox` | **0.1510** | **0.2798** | + +
+
+ +
Toxicity score with respect to the size of the model.
+
+
+ +Below are few generation examples of `gpt-j-6b-detox` model: + +
+ +
+ +The evaluation script can be found [here](https://github.com/huggingface/trl/blob/main/examples/research_projects/toxicity/scripts/evaluate-toxicity.py). + +### Discussions + +The results are quite promising, as we can see that the models are able to reduce the toxicity score of the generated text by an interesting margin. The gap is clear for `gpt-neo-2B` model but we less so for the `gpt-j-6B` model. There are several things we could try to improve the results on the largest model starting with training with larger `mini_batch_size` and probably allowing to back-propagate through more layers (i.e. use less shared layers). + +To sum up, in addition to human feedback this could be a useful additional signal when training large language models to ensure there outputs are less toxic as well as useful. + +### Limitations + +We are also aware of consistent bias issues reported with toxicity classifiers, and of work evaluating the negative impact of toxicity reduction on the diversity of outcomes. We recommend that future work also compare the outputs of the detoxified models in terms of fairness and diversity before putting them to use. + +## What is next? + +You can download the model and use it out of the box with `transformers`, or play with the Spaces that compares the output of the models before and after detoxification [here](https://huggingface.co/spaces/ybelkada/detoxified-lms). diff --git a/testbed/huggingface__trl/docs/source/dpo_trainer.mdx b/testbed/huggingface__trl/docs/source/dpo_trainer.mdx new file mode 100644 index 0000000000000000000000000000000000000000..068f18b3121415c1fc557d98bc849af4d4031c82 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/dpo_trainer.mdx @@ -0,0 +1,283 @@ +# DPO Trainer + +[![](https://img.shields.io/badge/All_models-DPO-blue)](https://huggingface.co/models?other=dpo,trl) + +## Overview + +TRL supports the DPO Trainer for training language models from preference data, as described in the paper [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290) by [Rafael Rafailov](https://huggingface.co/rmrafailov), Archit Sharma, Eric Mitchell, [Stefano Ermon](https://huggingface.co/ermonste), [Christopher D. Manning](https://huggingface.co/manning), [Chelsea Finn](https://huggingface.co/cbfinn). + +The abstract from the paper is the following: + +> While large-scale unsupervised language models (LMs) learn broad world knowledge and some reasoning skills, achieving precise control of their behavior is difficult due to the completely unsupervised nature of their training. Existing methods for gaining such steerability collect human labels of the relative quality of model generations and fine-tune the unsupervised LM to align with these preferences, often with reinforcement learning from human feedback (RLHF). However, RLHF is a complex and often unstable procedure, first fitting a reward model that reflects the human preferences, and then fine-tuning the large unsupervised LM using reinforcement learning to maximize this estimated reward without drifting too far from the original model. In this paper we introduce a new parameterization of the reward model in RLHF that enables extraction of the corresponding optimal policy in closed form, allowing us to solve the standard RLHF problem with only a simple classification loss. The resulting algorithm, which we call Direct Preference Optimization (DPO), is stable, performant, and computationally lightweight, eliminating the need for sampling from the LM during fine-tuning or performing significant hyperparameter tuning. Our experiments show that DPO can fine-tune LMs to align with human preferences as well as or better than existing methods. Notably, fine-tuning with DPO exceeds PPO-based RLHF in ability to control sentiment of generations, and matches or improves response quality in summarization and single-turn dialogue while being substantially simpler to implement and train. + +The first step is to train an SFT model, to ensure the data we train on is in-distribution for the DPO algorithm. + +Then, fine-tuning a language model via DPO consists of two steps and is easier than [PPO](ppo_trainer): + +1. **Data collection**: Gather a [preference dataset](dataset_formats#preference) with positive and negative selected pairs of generation, given a prompt. +2. **Optimization**: Maximize the log-likelihood of the DPO loss directly. + +This process is illustrated in the sketch below (from [Figure 1 of the DPO paper](https://huggingface.co/papers/2305.18290)): + +![](https://github.com/huggingface/trl/assets/49240599/9150fac6-3d88-4ca2-8ec6-2a6f3473216d) + +Read more about DPO algorithm in the [original paper](https://huggingface.co/papers/2305.18290). + +## Quick start + +This example demonstrates how to train a model using the DPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_dpo.py +from datasets import load_dataset +from trl import DPOConfig, DPOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +train_dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +training_args = DPOConfig(output_dir="Qwen2-0.5B-DPO", logging_steps=10) +trainer = DPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_dpo.py +``` + +Distributed across 8 GPUs, the training takes approximately 3 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time. + +![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/dpo-qwen2-reward-margin.png) + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-DPO) performs, you can use the [TRL Chat CLI](clis#chat-interface). + +
$ trl chat --model_name_or_path trl-lib/Qwen2-0.5B-DPO
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-DPO>:
+The best programming language for specific applications can vary depending on the use case and knowledge level of the programmer. Here are some general factors that can be used as input to choose the best programming language:
+
+ 1 Ease of use: Some programming languages are more user-friendly than others, such as Python, Java, or Ruby. Python is popular due to its simplicity and great scalability.
+ 2 Versatility: The ability to work with a wide range of data structures and frameworks can define the language as versatile.
+ 3 Ease of learning: Different programming languages have different learning curves, so users must be willing to take some time to master one.
+ 4 Community support: The broader community of developers and enthusiasts in the selected programming language can provide great support and resources.
+ 5 Reusability: Languages that emphasize code reuse and can be easily modifiable can be more suitable for software development.
+
+The best programming language based on these factors is subjective and depends on what the programmer intends to accomplish.
+
+ +## Expected dataset type + +DPO requires a [preference dataset](dataset_formats#preference). The [`DPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +Although the [`DPOTrainer`] supports both explicit and implicit prompts, we recommend using explicit prompts. If provided with an implicit prompt dataset, the trainer will automatically extract the prompt from the `"chosen"` and `"rejected"` columns. For more information, refer to the [preference style](dataset_formats#preference) section. + +### Special considerations for vision-language models + +The [`DPOTrainer`] supports fine-tuning vision-language models (VLMs). For these models, a vision dataset is required. To learn more about the specific format for vision datasets, refer to the [Vision dataset format](dataset_formats#vision-datasets) section. + +Additionally, unlike standard text-based models where a `tokenizer` is used, for VLMs, you should replace the `tokenizer` with a `processor`. + +```diff +- model = AutoModelForCausalLM.from_pretrained(model_id) ++ model = AutoModelForVision2Seq.from_pretrained(model_id) + +- tokenizer = AutoTokenizer.from_pretrained(model_id) ++ processor = AutoProcessor.from_pretrained(model_id) + + trainer = DPOTrainer( + model, + args=training_args, + train_dataset=train_dataset, +- processing_class=tokenizer, ++ processing_class=processor, +) +``` + +For a complete example of fine-tuning a vision-language model, refer to the script in [`examples/scripts/dpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo_vlm.py). + + +## Example script + +We provide an example script to train a model using the DPO method. The script is available in [`examples/scripts/dpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo.py) + +To test the DPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command: + +```bash +accelerate launch examples/scripts/dpo.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/ultrafeedback_binarized \ + --num_train_epochs 1 \ + --logging_steps 25 \ + --output_dir Qwen2-0.5B-DPO +``` + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +- `rewards/chosen`: the mean difference between the log probabilities of the policy model and the reference model for the chosen responses scaled by beta +- `rewards/rejected`: the mean difference between the log probabilities of the policy model and the reference model for the rejected responses scaled by beta +- `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards +- `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards + +## Loss functions + +The DPO algorithm supports several loss functions. The loss function can be set using the `loss_type` parameter in the [`DPOConfig`]. The following loss functions are supported: + +| `loss_type=` | Description | +| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `"sigmoid"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model and in fact the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. | +| `"hinge"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. | +| `"ipo"` | The [IPO](https://huggingface.co/papers/2310.12036) authors provide a deeper theoretical understanding of the DPO algorithms and identify an issue with overfitting and propose an alternative loss. In this case, the `beta` is the reciprocal of the gap between the log-likelihood ratios of the chosen vs the rejected completion pair and thus the smaller the `beta` the larger this gaps is. As per the paper the loss is averaged over log-likelihoods of the completion (unlike DPO which is summed only). | +| `"exo_pair"` | The [EXO](https://huggingface.co/papers/2402.00856) authors propose to minimize the reverse KL instead of the negative log-sigmoid loss of DPO which corresponds to forward KL. Setting non-zero `label_smoothing` (default `1e-3`) leads to a simplified version of EXO on pair-wise preferences (see Eqn. (16) of the [EXO paper](https://huggingface.co/papers/2402.00856)). The full version of EXO uses `K>2` completions generated by the SFT policy, which becomes an unbiased estimator of the PPO objective (up to a constant) when `K` is sufficiently large. | +| `"nca_pair"` | The [NCA](https://huggingface.co/papers/2402.05369) authors shows that NCA optimizes the absolute likelihood for each response rather than the relative likelihood. | +| `"robust"` | The [Robust DPO](https://huggingface.co/papers/2403.00409) authors propose an unbiased estimate of the DPO loss that is robust to preference noise in the data. Like in cDPO, it assumes that the preference labels are noisy with some probability. In this approach, the `label_smoothing` parameter in the [`DPOConfig`] is used to model the probability of existing label noise. To apply this conservative loss, set `label_smoothing` to a value greater than 0.0 (between 0.0 and 0.5; the default is 0.0) | +| `"bco_pair"` | The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. For unpaired data, we recommend the dedicated [`BCOTrainer`]. | +| `"sppo_hard"` | The [SPPO](https://huggingface.co/papers/2405.00675) authors claim that SPPO is capable of solving the Nash equilibrium iteratively by pushing the chosen rewards to be as large as 1/2 and the rejected rewards to be as small as -1/2 and can alleviate data sparsity issues. The implementation approximates this algorithm by employing hard label probabilities, assigning 1 to the winner and 0 to the loser. | +| `"aot"` or `loss_type="aot_pair"` | The [AOT](https://huggingface.co/papers/2406.05882) authors propose to use Distributional Preference Alignment Via Optimal Transport. Traditionally, the alignment algorithms use paired preferences at a sample level, which does not ensure alignment on the distributional level. AOT, on the other hand, can align LLMs on paired or unpaired preference data by making the reward distribution of the positive samples stochastically dominant in the first order on the distribution of negative samples. Specifically, `loss_type="aot"` is appropriate for paired datasets, where each prompt has both chosen and rejected responses; `loss_type="aot_pair"` is for unpaired datasets. In a nutshell, `loss_type="aot"` ensures that the log-likelihood ratio of chosen to rejected of the aligned model has higher quantiles than that ratio for the reference model. `loss_type="aot_pair"` ensures that the chosen reward is higher on all quantiles than the rejected reward. Note that in both cases quantiles are obtained via sorting. To fully leverage the advantages of the AOT algorithm, it is important to maximize the per-GPU batch size. | +| `"apo_zero"` or `loss_type="apo_down"` | The [APO](https://huggingface.co/papers/2408.06266) method introduces an "anchored" version of the alignment objective. There are two variants: `apo_zero` and `apo_down`. The `apo_zero` loss increases the likelihood of winning outputs while decreasing the likelihood of losing outputs, making it suitable when the model is less performant than the winning outputs. On the other hand, `apo_down` decreases the likelihood of both winning and losing outputs, but with a stronger emphasis on reducing the likelihood of losing outputs. This variant is more effective when the model is better than the winning outputs. | +| `"discopop"` | The [DiscoPOP](https://huggingface.co/papers/2406.08414) paper uses LLMs to discover more efficient offline preference optimization losses. In the paper the proposed DiscoPOP loss (which is a log-ratio modulated loss) outperformed other optimization losses on different tasks (IMDb positive text generation, Reddit TLDR summarization, and Alpaca Eval 2.0). | + +### Label smoothing + +The [cDPO](https://ericmitchell.ai/cdpo.pdf) is a tweak on the DPO loss where we assume that the preference labels are noisy with some probability. In this approach, the `label_smoothing` parameter in the [`DPOConfig`] is used to model the probability of existing label noise. To apply this conservative loss, set `label_smoothing` to a value greater than 0.0 (between 0.0 and 0.5; the default is 0.0). + +### Syncing the reference model + +The [TR-DPO](https://huggingface.co/papers/2404.09656) paper suggests syncing the reference model weights after every `ref_model_sync_steps` steps of SGD with weight `ref_model_mixup_alpha` during DPO training. To toggle this callback use the `sync_ref_model=True` in the [`DPOConfig`]. + +### RPO loss + +The [RPO](https://huggingface.co/papers/2404.19733) paper implements an iterative preference tuning algorithm using a loss related to the RPO loss in this [paper](https://huggingface.co/papers/2405.16436) that essentially consists of a weighted SFT loss on the chosen preferences together with the DPO loss. To use this loss, set the `rpo_alpha` in the [`DPOConfig`] to an appropriate value. The paper suggests setting this weight to `1.0`. + +### WPO loss + +The [WPO](https://huggingface.co/papers/2406.11827) paper adapts off-policy data to resemble on-policy data more closely by reweighting preference pairs according to their probability under the current policy. To use this method, set the `use_weighting` flag to `True` in the [`DPOConfig`]. + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. [`~transformers.MixtralConfig`]). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config. + +## Accelerate DPO fine-tuning using `unsloth` + +You can further accelerate QLoRA / LoRA (2x faster, 60% less memory) using the [`unsloth`](https://github.com/unslothai/unsloth) library that is fully compatible with `SFTTrainer`. Currently `unsloth` supports only Llama (Yi, TinyLlama, Qwen, Deepseek etc) and Mistral architectures. Some benchmarks for DPO listed below: + +| GPU | Model | Dataset | 🤗 | 🤗 + Flash Attention 2 | 🦥 Unsloth | 🦥 VRAM saved | +| -------- | --------- | ---------- | --- | --------------------- | --------- | ------------ | +| A100 40G | Zephyr 7b | Ultra Chat | 1x | 1.24x | **1.88x** | -11.6% | +| Tesla T4 | Zephyr 7b | Ultra Chat | 1x | 1.09x | **1.55x** | -18.6% | + +First install `unsloth` according to the [official documentation](https://github.com/unslothai/unsloth). Once installed, you can incorporate unsloth into your workflow in a very simple manner; instead of loading `AutoModelForCausalLM`, you just need to load a `FastLanguageModel` as follows: + +```diff + from datasets import load_dataset + from trl import DPOConfig, DPOTrainer +- from transformers import AutoModelForCausalLM, AutoTokenizer ++ from unsloth import FastLanguageModel + +- model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +- tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") ++ model, tokenizer = FastLanguageModel.from_pretrained("Qwen/Qwen2-0.5B-Instruct") ++ model = FastLanguageModel.get_peft_model(model) + train_dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") + +- training_args = DPOConfig(output_dir="Qwen2-0.5B-DPO", logging_steps=10) ++ training_args = DPOConfig(output_dir="Qwen2-0.5B-DPO", logging_steps=10, bf16=True) + trainer = DPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) + trainer.train() + +``` + +The saved model is fully compatible with Hugging Face's transformers library. Learn more about unsloth in their [official repository](https://github.com/unslothai/unsloth). + +## Reference model considerations with PEFT + +You have three main options (plus several variants) for how the reference model works when using PEFT, assuming the model that you would like to further enhance with DPO was tuned using (Q)LoRA. + +1. Simply create two instances of the model, each loading your adapter - works fine but is very inefficient. +2. Merge the adapter into the base model, create another adapter on top, then leave the `ref_model` param null, in which case DPOTrainer will unload the adapter for reference inference - efficient, but has potential downsides discussed below. +3. Load the adapter twice with different names, then use `set_adapter` during training to swap between the adapter being DPO'd and the reference adapter - slightly less efficient compared to 2 (~adapter size VRAM overhead), but avoids the pitfalls. + +### Downsides to merging QLoRA before DPO (approach 2) + +As suggested by [Benjamin Marie](https://medium.com/@bnjmn_marie/dont-merge-your-lora-adapter-into-a-4-bit-llm-65b6da287997), the best option for merging QLoRA adapters is to first dequantize the base model, then merge the adapter. Something similar to [this script](https://github.com/jondurbin/qlora/blob/main/qmerge.py). + +However, after using this approach, you will have an unquantized base model. Therefore, to use QLoRA for DPO, you will need to re-quantize the merged model or use the unquantized merge (resulting in higher memory demand). + +### Using option 3 - load the adapter twice + +To avoid the downsides with option 2, you can load your fine-tuned adapter into the model twice, with different names, and set the model/ref adapter names in [`DPOTrainer`]. + +For example: + +```python +# Load the base model. +bnb_config = BitsAndBytesConfig( + load_in_4bit=True, + llm_int8_threshold=6.0, + llm_int8_has_fp16_weight=False, + bnb_4bit_compute_dtype=torch.bfloat16, + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", +) +model = AutoModelForCausalLM.from_pretrained( + "mistralai/mixtral-8x7b-v0.1", + load_in_4bit=True, + quantization_config=bnb_config, + attn_implementation="flash_attention_2", + torch_dtype=torch.bfloat16, + device_map="auto", +) +model.config.use_cache = False + +# Load the adapter. +model = PeftModel.from_pretrained( + model, + "/path/to/peft", + is_trainable=True, + adapter_name="train", +) +# Load the adapter a second time, with a different name, which will be our reference model. +model.load_adapter("/path/to/peft", adapter_name="reference") + +# Initialize the trainer, without a ref_model param. +training_args = DPOConfig( + model_adapter_name="train", + ref_adapter_name="reference", +) +dpo_trainer = DPOTrainer( + model, + args=training_args, + ... +) +``` + +## DPOTrainer + +[[autodoc]] DPOTrainer + +## DPOConfig + +[[autodoc]] DPOConfig + +## PreferenceCollator + +[[autodoc]] trainer.dpo_trainer.PreferenceCollator \ No newline at end of file diff --git a/testbed/huggingface__trl/docs/source/example_overview.md b/testbed/huggingface__trl/docs/source/example_overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d239199810642141ed1979d68b1da371196a9da9 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/example_overview.md @@ -0,0 +1,82 @@ +# Examples + + +## Introduction + +The examples should work in any of the following settings (with the same script): + - single GPU + - multi GPUS (using PyTorch distributed mode) + - multi GPUS (using DeepSpeed ZeRO-Offload stages 1, 2, & 3) + - fp16 (mixed-precision), fp32 (normal precision), or bf16 (bfloat16 precision) + +To run it in each of these various modes, first initialize the accelerate +configuration with `accelerate config` + +**NOTE to train with a 4-bit or 8-bit model**, please run + +```bash +pip install --upgrade trl[quantization] +``` + + +## Accelerate Config +For all the examples, you'll need to generate a 🤗 Accelerate config file with: + +```shell +accelerate config # will prompt you to define the training configuration +``` + +Then, it is encouraged to launch jobs with `accelerate launch`! + + +# Maintained Examples + + + +| File | Description | +| ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [`examples/scripts/alignprop.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/alignprop.py) | This script shows how to use the [`AlignPropTrainer`] to fine-tune a diffusion model. | +| [`examples/scripts/bco.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/bco.py) | This script shows how to use the [`KTOTrainer`] with the BCO loss to fine-tune a model to increase instruction-following, truthfulness, honesty and helpfulness using the [openbmb/UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) dataset. | +| [`examples/scripts/chat.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/chat.py) | This script allows you to load and use a model as a chatbot. | +| [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py) | This script shows how to use the [`CPOTrainer`] to fine-tune a model to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. | +| [`examples/scripts/ddpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ddpo.py) | This script shows how to use the [`DDPOTrainer`] to fine-tune a stable diffusion model using reinforcement learning. | +| [`examples/scripts/dpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo_vlm.py) | This script shows how to use the [`DPOTrainer`] to fine-tune a Vision Language Model to reduce hallucinations using the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset) dataset. | +| [`examples/scripts/dpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo.py) | This script shows how to use the [`DPOTrainer`] to fine-tune a stable to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. | +| [`examples/scripts/kto.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/kto.py) | This script shows how to use the [`KTOTrainer`] to fine-tune a model. | +| [`examples/scripts/orpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/orpo.py) | This script shows how to use the [`ORPOTrainer`] to fine-tune a model to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. | +| [`examples/scripts/ppo/ppo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo/ppo.py) | This script shows how to use the [`PPOTrainer`] to fine-tune a model to improve its ability to continue text with positive sentiment or physically descriptive language | +| [`examples/scripts/ppo/ppo_tldr.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo/ppo_tldr.py) | This script shows how to use the [`PPOTrainer`] to fine-tune a model to improve its ability to generate TL;DR summaries. | +| [`examples/scripts/reward_modeling.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/reward_modeling.py) | This script shows how to use the [`RewardTrainer`] to train a reward model on your own dataset. | +| [`examples/scripts/sft.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a model or adapters into a target dataset. | +| [`examples/scripts/sft_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Vision Language Model in a chat setting. The script has only been tested with [LLaVA 1.5](https://huggingface.co/llava-hf/llava-1.5-7b-hf), [LLaVA 1.6](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf), and [Llama-3.2-11B-Vision-Instruct](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct) models so users may see unexpected behaviour in other model architectures. | + +Here are also some easier-to-run colab notebooks that you can use to get started with TRL: + +| File | Description | +| --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| [`examples/notebooks/best_of_n.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/best_of_n.ipynb) | This notebook demonstrates how to use the "Best of N" sampling strategy using TRL when fine-tuning your model with PPO. | +| [`examples/notebooks/gpt2-sentiment.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/gpt2-sentiment.ipynb) | This notebook demonstrates how to reproduce the GPT2 imdb sentiment tuning example on a jupyter notebook. | +| [`examples/notebooks/gpt2-control.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/gpt2-control.ipynb) | This notebook demonstrates how to reproduce the GPT2 sentiment control example on a jupyter notebook. | + + +We also have some other examples that are less maintained but can be used as a reference: +1. **[research_projects](https://github.com/huggingface/trl/tree/main/examples/research_projects)**: Check out this folder to find the scripts used for some research projects that used TRL (LM de-toxification, Stack-Llama, etc.) + + +## Distributed training + +All of the scripts can be run on multiple GPUs by providing the path of an 🤗 Accelerate config file when calling `accelerate launch`. To launch one of them on one or multiple GPUs, run the following command (swapping `{NUM_GPUS}` with the number of GPUs in your machine and `--all_arguments_of_the_script` with your arguments.) + +```shell +accelerate launch --config_file=examples/accelerate_configs/multi_gpu.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script +``` + +You can also adjust the parameters of the 🤗 Accelerate config file to suit your needs (e.g. training in mixed precision). + +### Distributed training with DeepSpeed + +Most of the scripts can be run on multiple GPUs together with DeepSpeed ZeRO-{1,2,3} for efficient sharding of the optimizer states, gradients, and model weights. To do so, run following command (swapping `{NUM_GPUS}` with the number of GPUs in your machine, `--all_arguments_of_the_script` with your arguments, and `--deepspeed_config` with the path to the DeepSpeed config file such as `examples/deepspeed_configs/deepspeed_zero1.yaml`): + +```shell +accelerate launch --config_file=examples/accelerate_configs/deepspeed_zero{1,2,3}.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script +``` diff --git a/testbed/huggingface__trl/docs/source/gkd_trainer.md b/testbed/huggingface__trl/docs/source/gkd_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f82ff1605df5217b015ee77003a309d7a3a1c4 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/gkd_trainer.md @@ -0,0 +1,98 @@ +# Generalized Knowledge Distillation Trainer + +[![](https://img.shields.io/badge/All_models-GKD-blue)](https://huggingface.co/models?other=gkd,trl) + +## Overview + +Generalized Knowledge Distillation (GKD) was proposed in [On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes](https://huggingface.co/papers/2306.13649) by Rishabh Agarwal, Nino Vieillard, Yongchao Zhou, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem. + +The abstract from the paper is the following: + +> Knowledge distillation (KD) is widely used for compressing a teacher model to reduce its inference cost and memory footprint, by training a smaller student model. However, current KD methods for auto-regressive sequence models suffer from distribution mismatch between output sequences seen during training and those generated by the student during inference. To address this issue, we introduce Generalized Knowledge Distillation (GKD). Instead of solely relying on a fixed set of output sequences, GKD trains the student on its self-generated output sequences by leveraging feedback from the teacher on such sequences. Unlike supervised KD approaches, GKD also offers the flexibility to employ alternative loss functions between the student and teacher, which can be useful when the student lacks the expressivity to mimic the teacher's distribution. Furthermore, GKD facilitates the seamless integration of distillation with RL fine-tuning (RLHF). We demonstrate the efficacy of GKD for distilling auto-regressive language models on summarization, translation, and arithmetic reasoning tasks, and task-agnostic distillation for instruction-tuning. + + +The key aspects of GKD are: +1. It addresses the train-inference distribution mismatch in auto-regressive sequence models by training the student model on its self-generated output sequences. +2. GKD allows flexibility in choosing different divergence measures between student and teacher models via the generalized Jensen-Shannon Divergence (JSD), which can be useful when the student lacks the capacity to fully mimic the teacher. + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and [Lewis Tunstall](https://huggingface.co/lewtun). + +## Usage tips + +The [`GKDTrainer`] is a wrapper around the [`SFTTrainer`] class that takes in a teacher model argument. It needs three parameters to be set via the [`GKDConfig`] namely: +* `lmbda`: controls the student data fraction, i.e., the proportion of on-policy student-generated outputs. When `lmbda=0.0`, the loss reduces to supervised JSD where the student is trained with the token-level probabilities of the teacher. When `lmbda=1.0`, the loss reduces to on-policy JSD, where the student generates output sequences and token-specific feedback on these sequences from the teacher. For values in between [0, 1] it is random between the two based on the `lmbda` value for each batch. +* `seq_kd`: controls whether to perform Sequence-Level KD (can be viewed as supervised FT on teacher-generated out). When `seq_kd=True` and `lmbda=0.0`, the loss reduces to supervised JSD, where the teacher generates output sequences and the student receives token-specific feedback on these sequences from the teacher. +* `beta`: controls the interpolation in the generalized Jensen-Shannon Divergence. When `beta=0.0` the loss approximates forward KL divergence, while for `beta=1.0` the loss approximates reverse KL divergence. For values in between [0, 1] it interpolates between the two. + +The authors find that on-policy data (high `lmbda`) performs better and the optimal `beta` varied depending on the task and evaluation method. + +> [!WARNING] +> Make sure that `attn_implementation="flash_attention_2"` when training [Gemma models](https://huggingface.co/models?other=gemma2). Otherwise you will encounter NaNs in the logits due to the [soft capping technique](https://huggingface.co/blog/gemma2#soft-capping-and-attention-implementations) adopted by this architecture. + +The basic API is as follows: + +```python +from datasets import Dataset +from trl import GKDConfig, GKDTrainer +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, +) + +NUM_DUMMY_SAMPLES = 100 + +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +# The model to optimise +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +# The teacher model to calculate the KL divergence against +teacher_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-1.5B-Instruct") + +train_dataset = Dataset.from_dict( + { + "messages": [ + [ + {"role": "user", "content": "Hi, how are you?"}, + {"role": "assistant", "content": "I'm great thanks"}, + ] + ] + * NUM_DUMMY_SAMPLES + } +) +eval_dataset = Dataset.from_dict( + { + "messages": [ + [ + {"role": "user", "content": "What colour is the sky?"}, + {"role": "assistant", "content": "The sky is blue"}, + ] + ] + * NUM_DUMMY_SAMPLES + } +) + +training_args = GKDConfig(output_dir="gkd-model", per_device_train_batch_size=1) +trainer = GKDTrainer( + model=model, + teacher_model=teacher_model, + args=training_args, + processing_class=tokenizer, + train_dataset=train_dataset, + eval_dataset=eval_dataset, +) +trainer.train() +``` + +### Expected dataset type + +The dataset should be formatted as a list of "messages" where each message is a list of dictionaries with the following keys: +* `role`: either `system`, `assistant` or `user` +* `content`: the message content + + +## GKDTrainer + +[[autodoc]] GKDTrainer + +## GKDConfig + +[[autodoc]] GKDConfig diff --git a/testbed/huggingface__trl/docs/source/how_to_train.md b/testbed/huggingface__trl/docs/source/how_to_train.md new file mode 100644 index 0000000000000000000000000000000000000000..bac324e43bdc20a7519105bd94963531b3a590e6 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/how_to_train.md @@ -0,0 +1,65 @@ +# Training FAQ + +## What Metrics Should I Look at? + +When performing classical supervised fine-tuning of language models, the loss (especially the validation loss) serves as a good indicator of the training progress. However, in Reinforcement Learning (RL), the loss becomes less informative about the model's performance, and its value may fluctuate while the actual performance improves. + +To address this, we recommend focusing on two key metrics first: + +**Mean Reward**: The primary goal is to maximize the reward achieved by the model during RL training. +**Objective KL Divergence**: KL divergence (Kullback-Leibler divergence) measures the dissimilarity between two probability distributions. In the context of RL training, we use it to quantify the difference between the current model and a reference model. Ideally, we want to keep the KL divergence between 0 and 10 to ensure the model's generated text remains close to what the reference model produces. + +However, there are more metrics that can be useful for debugging, checkout the [logging section](logging). + +## Why Do We Use a Reference Model, and What's the Purpose of KL Divergence? + +When training RL models, optimizing solely for reward may lead to unexpected behaviors, where the model exploits the environment in ways that don't align with good language generation. In the case of RLHF, we use a reward model trained to predict whether a generated text is highly ranked by humans. + +However, the RL model being optimized against the reward model may learn patterns that yield high reward but do not represent good language. This can result in extreme cases where the model generates texts with excessive exclamation marks or emojis to maximize the reward. In some worst-case scenarios, the model may generate patterns completely unrelated to natural language yet receive high rewards, similar to adversarial attacks. + +
+ +

Figure: Samples without a KL penalty from https://huggingface.co/papers/1909.08593.

+
+ +To address this issue, we add a penalty to the reward function based on the KL divergence between the current model and the reference model. By doing this, we encourage the model to stay close to what the reference model generates. + +## What Is the Concern with Negative KL Divergence? + +If you generate text by purely sampling from the model distribution things work fine in general. But when you use the `generate` method there are a few caveats because it does not always purely sample depending on the settings which can cause KL-divergence to go negative. Essentially when the active model achieves `log_p_token_active < log_p_token_ref` we get negative KL-div. This can happen in a several cases: + +- **top-k sampling**: the model can smooth out the probability distribution causing the top-k tokens having a smaller probability than those of the reference model but they still are selected +- **min_length**: this ignores the EOS token until `min_length` is reached. thus the model can assign a very low log prob to the EOS token and very high probs to all others until min_length is reached + +These are just a few examples. Why is negative KL an issue? The total reward `R` is computed `R = r - beta * KL` so if the model can learn how to drive KL-divergence negative it effectively gets a positive reward. In many cases it can be much easier to exploit such a bug in the generation than actually learning the reward function. In addition the KL can become arbitrarily small thus the actual reward can be very small compared to it. + +So how should you generate text for PPO training? Let's have a look! + +## How to generate text for training? + +In order to avoid the KL issues described above we recommend to use the following settings: + +```python +generation_kwargs = { + "min_length": -1, # don't ignore the EOS token (see above) + "top_k": 0.0, # no top-k sampling + "top_p": 1.0, # no nucleus sampling + "do_sample": True, # yes, we want to sample + "pad_token_id": tokenizer.eos_token_id, # most decoder models don't have a padding token - use EOS token instead + "max_new_tokens": 32, # specify how many tokens you want to generate at most +} +``` + +With these settings we usually don't encounter any issues. You can also experiments with other settings but if you encounter issues with negative KL-divergence try to go back to these and see if they persist. + +## How can debug your own use-case? + +Debugging the RL pipeline can be challenging due to its complexity. Here are some tips and suggestions to make the process easier: + +- **Start from a working example**: Begin with a working example from the trl repository and gradually modify it to fit your specific use-case. Changing everything at once can make it difficult to identify the source of potential issues. For example, you can start by replacing the model in the example and once you figure out the best hyperparameters try to switch to your dataset and reward model. If you change everything at once you won't know where a potential problem comes from. +- **Start small, scale later**: Training large models can be very slow and take several hours or days until you see any improvement. For debugging this is not a convenient timescale so try to use small model variants during the development phase and scale up once that works. That being said you sometimes have to be careful as small models might not have the capacity to solve a complicated task either. +- **Start simple**: Try to start with a minimal example and build complexity from there. Your use-case might require for example a complicated reward function consisting of many different rewards - try to use one signal first and see if you can optimize that and then add more complexity after that. +- **Inspect the generations**: It's always a good idea to inspect what the model is generating. Maybe there is a bug in your post-processing or your prompt. Due to bad settings you might cut-off generations too soon. These things are very hard to see on the metrics but very obvious if you look at the generations. +- **Inspect the reward model**: If you reward is not improving over time maybe there's an issue with the reward model. You can look at extreme cases to see if it does what it should: e.g. in the sentiment case you can check if simple positive and negative examples really get different rewards. And you can look at the distribution of your dataset. Finally, maybe the reward is dominated by the query which the model can't affect so you might need to normalize this (e.g. reward of query+response minus reward of the query). + +These are just a few tips that we find helpful - if you have more useful tricks feel free to open a PR to add them as well! diff --git a/testbed/huggingface__trl/docs/source/index.mdx b/testbed/huggingface__trl/docs/source/index.mdx new file mode 100644 index 0000000000000000000000000000000000000000..bdddc9b6f2e6125c94eed6c6f8fb9841f39c5368 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/index.mdx @@ -0,0 +1,76 @@ +
+ +
+ +# TRL - Transformer Reinforcement Learning + +TRL is a full stack library where we provide a set of tools to train transformer language models with Reinforcement Learning, from the Supervised Fine-tuning step (SFT), Reward Modeling step (RM) to the Proximal Policy Optimization (PPO) step. +The library is integrated with 🤗 [transformers](https://github.com/huggingface/transformers). + +
+ +
+ +Check the appropriate sections of the documentation depending on your needs: + +## API documentation + +- [Model Classes](models): *A brief overview of what each public model class does.* +- [`SFTTrainer`](sft_trainer): *Supervise Fine-tune your model easily with `SFTTrainer`* +- [`RewardTrainer`](reward_trainer): *Train easily your reward model using `RewardTrainer`.* +- [`PPOTrainer`](ppo_trainer): *Further fine-tune the supervised fine-tuned model using PPO algorithm* +- [Best-of-N Sampling](best-of-n): *Use best of n sampling as an alternative way to sample predictions from your active model* +- [`DPOTrainer`](dpo_trainer): *Direct Preference Optimization training using `DPOTrainer`.* +- [`TextEnvironment`](text_environments): *Text environment to train your model using tools with RL.* + +## Examples + +- [Sentiment Tuning](sentiment_tuning): *Fine tune your model to generate positive movie contents* +- [Training with PEFT](lora_tuning_peft): *Memory efficient RLHF training using adapters with PEFT* +- [Detoxifying LLMs](detoxifying_a_lm): *Detoxify your language model through RLHF* +- [StackLlama](using_llama_models): *End-to-end RLHF training of a Llama model on Stack exchange dataset* +- [Learning with Tools](learning_tools): *Walkthrough of using `TextEnvironments`* +- [Multi-Adapter Training](multi_adapter_rl): *Use a single base model and multiple adapters for memory efficient end-to-end training* + + +## Blog posts + + diff --git a/testbed/huggingface__trl/docs/source/iterative_sft_trainer.mdx b/testbed/huggingface__trl/docs/source/iterative_sft_trainer.mdx new file mode 100644 index 0000000000000000000000000000000000000000..7a4fabbf6367a3b8843cc63c98f5286e872930fc --- /dev/null +++ b/testbed/huggingface__trl/docs/source/iterative_sft_trainer.mdx @@ -0,0 +1,57 @@ +# Iterative Trainer + +[![](https://img.shields.io/badge/All_models-Iterative_SFT-blue)](https://huggingface.co/models?other=iterative-sft,trl) + + +Iterative fine-tuning is a training method that enables to perform custom actions (generation and filtering for example) between optimization steps. In TRL we provide an easy-to-use API to fine-tune your models in an iterative way in just a few lines of code. + +## Usage + +To get started quickly, instantiate an instance a model, and a tokenizer. + +```python + +model = AutoModelForCausalLM.from_pretrained(model_name) +tokenizer = AutoTokenizer.from_pretrained(model_name) +if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + +trainer = IterativeSFTTrainer( + model, + tokenizer +) + +``` + +You have the choice to either provide a list of strings or a list of tensors to the step function. + +#### Using a list of tensors as input: + +```python + +inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask +} + +trainer.step(**inputs) + +``` + +#### Using a list of strings as input: + +```python + +inputs = { + "texts": texts +} + +trainer.step(**inputs) + +``` + +For causal language models, labels will automatically be created from input_ids or from texts. When using sequence to sequence models you will have to provide your own labels or text_labels. + +## IterativeTrainer + +[[autodoc]] IterativeSFTTrainer diff --git a/testbed/huggingface__trl/docs/source/judges.mdx b/testbed/huggingface__trl/docs/source/judges.mdx new file mode 100644 index 0000000000000000000000000000000000000000..d3fd1634161e76b34968008fb00998444296ebd9 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/judges.mdx @@ -0,0 +1,89 @@ +# Judges + + + +TRL Judges is an experimental API which is subject to change at any time. + + + +TRL provides judges to easily compare two completions. + +Make sure to have installed the required dependencies by running: + +```bash +pip install trl[judges] +``` + +## Using the provided judges + +TRL provides several judges out of the box. For example, you can use the `HfPairwiseJudge` to compare two completions using a pre-trained model from the Hugging Face model hub: + +```python +from trl import HfPairwiseJudge + +judge = HfPairwiseJudge() +judge.judge( + prompts=["What is the capital of France?", "What is the biggest planet in the solar system?"], + completions=[["Paris", "Lyon"], ["Saturn", "Jupiter"]], +) # Outputs: [0, 1] +``` + +## Define your own judge + +To define your own judge, we provide several base classes that you can subclass. For rank-based judges, you need to subclass [`BaseRankJudge`] and implement the [`BaseRankJudge.judge`] method. For pairwise judges, you need to subclass [`BasePairJudge`] and implement the [`BasePairJudge.judge`] method. If you want to define a judge that doesn't fit into these categories, you need to subclass [`BaseJudge`] and implement the [`BaseJudge.judge`] method. + +As an example, let's define a pairwise judge that prefers shorter completions: + +```python +from trl import BasePairwiseJudge + +class PrefersShorterJudge(BasePairwiseJudge): + def judge(self, prompts, completions, shuffle_order=False): + return [0 if len(completion[0]) > len(completion[1]) else 1 for completion in completions] +``` + +You can then use this judge as follows: + +```python +judge = PrefersShorterJudge() +judge.judge( + prompts=["What is the capital of France?", "What is the biggest planet in the solar system?"], + completions=[["Paris", "The capital of France is Paris."], ["Jupiter is the biggest planet in the solar system.", "Jupiter"]], +) # Outputs: [0, 1] +``` + +## Provided judges + +### PairRMJudge + +[[autodoc]] PairRMJudge + +### HfPairwiseJudge + +[[autodoc]] HfPairwiseJudge + +### OpenAIPairwiseJudge + +[[autodoc]] OpenAIPairwiseJudge + +### AllTrueJudge + +[[autodoc]] AllTrueJudge + +## Base classes + +### BaseJudge + +[[autodoc]] BaseJudge + +### BaseBinaryJudge + +[[autodoc]] BaseBinaryJudge + +### BaseRankJudge + +[[autodoc]] BaseRankJudge + +### BasePairwiseJudge + +[[autodoc]] BasePairwiseJudge diff --git a/testbed/huggingface__trl/docs/source/kto_trainer.mdx b/testbed/huggingface__trl/docs/source/kto_trainer.mdx new file mode 100644 index 0000000000000000000000000000000000000000..1ed6a336138e2d4ed220adb9dbe69b6c5af60603 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/kto_trainer.mdx @@ -0,0 +1,139 @@ +# KTO Trainer + +[![](https://img.shields.io/badge/All_models-KTO-blue)](https://huggingface.co/models?other=kto,trl) + +## Overview + +Kahneman-Tversky Optimization (KTO) was introduced in [KTO: Model Alignment as Prospect Theoretic Optimization](https://huggingface.co/papers/2402.01306) by [Kawin Ethayarajh](https://huggingface.co/kawine), [Winnie Xu](https://huggingface.co/xwinxu), [Niklas Muennighoff](https://huggingface.co/Muennighoff), Dan Jurafsky, [Douwe Kiela](https://huggingface.co/douwekiela). + + +The abstract from the paper is the following: + +> Kahneman & Tversky's prospect theory tells us that humans perceive random variables in a biased but well-defined manner; for example, humans are famously loss-averse. We show that objectives for aligning LLMs with human feedback implicitly incorporate many of these biases -- the success of these objectives (e.g., DPO) over cross-entropy minimization can partly be ascribed to them being human-aware loss functions (HALOs). However, the utility functions these methods attribute to humans still differ from those in the prospect theory literature. Using a Kahneman-Tversky model of human utility, we propose a HALO that directly maximizes the utility of generations instead of maximizing the log-likelihood of preferences, as current methods do. We call this approach Kahneman-Tversky Optimization (KTO), and it matches or exceeds the performance of preference-based methods at scales from 1B to 30B. Crucially, KTO does not need preferences -- only a binary signal of whether an output is desirable or undesirable for a given input. This makes it far easier to use in the real world, where preference data is scarce and expensive. + +The official code can be found in [ContextualAI/HALOs](https://github.com/ContextualAI/HALOs). + +This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif), [Younes Belkada](https://huggingface.co/ybelkada), [Lewis Tunstall](https://huggingface.co/lewtun) and Pablo Vicente. + +## Quick start + +This example demonstrates how to train a model using the KTO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [KTO Mix 14k](https://huggingface.co/datasets/trl-lib/kto-mix-14k). You can view the data in the dataset here: + + + +Below is the script to train the model: + +```python +# train_kto.py +from datasets import load_dataset +from trl import KTOConfig, KTOTrainer +from transformers import AutoModelForCausalLM, AutoTokenizer + +model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") +train_dataset = load_dataset("trl-lib/kto-mix-14k", split="train") + +training_args = KTOConfig(output_dir="Qwen2-0.5B-KTO", logging_steps=10) +trainer = KTOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset) +trainer.train() +``` + +Execute the script using the following command: + +```bash +accelerate launch train_kto.py +``` + +Distributed across 8 x H100 GPUs, the training takes approximately 30 minutes. You can verify the training progress by checking the reward graph. An increasing trend in the reward margin indicates that the model is improving and generating better responses over time. + +![](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/kto-qwen2-reward-margin.png) + +To see how the [trained model](https://huggingface.co/trl-lib/Qwen2-0.5B-KTO) performs, you can use the [TRL Chat CLI](clis#chat-interface). + +
$ trl chat --model_name_or_path trl-lib/Qwen2-0.5B-KTO
+<quentin_gallouedec>:
+What is the best programming language?
+
+<trl-lib/Qwen2-0.5B-KTO>:
+The best programming language can vary depending on individual preferences, industry-specific requirements, technical skills, and familiarity with the specific use case or task. Here are some widely-used programming languages that have been noted as popular and widely used:                                                                                  
+
+Here are some other factors to consider when choosing a programming language for a project:
+
+ 1 JavaScript: JavaScript is at the heart of the web and can be used for building web applications, APIs, and interactive front-end applications like frameworks like React and Angular. It's similar to C, C++, and F# in syntax structure and is accessible and easy to learn, making it a popular choice for beginners and professionals alike.                                                                   
+ 2 Java: Known for its object-oriented programming (OOP) and support for Java 8 and .NET, Java is used for developing enterprise-level software applications, high-performance games, as well as mobile apps, game development, and desktop applications.                                                                                                                                                            
+ 3 C++: Known for its flexibility and scalability, C++ offers comprehensive object-oriented programming and is a popular choice for high-performance computing and other technical fields. It's a powerful platform for building real-world applications and games at scale.                                                                                                                                         
+ 4 Python: Developed by Guido van Rossum in 1991, Python is a high-level, interpreted, and dynamically typed language known for its simplicity, readability, and versatility.   
+
+ +## Expected dataset format + +KTO requires an [unpaired preference dataset](dataset_formats#unpaired-preference). Alternatively, you can provide a *paired* preference dataset (also known simply as a *preference dataset*). In this case, the trainer will automatically convert it to an unpaired format by separating the chosen and rejected responses, assigning `label = True` to the chosen completions and `label = False` to the rejected ones. + +The [`KTOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset format. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset. + +In theory, the dataset should contain at least one chosen and one rejected completion. However, some users have successfully run KTO using *only* chosen or only rejected data. If using only rejected data, it is advisable to adopt a conservative learning rate. + +## Example script + +We provide an example script to train a model using the KTO method. The script is available in [`examples/scripts/kto.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/kto.py) + +To test the KTO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/kto-mix-14k), run the following command: + +```bash +accelerate launch examples/scripts/kto.py \ + --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ + --dataset_name trl-lib/kto-mix-14k \ + --num_train_epochs 1 \ + --logging_steps 25 \ + --output_dir Qwen2-0.5B-KTO +``` + +## Usage tips + +### For Mixture of Experts Models: Enabling the auxiliary loss + +MOEs are the most efficient if the load is about equally distributed between experts. +To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss. + +This option is enabled by setting `output_router_logits=True` in the model config (e.g. [`~transformers.MixtralConfig`]). +To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config. + + +### Batch size recommendations + +Use a per-step batch size that is at least 4, and an effective batch size between 16 and 128. Even if your effective batch size is large, if your per-step batch size is poor, then the KL estimate in KTO will be poor. + +### Learning rate recommendations + +Each choice of `beta` has a maximum learning rate it can tolerate before learning performance degrades. For the default setting of `beta = 0.1`, the learning rate should typically not exceed `1e-6` for most models. As `beta` decreases, the learning rate should also be reduced accordingly. In general, we strongly recommend keeping the learning rate between `5e-7` and `5e-6`. Even with small datasets, we advise against using a learning rate outside this range. Instead, opt for more epochs to achieve better results. + +### Imbalanced data + +The `desirable_weight` and `undesirable_weight` of the [`KTOConfig`] refer to the weights placed on the losses for desirable/positive and undesirable/negative examples. +By default, they are both 1. However, if you have more of one or the other, then you should upweight the less common type such that the ratio of (`desirable_weight` \\(\times\\) number of positives) to (`undesirable_weight` \\(\times\\) number of negatives) is in the range 1:1 to 4:3. + +## Logged metrics + +While training and evaluating we record the following reward metrics: + +- `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta +- `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta +- `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards +- `logps/chosen`: the mean log probabilities of the chosen completions +- `logps/rejected`: the mean log probabilities of the rejected completions +- `logits/chosen`: the mean logits of the chosen completions +- `logits/rejected`: the mean logits of the rejected completions +- `kl`: the KL divergence between the policy model and the reference model + +## KTOTrainer + +[[autodoc]] KTOTrainer + +## KTOConfig + +[[autodoc]] KTOConfig diff --git a/testbed/huggingface__trl/docs/source/logging.mdx b/testbed/huggingface__trl/docs/source/logging.mdx new file mode 100644 index 0000000000000000000000000000000000000000..4c60868daca05337518aab4c9e6eb31bbe5bdad5 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/logging.mdx @@ -0,0 +1,74 @@ +# Logging + +As reinforcement learning algorithms are historically challenging to debug, it's important to pay careful attention to logging. +By default, the TRL [`PPOTrainer`] saves a lot of relevant information to wandb or tensorboard. + +Upon initialization, pass one of these two options to the [`PPOConfig`]: + +``` +training_args = PPOConfig(..., report_to="wandb") # or "tensorboard" +``` + +If you want to log with tensorboard, add the kwarg `project_kwargs={"logging_dir": PATH_TO_LOGS}` to the PPOConfig. + +## PPO Logging + +Here's a brief explanation for the logged metrics provided in the data: + +Key metrics to monitor. We want to maximize the reward, maintain a low KL divergence, and maximize entropy: +1. `env/reward_mean`: The average reward obtained from the environment. Alias `ppo/mean_scores`, which is sed to specifically monitor the reward model. +1. `env/reward_std`: The standard deviation of the reward obtained from the environment. Alias ``ppo/std_scores`, which is sed to specifically monitor the reward model. +1. `env/reward_dist`: The histogram distribution of the reward obtained from the environment. +1. `objective/kl`: The mean Kullback-Leibler (KL) divergence between the old and new policies. It measures how much the new policy deviates from the old policy. The KL divergence is used to compute the KL penalty in the objective function. +1. `objective/kl_dist`: The histogram distribution of the `objective/kl`. +1. `objective/kl_coef`: The coefficient for Kullback-Leibler (KL) divergence in the objective function. +1. `ppo/mean_non_score_reward`: The **KL penalty** calculated by `objective/kl * objective/kl_coef` as the total reward for optimization to prevent the new policy from deviating too far from the old policy. +1. `objective/entropy`: The entropy of the model's policy, calculated by `-logprobs.sum(-1).mean()`. High entropy means the model's actions are more random, which can be beneficial for exploration. + +Training stats: +1. `ppo/learning_rate`: The learning rate for the PPO algorithm. +1. `ppo/policy/entropy`: The entropy of the model's policy, calculated by `pd = torch.nn.functional.softmax(logits, dim=-1); entropy = torch.logsumexp(logits, dim=-1) - torch.sum(pd * logits, dim=-1)`. It measures the randomness of the policy. +1. `ppo/policy/clipfrac`: The fraction of probability ratios (old policy / new policy) that fell outside the clipping range in the PPO objective. This can be used to monitor the optimization process. +1. `ppo/policy/approxkl`: The approximate KL divergence between the old and new policies, measured by `0.5 * masked_mean((logprobs - old_logprobs) ** 2, mask)`, corresponding to the `k2` estimator in http://joschu.net/blog/kl-approx.html +1. `ppo/policy/policykl`: Similar to `ppo/policy/approxkl`, but measured by `masked_mean(old_logprobs - logprobs, mask)`, corresponding to the `k1` estimator in http://joschu.net/blog/kl-approx.html +1. `ppo/policy/ratio`: The histogram distribution of the ratio between the new and old policies, used to compute the PPO objective. +1. `ppo/policy/advantages_mean`: The average of the GAE (Generalized Advantage Estimation) advantage estimates. The advantage function measures how much better an action is compared to the average action at a state. +1. `ppo/policy/advantages`: The histogram distribution of `ppo/policy/advantages_mean`. +1. `ppo/returns/mean`: The mean of the TD(λ) returns, calculated by `returns = advantage + values`, another indicator of model performance. See https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/ for more details. +1. `ppo/returns/var`: The variance of the TD(λ) returns, calculated by `returns = advantage + values`, another indicator of model performance. +1. `ppo/val/mean`: The mean of the values, used to monitor the value function's performance. +1. `ppo/val/var` : The variance of the values, used to monitor the value function's performance. +1. `ppo/val/var_explained`: The explained variance for the value function, used to monitor the value function's performance. +1. `ppo/val/clipfrac`: The fraction of the value function's predicted values that are clipped. +1. `ppo/val/vpred`: The predicted values from the value function. +1. `ppo/val/error`: The mean squared error between the `ppo/val/vpred` and returns, used to monitor the value function's performance. +1. `ppo/loss/policy`: The policy loss for the Proximal Policy Optimization (PPO) algorithm. +1. `ppo/loss/value`: The loss for the value function in the PPO algorithm. This value quantifies how well the function estimates the expected future rewards. +1. `ppo/loss/total`: The total loss for the PPO algorithm. It is the sum of the policy loss and the value function loss. + + +Stats on queries, responses, and logprobs: +1. `tokens/queries_len_mean`: The average length of the queries tokens. +1. `tokens/queries_len_std`: The standard deviation of the length of the queries tokens. +1. `tokens/queries_dist`: The histogram distribution of the length of the queries tokens. +1. `tokens/responses_len_mean`: The average length of the responses tokens. +1. `tokens/responses_len_std`: The standard deviation of the length of the responses tokens. +1. `tokens/responses_dist`: The histogram distribution of the length of the responses tokens. (Costa: inconsistent naming, should be `tokens/responses_len_dist`) +1. `objective/logprobs`: The histogram distribution of the log probabilities of the actions taken by the model. +1. `objective/ref_logprobs`: The histogram distribution of the log probabilities of the actions taken by the reference model. + + + +### Crucial values +During training, many values are logged, here are the most important ones: + +1. `env/reward_mean`,`env/reward_std`, `env/reward_dist`: the properties of the reward distribution from the "environment" / reward model +1. `ppo/mean_non_score_reward`: The mean negated KL penalty during training (shows the delta between the reference model and the new policy over the batch in the step) + +Here are some parameters that are useful to monitor for stability (when these diverge or collapse to 0, try tuning variables): + +1. `ppo/loss/value`: it will spike / NaN when not going well. +1. `ppo/policy/ratio`: `ratio` being 1 is a baseline value, meaning that the probability of sampling a token is the same under the new and old policy. If the ratio is too high like 200, it means the probability of sampling a token is 200 times higher under the new policy than the old policy. This is a sign that the new policy is too different from the old policy, which will likely cause overoptimization and collapse training later on. +1. `ppo/policy/clipfrac` and `ppo/policy/approxkl`: if `ratio` is too high, the `ratio` is going to get clipped, resulting in high `clipfrac` and high `approxkl` as well. +1. `objective/kl`: it should stay positive so that the policy is not too far away from the reference policy. +1. `objective/kl_coef`: The target coefficient with [`AdaptiveKLController`]. Often increases before numerical instabilities. \ No newline at end of file diff --git a/testbed/huggingface__trl/docs/source/lora_tuning_peft.mdx b/testbed/huggingface__trl/docs/source/lora_tuning_peft.mdx new file mode 100644 index 0000000000000000000000000000000000000000..531ee0fcd7f72718ca5a81c889f4194d7f378de9 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/lora_tuning_peft.mdx @@ -0,0 +1,144 @@ +# Examples of using peft with trl to finetune 8-bit models with Low Rank Adaption (LoRA) + +The notebooks and scripts in this examples show how to use Low Rank Adaptation (LoRA) to fine-tune models in a memory efficient manner. Most of PEFT methods supported in peft library but note that some PEFT methods such as Prompt tuning are not supported. +For more information on LoRA, see the [original paper](https://huggingface.co/papers/2106.09685). + +Here's an overview of the `peft`-enabled notebooks and scripts in the [trl repository](https://github.com/huggingface/trl/tree/main/examples): + +| File | Task | Description | Colab link | +|---|---| --- | +| [`stack_llama/rl_training.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/rl_training.py) | RLHF | Distributed fine-tuning of the 7b parameter LLaMA models with a learned reward model and `peft`. | | +| [`stack_llama/reward_modeling.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/reward_modeling.py) | Reward Modeling | Distributed training of the 7b parameter LLaMA reward model with `peft`. | | +| [`stack_llama/supervised_finetuning.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/supervised_finetuning.py) | SFT | Distributed instruction/supervised fine-tuning of the 7b parameter LLaMA model with `peft`. | | + +## Installation +Note: peft is in active development, so we install directly from their Github page. +Peft also relies on the latest version of transformers. + +```bash +pip install trl[peft] +pip install bitsandbytes loralib +pip install git+https://github.com/huggingface/transformers.git@main +#optional: wandb +pip install wandb +``` + +Note: if you don't want to log with `wandb` remove `log_with="wandb"` in the scripts/notebooks. You can also replace it with your favourite experiment tracker that's [supported by `accelerate`](https://huggingface.co/docs/accelerate/usage_guides/tracking). + +## How to use it? + +Simply declare a `PeftConfig` object in your script and pass it through `.from_pretrained` to load the TRL+PEFT model. + +```python +from peft import LoraConfig +from trl import AutoModelForCausalLMWithValueHead + +model_id = "edbeeching/gpt-neo-125M-imdb" +lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +model = AutoModelForCausalLMWithValueHead.from_pretrained( + model_id, + peft_config=lora_config, +) +``` +And if you want to load your model in 8bit precision: +```python +pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( + config.model_name, + load_in_8bit=True, + peft_config=lora_config, +) +``` +... or in 4bit precision: +```python +pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( + config.model_name, + peft_config=lora_config, + load_in_4bit=True, +) +``` + + +## Launch scripts + +The `trl` library is powered by `accelerate`. As such it is best to configure and launch trainings with the following commands: + +```bash +accelerate config # will prompt you to define the training configuration +accelerate launch examples/scripts/ppo.py --use_peft # launch`es training +``` + +## Using `trl` + `peft` and Data Parallelism + +You can scale up to as many GPUs as you want, as long as you are able to fit the training process in a single device. The only tweak you need to apply is to load the model as follows: +```python +from peft import LoraConfig +... + +lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( + config.model_name, + peft_config=lora_config, +) +``` +And if you want to load your model in 8bit precision: +```python +pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( + config.model_name, + peft_config=lora_config, + load_in_8bit=True, +) +``` +... or in 4bit precision: +```python +pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( + config.model_name, + peft_config=lora_config, + load_in_4bit=True, +) +``` +Finally, make sure that the rewards are computed on correct device as well, for that you can use `ppo_trainer.model.current_device`. + +## Naive pipeline parallelism (NPP) for large models (>60B models) + +The `trl` library also supports naive pipeline parallelism (NPP) for large models (>60B models). This is a simple way to parallelize the model across multiple GPUs. +This paradigm, termed as "Naive Pipeline Parallelism" (NPP) is a simple way to parallelize the model across multiple GPUs. We load the model and the adapters across multiple GPUs and the activations and gradients will be naively communicated across the GPUs. This supports `int8` models as well as other `dtype` models. + +
+ +
+ +### How to use NPP? + +Simply load your model with a custom `device_map` argument on the `from_pretrained` to split your model across multiple devices. Check out this [nice tutorial](https://github.com/huggingface/blog/blob/main/accelerate-large-models.md) on how to properly create a `device_map` for your model. + +Also make sure to have the `lm_head` module on the first GPU device as it may throw an error if it is not on the first device. As this time of writing, you need to install the `main` branch of `accelerate`: `pip install git+https://github.com/huggingface/accelerate.git@main` and `peft`: `pip install git+https://github.com/huggingface/peft.git@main`. + +### Launch scripts + +Although `trl` library is powered by `accelerate`, you should run your training script in a single process. Note that we do not support Data Parallelism together with NPP yet. + +```bash +python PATH_TO_SCRIPT +``` + +## Fine-tuning Llama-2 model + +You can easily fine-tune Llama2 model using `SFTTrainer` and the official script! For example to fine-tune llama2-7b on the Guanaco dataset, run (tested on a single NVIDIA T4-16GB): + +```bash +python examples/scripts/sft.py --output_dir sft_openassistant-guanaco --model_name meta-llama/Llama-2-7b-hf --dataset_name timdettmers/openassistant-guanaco --load_in_4bit --use_peft --per_device_train_batch_size 4 --gradient_accumulation_steps 2 +``` diff --git a/testbed/huggingface__trl/docs/source/multi_adapter_rl.mdx b/testbed/huggingface__trl/docs/source/multi_adapter_rl.mdx new file mode 100644 index 0000000000000000000000000000000000000000..42cc9d4e9193a1ce6035083c3d25da9fd1b57194 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/multi_adapter_rl.mdx @@ -0,0 +1,100 @@ +# Multi Adapter RL (MARL) - a single base model for everything + +Here we present an approach that uses a single base model for the entire PPO algorithm - which includes retrieving the reference logits, computing the active logits and the rewards. This feature is experimental as we did not test the convergence of the approach. We encourage the community to let us know if they potentially face issues. + +## Requirements + +You just need to install `peft` and optionally install `bitsandbytes` as well if you want to go for 8bit base models, for more memory efficient finetuning. + +## Summary + +You need to address this approach in three stages that we summarize as follows: + +1- Train a base model on the target domain (e.g. [IMDB dataset](https://huggingface.co/datasets/stanfordnlp/imdb)) - this is the Supervised Fine Tuning stage - it can leverage the `SFTTrainer` from TRL. +2- Train a reward model using `peft`. This is required in order to re-use the adapter during the RL optimisation process (step 3 below). We show an example of leveraging the `RewardTrainer` from TRL in [this example](https://github.com/huggingface/trl/tree/main/examples/scripts/reward_modeling.py) +3- Fine tune new adapters on the base model using PPO and the reward adapter. ("0 abstraction RL") + +Make sure to use the same model (i.e. same architecture and same weights) for the stages 2 & 3. + +## Quickstart + +Let us assume you have trained your reward adapter on `llama-7b` model using `RewardTrainer` and pushed the weights on the hub under `trl-lib/llama-7b-hh-rm-adapter`. +When doing PPO, before passing the model to `PPOTrainer` create your model as follows: + +```python +model_name = "huggyllama/llama-7b" +rm_adapter_id = "trl-lib/llama-7b-hh-rm-adapter" + +# PPO adapter +lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +model = AutoModelForCausalLMWithValueHead.from_pretrained( + model_name, + peft_config=lora_config, + reward_adapter=rm_adapter_id, +) + +... +trainer = PPOTrainer( + model=model, + ... +) + +... +``` +Then inside your PPO training loop, call the `compute_reward_score` method by accessing the `model` attribute from `PPOTrainer`. + +```python +rewards = trainer.model.compute_reward_score(**inputs) +``` + +## Advanced usage + +### Control on the adapter name + +If you are familiar with the `peft` library, you know that you can use multiple adapters inside the same model. What you can do is train multiple adapters on the same base model to fine-tune on different policies. +In this case, you want to be able to control the adapter name you want to activate back, after retrieving the reward. For that, simply pass the appropriate `adapter_name` to `ppo_adapter_name` argument when calling `compute_reward_score`. + +```python +adapter_name_policy_1 = "policy_1" +rewards = trainer.model.compute_reward_score(**inputs, ppo_adapter_name=adapter_name_policy_1) +... +``` + +### Using 4-bit and 8-bit base models + +For more memory efficient fine-tuning, you can load your base model in 8-bit or 4-bit while keeping the adapters in the default precision (float32). +Just pass the appropriate arguments (i.e. `load_in_8bit=True` or `load_in_4bit=True`) to `AutoModelForCausalLMWithValueHead.from_pretrained` as follows (assuming you have installed `bitsandbytes`): +```python +model_name = "llama-7b" +rm_adapter_id = "trl-lib/llama-7b-hh-rm-adapter" + +# PPO adapter +lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", +) + +model = AutoModelForCausalLMWithValueHead.from_pretrained( + model_name, + peft_config=lora_config, + reward_adapter=rm_adapter_id, + load_in_8bit=True, +) + +... +trainer = PPOTrainer( + model=model, + ... +) +... +``` diff --git a/testbed/huggingface__trl/docs/source/quickstart.mdx b/testbed/huggingface__trl/docs/source/quickstart.mdx new file mode 100644 index 0000000000000000000000000000000000000000..6d653ef5f382e28653490b2c7beb885a77762ae5 --- /dev/null +++ b/testbed/huggingface__trl/docs/source/quickstart.mdx @@ -0,0 +1,88 @@ +# Quickstart + +## How does it work? + +Fine-tuning a language model via PPO consists of roughly three steps: + +1. **Rollout**: The language model generates a response or continuation based on a query which could be the start of a sentence. +2. **Evaluation**: The query and response are evaluated with a function, model, human feedback, or some combination of them. The important thing is that this process should yield a scalar value for each query/response pair. The optimization will aim at maximizing this value. +3. **Optimization**: This is the most complex part. In the optimisation step the query/response pairs are used to calculate the log-probabilities of the tokens in the sequences. This is done with the model that is trained and a reference model, which is usually the pre-trained model before fine-tuning. The KL-divergence between the two outputs is used as an additional reward signal to make sure the generated responses don't deviate too far from the reference language model. The active language model is then trained with PPO. + +The full process is illustrated in the following figure: + + +## Minimal example + +The following code illustrates the steps above. + +```python +# 0. imports +import torch +from transformers import GPT2Tokenizer + +from trl import AutoModelForCausalLMWithValueHead, PPOConfig, PPOTrainer + + +# 1. load a pretrained model +model = AutoModelForCausalLMWithValueHead.from_pretrained("gpt2") +ref_model = AutoModelForCausalLMWithValueHead.from_pretrained("gpt2") +tokenizer = GPT2Tokenizer.from_pretrained("gpt2") +tokenizer.pad_token = tokenizer.eos_token + +# 2. initialize trainer +ppo_config = {"mini_batch_size": 1, "batch_size": 1} +config = PPOConfig(**ppo_config) +ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer) + +# 3. encode a query +query_txt = "This morning I went to the " +query_tensor = tokenizer.encode(query_txt, return_tensors="pt").to(model.pretrained_model.device) + +# 4. generate model response +generation_kwargs = { + "min_length": -1, + "top_k": 0.0, + "top_p": 1.0, + "do_sample": True, + "pad_token_id": tokenizer.eos_token_id, + "max_new_tokens": 20, +} +response_tensor = ppo_trainer.generate([item for item in query_tensor], return_prompt=False, **generation_kwargs) +response_txt = tokenizer.decode(response_tensor[0]) + +# 5. define a reward for response +# (this could be any reward such as human feedback or output from another model) +reward = [torch.tensor(1.0, device=model.pretrained_model.device)] + +# 6. train model with ppo +train_stats = ppo_trainer.step([query_tensor[0]], [response_tensor[0]], reward) +``` + +In general, you would run steps 3-6 in a for-loop and run it on many diverse queries. You can find more realistic examples in the examples section. + +## How to use a trained model + +After training a `AutoModelForCausalLMWithValueHead`, you can directly use the model in `transformers`. +```python + +# .. Let's assume we have a trained model using `PPOTrainer` and `AutoModelForCausalLMWithValueHead` + +# push the model on the Hub +model.push_to_hub("my-fine-tuned-model-ppo") + +# or save it locally +model.save_pretrained("my-fine-tuned-model-ppo") + +# load the model from the Hub +from transformers import AutoModelForCausalLM + +model = AutoModelForCausalLM.from_pretrained("my-fine-tuned-model-ppo") +``` + +You can also load your model with `AutoModelForCausalLMWithValueHead` if you want to use the value head, for example to continue training. + +```python +from trl.model import AutoModelForCausalLMWithValueHead + +model = AutoModelForCausalLMWithValueHead.from_pretrained("my-fine-tuned-model-ppo") +``` diff --git a/testbed/huggingface__trl/examples/accelerate_configs/single_gpu.yaml b/testbed/huggingface__trl/examples/accelerate_configs/single_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebd00a067118e56f3d63ab0f24827cfea21b24b9 --- /dev/null +++ b/testbed/huggingface__trl/examples/accelerate_configs/single_gpu.yaml @@ -0,0 +1,16 @@ +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: "NO" +downcast_bf16: 'no' +gpu_ids: all +machine_rank: 0 +main_training_function: main +mixed_precision: 'bf16' +num_machines: 1 +num_processes: 8 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false diff --git a/testbed/huggingface__trl/examples/datasets/hh-rlhf-helpful-base.py b/testbed/huggingface__trl/examples/datasets/hh-rlhf-helpful-base.py new file mode 100644 index 0000000000000000000000000000000000000000..afbb3d051390ceee552bff0398b68e808b54db13 --- /dev/null +++ b/testbed/huggingface__trl/examples/datasets/hh-rlhf-helpful-base.py @@ -0,0 +1,96 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +from dataclasses import dataclass +from typing import Dict, List, Optional + +from datasets import load_dataset +from transformers import HfArgumentParser + + +@dataclass +class ScriptArguments: + r""" + Arguments for the script. + + Args: + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the dataset to the Hugging Face Hub. + repo_id (`str`, *optional*, defaults to `"trl-lib/hh-rlhf-helpful-base"`): + Hugging Face repository ID to push the dataset to. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of workers to use for dataset processing. + """ + + push_to_hub: bool = False + repo_id: str = "trl-lib/hh-rlhf-helpful-base" + dataset_num_proc: Optional[int] = None + + +def common_start(str1: str, str2: str) -> str: + # Zip the two strings and iterate over them together + common_chars = [] + for c1, c2 in zip(str1, str2): + if c1 == c2: + common_chars.append(c1) + else: + break + # Join the common characters and return as a string + return "".join(common_chars) + + +def extract_dialogue(example: str) -> List[Dict[str, str]]: + # Extract the prompt, which corresponds to the common start of the chosen and rejected dialogues + prompt_text = common_start(example["chosen"], example["rejected"]) + + # The chosen and rejected may share a common start, so we need to remove the common part + if not prompt_text.endswith("\n\nAssistant: "): + prompt_text = prompt_text[: prompt_text.rfind("\n\nAssistant: ")] + "\n\nAssistant: " + + # Extract the chosen and rejected lines + chosen_line = example["chosen"][len(prompt_text) :] + rejected_line = example["rejected"][len(prompt_text) :] + + # Remove the generation prompt ("\n\nAssistant: ") from the prompt + prompt_text = prompt_text[: -len("\n\nAssistant: ")] + + # Split the string at every occurrence of "Human: " or "Assistant: " + prompt_lines = re.split(r"(\n\nAssistant: |\n\nHuman: )", prompt_text) + + # Remove the first element as it's empty + prompt_lines = prompt_lines[1:] + + prompt = [] + for idx in range(0, len(prompt_lines), 2): + role = "user" if prompt_lines[idx] == "\n\nHuman: " else "assistant" + content = prompt_lines[idx + 1] + prompt.append({"role": role, "content": content}) + + # Remove the prompt from the chosen and rejected dialogues + chosen = [{"role": "assitant", "content": chosen_line}] + rejected = [{"role": "assistant", "content": rejected_line}] + + return {"prompt": prompt, "chosen": chosen, "rejected": rejected} + + +if __name__ == "__main__": + parser = HfArgumentParser(ScriptArguments) + script_args = parser.parse_args_into_dataclasses()[0] + + dataset = load_dataset("Anthropic/hh-rlhf", data_dir="helpful-base") + dataset = dataset.map(extract_dialogue, num_proc=script_args.dataset_num_proc) + + if script_args.push_to_hub: + dataset.push_to_hub(script_args.repo_id) diff --git a/testbed/huggingface__trl/pyproject.toml b/testbed/huggingface__trl/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..02ee4b455230c848eedd24a22fe926d460a750ff --- /dev/null +++ b/testbed/huggingface__trl/pyproject.toml @@ -0,0 +1,23 @@ +[tool.ruff] +target-version = "py37" +line-length = 119 + +[tool.ruff.lint] +ignore = [ + "B028", # warning without explicit stacklevel + "C408", # dict() calls (stylistic) + "C901", # function complexity + "E501", +] +extend-select = ["E", "F", "I", "W", "UP", "B", "T", "C"] + +[tool.ruff.lint.per-file-ignores] +# Allow prints in auxiliary scripts +"examples/**.py" = ["T201"] +"scripts/**.py" = ["T201"] +# Ignore import violations in all `__init__.py` files. +"__init__.py" = ["F401"] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["trl"] diff --git a/testbed/huggingface__trl/requirements.txt b/testbed/huggingface__trl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c84bdbe3a3d3975b9129f0cf14ba162e4e66e3ad --- /dev/null +++ b/testbed/huggingface__trl/requirements.txt @@ -0,0 +1,4 @@ +accelerate +datasets +rich +transformers>=4.46.0 \ No newline at end of file diff --git a/testbed/huggingface__trl/setup.cfg b/testbed/huggingface__trl/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..29b21fba75bf481a19d5c9d6e7e4b0174eef6aa2 --- /dev/null +++ b/testbed/huggingface__trl/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +license_file = LICENSE \ No newline at end of file diff --git a/testbed/huggingface__trl/setup.py b/testbed/huggingface__trl/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca8db38aa1441b1fcef8e6cb5376b58675c5fe2 --- /dev/null +++ b/testbed/huggingface__trl/setup.py @@ -0,0 +1,141 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""trl is an open library for RL with transformer models. + +Note: + + VERSION needs to be formatted following the MAJOR.MINOR.PATCH convention + (we need to follow this convention to be able to retrieve versioned scripts) + +Simple check list for release from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py + +To create the package for pypi. + +0. Prerequisites: + - Dependencies: + - twine: "pip install twine" + - Create an account in (and join the 'trl' project): + - PyPI: https://pypi.org/ + - Test PyPI: https://test.pypi.org/ + +1. Change the version in: + - __init__.py + - setup.py + +2. Commit these changes: "git commit -m 'Release: VERSION'" + +3. Add a tag in git to mark the release: "git tag VERSION -m 'Add tag VERSION for pypi'" + Push the tag to remote: git push --tags origin main + +4. Build both the sources and the wheel. Do not change anything in setup.py between + creating the wheel and the source distribution (obviously). + + First, delete any "build" directory that may exist from previous builds. + + For the wheel, run: "python setup.py bdist_wheel" in the top level directory. + (this will build a wheel for the python version you use to build it). + + For the sources, run: "python setup.py sdist" + You should now have a /dist directory with both .whl and .tar.gz source versions. + +5. Check that everything looks correct by uploading the package to the pypi test server: + + twine upload dist/* -r pypitest --repository-url=https://test.pypi.org/legacy/ + + Check that you can install it in a virtualenv/notebook by running: + pip install huggingface_hub fsspec aiohttp + pip install -U tqdm + pip install -i https://testpypi.python.org/pypi evaluate + +6. Upload the final version to actual pypi: + twine upload dist/* -r pypi + +7. Fill release notes in the tag in github once everything is looking hunky-dory. + +8. Change the version in __init__.py and setup.py to X.X.X+1.dev0 (e.g. VERSION=1.18.3 -> 1.18.4.dev0). + Then push the change with a message 'set dev version' +""" + +import os + +from setuptools import find_packages, setup + + +__version__ = "0.13.0.dev0" # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) + +REQUIRED_PKGS = [ + "accelerate>=0.34.0", + "datasets>=2.21.0", + "rich", # rich shouldn't be a required package for trl, we should remove it from here + "transformers>=4.46.0", +] +EXTRAS = { + # Windows support is partially supported with DeepSpeed https://github.com/microsoft/DeepSpeed/tree/master#windows + "deepspeed": ["deepspeed>=0.14.4; sys_platform != 'win32'"], + "diffusers": ["diffusers>=0.18.0"], + # liger-kernel depends on triton, which is only available on Linux https://github.com/triton-lang/triton#compatibility + "liger": ["liger-kernel>=0.4.0; sys_platform != 'win32'"], + "judges": ["openai>=1.23.2", "llm-blender>=0.0.2"], + "peft": ["peft>=0.8.0"], + "quantization": ["bitsandbytes"], + "scikit": ["scikit-learn"], + "test": ["parameterized", "pytest-cov", "pytest-rerunfailures", "pytest-xdist", "pytest"], + "vlm": ["Pillow"], +} +EXTRAS["dev"] = [] +for reqs in EXTRAS.values(): + EXTRAS["dev"].extend(reqs) + +try: + file_path = os.path.dirname(os.path.abspath(__file__)) + os.symlink(os.path.join(file_path, "examples/scripts"), os.path.join(file_path, "trl/commands/scripts")) + + setup( + name="trl", + license="Apache 2.0", + classifiers=[ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + ], + url="https://github.com/huggingface/trl", + entry_points={ + "console_scripts": ["trl=trl.commands.cli:main"], + }, + include_package_data=True, + package_data={"trl": ["commands/scripts/config/*", "commands/scripts/*", "templates/*.md"]}, + packages=find_packages(exclude={"tests"}), + install_requires=REQUIRED_PKGS, + extras_require=EXTRAS, + python_requires=">=3.9", + long_description=open("README.md", encoding="utf-8").read(), + long_description_content_type="text/markdown", + zip_safe=False, + version=__version__, + description="Train transformer language models with reinforcement learning.", + keywords="ppo, transformers, huggingface, gpt2, language modeling, rlhf", + author="Leandro von Werra", + author_email="leandro.vonwerra@gmail.com", + ) +finally: + os.unlink(os.path.join(file_path, "trl/commands/scripts")) diff --git a/testbed/huggingface__trl/tests/test_data_utils.py b/testbed/huggingface__trl/tests/test_data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3495b8f02d04c68fa228fc0271c531cc178aa938 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_data_utils.py @@ -0,0 +1,361 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +import unittest + +from datasets import Dataset, DatasetDict +from parameterized import parameterized +from transformers import AutoTokenizer + +from trl.data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + maybe_apply_chat_template, + maybe_extract_prompt, + maybe_unpair_preference_dataset, + unpair_preference_dataset, +) + + +class IsConversationalTester(unittest.TestCase): + conversational_examples = [ + { # Language modeling + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + }, + { # Prompt only + "prompt": [{"role": "user", "content": "What color is the sky?"}], + }, + { # Pompt-completion + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + }, + { # Preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], + }, + { # Preference with implicit prompt + "chosen": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}, + ], + }, + { # Unpaired preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + "label": True, + }, + ] + + non_conversational_examples = [ + {"prompt": "The sky is", "completion": " blue."}, + {"text": "The sky is blue."}, + {"prompt": "The sky is"}, + {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}, + {"prompt": "The sky is", "completion": " blue.", "label": True}, + ] + + @parameterized.expand(itertools.product(conversational_examples)) + def test_conversational(self, example): + self.assertTrue(is_conversational(example)) + + @parameterized.expand(itertools.product(non_conversational_examples)) + def test_non_conversational(self, example): + self.assertFalse(is_conversational(example)) + + +class ApplyChatTemplateTester(unittest.TestCase): + tokenizers = [ + "trl-internal-testing/tiny-random-Qwen2-7B-Instruct", + "trl-internal-testing/tiny-random-Meta-Llama-3.1-8B-Instruct", + "trl-internal-testing/tiny-random-Meta-Llama-3-8B-Instruct", + "trl-internal-testing/tiny-random-DeepSeek-Coder-V2-Instruct", + "trl-internal-testing/tiny-random-Phi-3-mini-128k-instruct", + "trl-internal-testing/tiny-random-gemma-2-9b-it", + "trl-internal-testing/tiny-random-Mistral-7B-Instruct-v0.1", + "trl-internal-testing/tiny-random-Mistral-7B-Instruct-v0.2", + ] + + conversational_examples = [ + { # Language modeling + "messages": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + }, + { # Prompt only + "prompt": [{"role": "user", "content": "What color is the sky?"}], + }, + { # Pompt-completion + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + }, + { # Preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "chosen": [{"role": "assistant", "content": "It is blue."}], + "rejected": [{"role": "assistant", "content": "It is green."}], + }, + { # Preference with implicit prompt + "chosen": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}, + ], + }, + { # Unpaired preference + "prompt": [{"role": "user", "content": "What color is the sky?"}], + "completion": [{"role": "assistant", "content": "It is blue."}], + "label": True, + }, + ] + + non_conversational_examples = [ + {"prompt": "The sky is", "completion": " blue."}, + {"text": "The sky is blue."}, + {"prompt": "The sky is"}, + {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}, + {"chosen": "The sky is blue.", "rejected": "The sky is green."}, + {"prompt": "The sky is", "completion": " blue.", "label": True}, + ] + + @parameterized.expand(itertools.product(tokenizers, conversational_examples)) + def test_apply_chat_template(self, tokenizer_id, example): + tokenizer = AutoTokenizer.from_pretrained(tokenizer_id) + result = apply_chat_template(example, tokenizer) + + # Checking if the result is a dictionary + self.assertIsInstance(result, dict) + + # The chat template should be applied to the the following keys + for key in ["prompt", "chosen", "rejected", "completion"]: + if key in example: + self.assertIn(key, result) + self.assertIsInstance(result[key], str) + + # Exception for messages, the key is "text" once the chat template is applied + if "messages" in example: + self.assertIn("text", result) + self.assertIsInstance(result["text"], str) + + # The label should be kept + if "label" in example: + self.assertIn("label", result) + self.assertIsInstance(result["label"], bool) + self.assertEqual(result["label"], example["label"]) + + # both conversational and non-conversational examples + @parameterized.expand(itertools.product(tokenizers, conversational_examples + non_conversational_examples)) + def test_maybe_apply_chat_template(self, tokenizer_id, example): + tokenizer = AutoTokenizer.from_pretrained(tokenizer_id) + result = maybe_apply_chat_template(example, tokenizer) + + # Checking if the result is a dictionary + self.assertIsInstance(result, dict) + + # The chat template should be applied to the the following keys + for key in ["prompt", "chosen", "rejected", "completion"]: + if key in example: + self.assertIn(key, result) + self.assertIsInstance(result[key], str) + + # Exception for messages, the key is "text" once the chat template is applied + if "messages" in example: + self.assertIn("text", result) + self.assertIsInstance(result["text"], str) + + # The label should be kept + if "label" in example: + self.assertIn("label", result) + self.assertIsInstance(result["label"], bool) + self.assertEqual(result["label"], example["label"]) + + +class UnpairPreferenceDatasetTester(unittest.TestCase): + paired_dataset = Dataset.from_dict( + { + "prompt": ["The sky is", "The sun is"], + "chosen": [" blue.", " in the sky."], + "rejected": [" green.", " in the sea."], + } + ) + + unpaired_dataset = Dataset.from_dict( + { + "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"], + "completion": [" blue.", " in the sky.", " green.", " in the sea."], + "label": [True, True, False, False], + } + ) + + def test_unpair_preference_dataset(self): + # Test that a paired dataset is correctly converted to unpaired + unpaired_dataset = unpair_preference_dataset(self.paired_dataset) + self.assertEqual( + unpaired_dataset.to_dict(), + self.unpaired_dataset.to_dict(), + "The paired dataset should be converted to unpaired.", + ) + + def test_unpair_preference_dataset_dict(self): + # Test that a paired dataset dict is correctly converted to unpaired + paired_dataset_dict = DatasetDict({"abc": self.paired_dataset}) + unpaired_dataset_dict = unpair_preference_dataset(paired_dataset_dict) + self.assertEqual( + unpaired_dataset_dict["abc"].to_dict(), + self.unpaired_dataset.to_dict(), + "The paired dataset should be converted to unpaired.", + ) + + def test_maybe_unpair_preference_dataset(self): + # Test that a paired dataset is correctly converted to unpaired with maybe_unpair_preference_dataset + unpaired_dataset = maybe_unpair_preference_dataset(self.paired_dataset) + self.assertEqual( + unpaired_dataset.to_dict(), + self.unpaired_dataset.to_dict(), + "The paired dataset should be converted to unpaired.", + ) + + def test_maybe_unpair_preference_dataset_dict(self): + # Test that a paired dataset dict is correctly converted to unpaired with maybe_unpair_preference_dataset + paired_dataset_dict = DatasetDict({"abc": self.paired_dataset}) + unpaired_dataset_dict = maybe_unpair_preference_dataset(paired_dataset_dict) + self.assertEqual( + unpaired_dataset_dict["abc"].to_dict(), + self.unpaired_dataset.to_dict(), + "The paired dataset should be converted to unpaired.", + ) + + def test_maybe_unpair_preference_dataset_already_paired(self): + # Test that a paired dataset remains unchanged with maybe_unpair_preference_dataset + unpaired_dataset = maybe_unpair_preference_dataset(self.unpaired_dataset) + self.assertEqual( + unpaired_dataset.to_dict(), + self.unpaired_dataset.to_dict(), + "The unpaired dataset should remain unchanged.", + ) + + def test_maybe_unpair_preference_dataset_dict_already_paired(self): + # Test that a paired dataset dict remains unchanged with maybe_unpair_preference_dataset + unpaired_dataset_dict = maybe_unpair_preference_dataset(DatasetDict({"abc": self.unpaired_dataset})) + self.assertEqual( + unpaired_dataset_dict["abc"].to_dict(), + self.unpaired_dataset.to_dict(), + "The unpaired dataset should remain unchanged.", + ) + + +class ExtractPromptTester(unittest.TestCase): + example_implicit_prompt_conversational = { + "chosen": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "user", "content": "What color is the sky?"}, + {"role": "assistant", "content": "It is green."}, + ], + } + + example_explicit_prompt_conversational = { + "prompt": [ + {"role": "user", "content": "What color is the sky?"}, + ], + "chosen": [ + {"role": "assistant", "content": "It is blue."}, + ], + "rejected": [ + {"role": "assistant", "content": "It is green."}, + ], + } + + example_implicit_prompt_standard = { + "chosen": "The sky is blue.", + "rejected": "The sky is green.", + } + + example_explicit_prompt_standard = { + "prompt": "The sky is", + "chosen": " blue.", + "rejected": " green.", + } + + def test_extract_prompt_conversational(self): + # Test that the prompt is correctly extracted from the dataset + example_extracted_prompt = extract_prompt(self.example_implicit_prompt_conversational) + self.assertEqual( + example_extracted_prompt, + self.example_explicit_prompt_conversational, + "The prompt is not correctly extracted from the dataset.", + ) + + def test_maybe_extract_prompt_conversational(self): + # Test that the prompt is correctly extracted from the dataset with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_implicit_prompt_conversational) + self.assertEqual( + example_extracted_prompt, + self.example_explicit_prompt_conversational, + "The prompt is not correctly extracted from the dataset.", + ) + + def test_maybe_extract_prompt_conversational_already_explicit(self): + # Test that the prompt remains unchanged with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_explicit_prompt_conversational) + self.assertEqual( + example_extracted_prompt, + self.example_explicit_prompt_conversational, + "The prompt should remain unchanged.", + ) + + def test_extract_prompt_standard(self): + # Test that the prompt is correctly extracted from the dataset + example_extracted_prompt = extract_prompt(self.example_implicit_prompt_standard) + self.assertEqual( + example_extracted_prompt, + self.example_explicit_prompt_standard, + "The prompt is not correctly extracted from the dataset.", + ) + + def test_maybe_extract_prompt_standard(self): + # Test that the prompt is correctly extracted from the dataset with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_implicit_prompt_standard) + self.assertEqual( + example_extracted_prompt, + self.example_explicit_prompt_standard, + "The prompt is not correctly extracted from the dataset.", + ) + + def test_maybe_extract_prompt_standard_already_explicit(self): + # Test that the prompt remains unchanged with maybe_extract_prompt + example_extracted_prompt = maybe_extract_prompt(self.example_explicit_prompt_standard) + self.assertEqual( + example_extracted_prompt, + self.example_explicit_prompt_standard, + "The prompt should remain unchanged.", + ) + + +# Run the tests +if __name__ == "__main__": + unittest.main() diff --git a/testbed/huggingface__trl/tests/test_gkd_trainer.py b/testbed/huggingface__trl/tests/test_gkd_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..76570e5a86d865515503ba30aa775e4bc6909b90 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_gkd_trainer.py @@ -0,0 +1,262 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import tempfile +import unittest + +import torch +import torch.nn.functional as F +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig + +from trl import GKDConfig, GKDTrainer +from trl.trainer.utils import SIMPLE_CHAT_TEMPLATE + + +class TestGKDTrainer(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tokenizer = AutoTokenizer.from_pretrained("gpt2") + cls.tokenizer.pad_token = cls.tokenizer.eos_token + cls.model = AutoModelForCausalLM.from_pretrained("gpt2") + cls.generation_config = GenerationConfig( + max_new_tokens=20, + num_return_sequences=1, + pad_token_id=cls.tokenizer.pad_token_id, + eos_token_id=cls.tokenizer.eos_token_id, + ) + + def test_generate_on_policy_outputs_deterministic(self): + prompts = ["Hello, how are you?", "What's the weather like today?"] + tokenized_prompts = self.tokenizer(prompts, return_tensors="pt", padding=True) + + inputs = { + "prompts": tokenized_prompts["input_ids"], + "prompt_attention_mask": tokenized_prompts["attention_mask"], + } + + # Set temperature to 0 for deterministic output + deterministic_generation_config = GenerationConfig( + max_new_tokens=30, + num_return_sequences=1, + pad_token_id=self.tokenizer.pad_token_id, + eos_token_id=self.tokenizer.eos_token_id, + temperature=0.0, + ) + + outputs = GKDTrainer.generate_on_policy_outputs( + self.model, inputs, deterministic_generation_config, self.tokenizer.pad_token_id + ) + + new_input_ids, new_attention_mask, new_labels = outputs + + # Decode the generated outputs + generated_texts = self.tokenizer.batch_decode(new_input_ids, skip_special_tokens=True) + + # Check if the generated texts start with the original prompts + for prompt, generated_text in zip(prompts, generated_texts): + self.assertTrue( + generated_text.startswith(prompt), + f"Generated text '{generated_text}' does not start with prompt '{prompt}'", + ) + + # Run the generation twice and check if the outputs are identical + outputs2 = GKDTrainer.generate_on_policy_outputs( + self.model, inputs, deterministic_generation_config, self.tokenizer.pad_token_id + ) + + new_input_ids2, new_attention_mask2, new_labels2 = outputs2 + + # Check if the two generations are identical + self.assertTrue(torch.all(new_input_ids.eq(new_input_ids2)), "Deterministic generations are not identical") + self.assertTrue( + torch.all(new_attention_mask.eq(new_attention_mask2)), + "Attention masks for deterministic generations are not identical", + ) + self.assertTrue( + torch.all(new_labels.eq(new_labels2)), + "Labels for deterministic generations are not identical", + ) + + def test_generate_on_policy_outputs(self): + prompts = ["Hello, how are you?", "What's the weather like today?"] + tokenized_prompts = self.tokenizer(prompts, return_tensors="pt", padding=True) + + inputs = { + "prompts": tokenized_prompts["input_ids"], + "attention_mask": tokenized_prompts["attention_mask"], + } + + outputs = GKDTrainer.generate_on_policy_outputs( + self.model, inputs, self.generation_config, self.tokenizer.pad_token_id + ) + + # Check that outputs is a tuple of three tensors + self.assertIsInstance(outputs, tuple) + self.assertEqual(len(outputs), 3) + + new_input_ids, new_attention_mask, new_labels = outputs + + # Check shapes + batch_size = len(prompts) + self.assertEqual(new_input_ids.shape[0], batch_size) + self.assertEqual(new_attention_mask.shape[0], batch_size) + self.assertEqual(new_labels.shape[0], batch_size) + + # Check types + self.assertIsInstance(new_input_ids, torch.Tensor) + self.assertIsInstance(new_attention_mask, torch.Tensor) + self.assertIsInstance(new_labels, torch.Tensor) + + # Check that new_input_ids and new_attention_mask have the same shape + self.assertEqual(new_input_ids.shape, new_attention_mask.shape) + self.assertEqual(new_labels.shape, new_attention_mask.shape) + + +class TestGeneralizedJSDLoss(unittest.TestCase): + def setUp(self): + self.batch_size = 2 + self.seq_length = 3 + self.vocab_size = 5 + self.student_logits = torch.randn(self.batch_size, self.seq_length, self.vocab_size) + self.teacher_logits = torch.randn(self.batch_size, self.seq_length, self.vocab_size) + + def test_uniform_distribution(self): + logits = torch.ones(1, 1, self.vocab_size) + loss = GKDTrainer.generalized_jsd_loss(logits, logits) + self.assertAlmostEqual(loss.item(), 0, places=5) + + def test_generalized_jsd_loss_edge_cases(self): + # Setup + student_logits = torch.log(torch.tensor([[0.1, 0.9]])).unsqueeze(0) + teacher_logits = torch.log(torch.tensor([[0.9, 0.1]])).unsqueeze(0) + + # Case 1: beta = 1 (should be equivalent to KL(student || teacher)) + loss_beta_1 = GKDTrainer.generalized_jsd_loss(student_logits, teacher_logits, beta=1) + expected_loss_beta_1 = F.kl_div( + F.log_softmax(student_logits, dim=-1), F.softmax(teacher_logits, dim=-1), reduction="batchmean" + ) + self.assertAlmostEqual(loss_beta_1.item(), expected_loss_beta_1.item(), places=5) + + # Case 2: beta = 0 (should be equivalent to KL(teacher || student)) + loss_beta_0 = GKDTrainer.generalized_jsd_loss(student_logits, teacher_logits, beta=0) + expected_loss_beta_0 = F.kl_div( + F.log_softmax(teacher_logits, dim=-1), F.softmax(student_logits, dim=-1), reduction="batchmean" + ) + self.assertAlmostEqual(loss_beta_0.item(), expected_loss_beta_0.item(), places=5) + + def test_output_shape(self): + loss = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits) + self.assertTrue(torch.is_tensor(loss)) + self.assertEqual(loss.shape, torch.Size([])) + + def test_beta_values(self): + loss_beta_0 = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, beta=0) + loss_beta_1 = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, beta=1) + self.assertNotEqual(loss_beta_0, loss_beta_1) + + def test_temperature_scaling(self): + loss_temp_1 = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, temperature=1) + loss_temp_2 = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, temperature=2) + self.assertNotEqual(loss_temp_1, loss_temp_2) + + def test_reduction_methods(self): + loss_batchmean = GKDTrainer.generalized_jsd_loss( + self.student_logits, self.teacher_logits, reduction="batchmean" + ) + loss_sum = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, reduction="sum") + loss_mean = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, reduction="mean") + loss_none = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, reduction="none") + + self.assertEqual(loss_batchmean.shape, torch.Size([])) + self.assertEqual(loss_sum.shape, torch.Size([])) + self.assertEqual(loss_mean.shape, torch.Size([])) + self.assertEqual(loss_none.shape, self.student_logits.shape) + + def test_symmetry(self): + student_teacher = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, beta=0.1) + teacher_student = GKDTrainer.generalized_jsd_loss(self.teacher_logits, self.student_logits, beta=0.1) + self.assertNotEqual(student_teacher, teacher_student) + + student_teacher = GKDTrainer.generalized_jsd_loss(self.student_logits, self.teacher_logits, beta=0.5) + teacher_student = GKDTrainer.generalized_jsd_loss(self.teacher_logits, self.student_logits, beta=0.5) + self.assertEqual(student_teacher, teacher_student) + + def test_zero_loss_for_identical_inputs(self): + identical_logits = torch.randn(self.batch_size, self.seq_length, self.vocab_size) + loss = GKDTrainer.generalized_jsd_loss(identical_logits, identical_logits) + self.assertAlmostEqual(loss.item(), 0, places=6) + + +class GKDTrainerTester(unittest.TestCase): + def setUp(self): + self.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.teacher_model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + # Ensure the tokenizer has a chat template + if not hasattr(self.tokenizer, "chat_template") or self.tokenizer.chat_template is None: + self.tokenizer.chat_template = SIMPLE_CHAT_TEMPLATE + + def test_gkd_trainer(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = GKDConfig( + output_dir=tmp_dir, + dataloader_drop_last=True, + eval_strategy="steps", + max_steps=4, + eval_steps=2, + save_steps=2, + per_device_train_batch_size=2, + per_device_eval_batch_size=2, + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling") + + trainer = GKDTrainer( + model=self.model_id, + teacher_model=self.model_id, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + ) + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[(-1)]["train_loss"]) + self.assertIsNotNone(trainer.state.log_history[0]["eval_loss"]) + self.assertIn("model.safetensors", os.listdir(tmp_dir + "/checkpoint-2")) + + def test_generation_config_init(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = GKDConfig(output_dir=tmp_dir) + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling") + + trainer = GKDTrainer( + model=self.model_id, + teacher_model=self.model_id, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + ) + + self.assertEqual(trainer.generation_config.pad_token_id, self.tokenizer.eos_token_id) + self.assertEqual(trainer.generation_config.eos_token_id, self.model.generation_config.eos_token_id) + self.assertEqual(trainer.generation_config.max_new_tokens, training_args.max_new_tokens) + self.assertEqual(trainer.generation_config.temperature, training_args.temperature) + self.assertEqual(trainer.generation_config.top_k, 0) diff --git a/testbed/huggingface__trl/tests/test_judges.py b/testbed/huggingface__trl/tests/test_judges.py new file mode 100644 index 0000000000000000000000000000000000000000..13d2164ffe2cc82bfecbcd0314252c5f1560d26b --- /dev/null +++ b/testbed/huggingface__trl/tests/test_judges.py @@ -0,0 +1,76 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import time +import unittest + +from trl import AllTrueJudge, HfPairwiseJudge, PairRMJudge + +from .testing_utils import RandomBinaryJudge, require_llm_blender + + +class TestJudges(unittest.TestCase): + def _get_prompts_and_pairwise_completions(self): + prompts = ["The capital of France is", "The biggest planet in the solar system is"] + completions = [["Paris", "Marseille"], ["Saturn", "Jupiter"]] + return prompts, completions + + def _get_prompts_and_single_completions(self): + prompts = ["What's the capital of France?", "What's the color of the sky?"] + completions = ["Marseille", "blue"] + return prompts, completions + + def test_all_true_judge(self): + judge = AllTrueJudge(judges=[RandomBinaryJudge(), RandomBinaryJudge()]) + prompts, completions = self._get_prompts_and_single_completions() + judgements = judge.judge(prompts=prompts, completions=completions) + self.assertEqual(len(judgements), 2) + self.assertTrue(all(judgement in {0, 1, -1} for judgement in judgements)) + + @unittest.skip("This test needs to be run manually since it requires a valid Hugging Face API key.") + def test_hugging_face_judge(self): + judge = HfPairwiseJudge() + prompts, completions = self._get_prompts_and_pairwise_completions() + ranks = judge.judge(prompts=prompts, completions=completions) + self.assertEqual(len(ranks), 2) + self.assertTrue(all(isinstance(rank, int) for rank in ranks)) + self.assertEqual(ranks, [0, 1]) + + def load_pair_rm_judge(self): + # When using concurrent tests, PairRM may fail to load the model while another job is still downloading. + # This is a workaround to retry loading the model a few times. + for _ in range(5): + try: + return PairRMJudge() + except ValueError: + time.sleep(5) + raise ValueError("Failed to load PairRMJudge") + + @require_llm_blender + def test_pair_rm_judge(self): + judge = self.load_pair_rm_judge() + prompts, completions = self._get_prompts_and_pairwise_completions() + ranks = judge.judge(prompts=prompts, completions=completions) + self.assertEqual(len(ranks), 2) + self.assertTrue(all(isinstance(rank, int) for rank in ranks)) + self.assertEqual(ranks, [0, 1]) + + @require_llm_blender + def test_pair_rm_judge_return_scores(self): + judge = self.load_pair_rm_judge() + prompts, completions = self._get_prompts_and_pairwise_completions() + probs = judge.judge(prompts=prompts, completions=completions, return_scores=True) + self.assertEqual(len(probs), 2) + self.assertTrue(all(isinstance(prob, float) for prob in probs)) + self.assertTrue(all(0 <= prob <= 1 for prob in probs)) diff --git a/testbed/huggingface__trl/tests/test_kto_trainer.py b/testbed/huggingface__trl/tests/test_kto_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a094a66e8f9e09dab9bf20ef2b701a2b2c1bf3 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_kto_trainer.py @@ -0,0 +1,382 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import tempfile +import unittest + +import torch +from datasets import load_dataset +from parameterized import parameterized +from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer +from transformers.testing_utils import require_peft + +from trl import KTOConfig, KTOTrainer +from trl.trainer.kto_trainer import _get_kl_dataset, _process_tokens, _tokenize + +from .testing_utils import require_no_wandb + + +class KTOTrainerTester(unittest.TestCase): + def setUp(self): + self.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + # get t5 as seq2seq example: + model_id = "trl-internal-testing/tiny-T5ForConditionalGeneration-correct-vocab" + self.t5_model = AutoModelForSeq2SeqLM.from_pretrained(model_id) + self.t5_ref_model = AutoModelForSeq2SeqLM.from_pretrained(model_id) + self.t5_tokenizer = AutoTokenizer.from_pretrained(model_id) + + @parameterized.expand( + [ + ("gpt2", "standard_preference", "kto", True, True), + # ("t5", "standard_implicit_prompt_preference", "kto", True, False), # KTO broken for enc-dec + ("gpt2", "standard_unpaired_preference", "kto", False, True), + # ("t5", "conversational_preference", "kto", False, False), + ("gpt2", "conversational_implicit_prompt_preference", "apo_zero_unpaired", True, True), + # ("t5", "conversational_unpaired_preference", "apo_zero_unpaired", True, False), + ("gpt2", "standard_unpaired_preference", "apo_zero_unpaired", False, True), + # ("t5", "conversational_unpaired_preference", "apo_zero_unpaired", False, False), + ] + ) + def test_kto_trainer(self, name, config_name, loss_type, pre_compute, eval_dataset): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps" if eval_dataset else "no", + beta=0.1, + precompute_ref_log_probs=pre_compute, + loss_type=loss_type, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + if name == "gpt2": + model = self.model + ref_model = self.ref_model + tokenizer = self.tokenizer + elif name == "t5": + model = self.t5_model + ref_model = self.t5_ref_model + tokenizer = self.t5_tokenizer + + trainer = KTOTrainer( + model=model, + ref_model=ref_model, + args=training_args, + processing_class=tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"] if eval_dataset else None, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.equal(param, new_param)) + + def test_kto_trainer_with_ref_model_is_model(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference") + + with self.assertRaises(ValueError): + KTOTrainer( + model=self.model, + ref_model=self.model, # ref_model can't be the same as model + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + ) + + def test_tokenize_and_process_tokens(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference") + + trainer = KTOTrainer( + model=self.model, + ref_model=self.ref_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + train_dataset = dummy_dataset["train"] + tokenized_dataset = train_dataset.map( + _tokenize, + fn_kwargs={"tokenizer": trainer.tokenizer}, + batched=True, + batch_size=2, + ) + self.assertListEqual(tokenized_dataset["prompt"], train_dataset["prompt"]) + self.assertListEqual(tokenized_dataset["completion"], train_dataset["completion"]) + self.assertListEqual(tokenized_dataset["label"], train_dataset["label"]) + self.assertListEqual(tokenized_dataset["prompt_input_ids"][0], [5377, 11141]) + self.assertListEqual(tokenized_dataset["prompt_attention_mask"][0], [1, 1]) + self.assertListEqual(tokenized_dataset["answer_input_ids"][0], [318, 1365, 621, 8253, 13]) + self.assertListEqual(tokenized_dataset["answer_attention_mask"][0], [1, 1, 1, 1, 1]) + + # Test corruption of (prompt, completion) pairs for KL dataset + for batch_size in [2, 3]: + tokenized_kl_dataset = tokenized_dataset.map(_get_kl_dataset, batched=True, batch_size=batch_size) + + # Verify that the "answer_input_ids" have been modified, meaning the new "answer_input_ids" differ + # from the original ones. However, when the length of the dataset modulo batch_size equals 1, + # the last batch remains unaltered. This is a rare scenario that does not impact the training + # process, so we exclude it from testing by iterating only up to len - 1. + for i in range(len(tokenized_kl_dataset["answer_input_ids"]) - 1): + self.assertListEqual( + tokenized_dataset["prompt_input_ids"][i], + tokenized_kl_dataset["prompt_input_ids"][i], + ) + self.assertListEqual( + tokenized_dataset["prompt_attention_mask"][i], + tokenized_kl_dataset["prompt_attention_mask"][i], + ) + self.assertNotEqual( + tokenized_dataset["answer_input_ids"][i], + tokenized_kl_dataset["answer_input_ids"][i], + ) + + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": trainer.is_encoder_decoder, + "tokenizer": trainer.tokenizer, + "max_length": trainer.max_length, + "truncation_mode": trainer.truncation_mode, + "label_pad_token_id": trainer.label_pad_token_id, + "max_prompt_length": trainer.max_prompt_length, + } + processed_dataset = tokenized_dataset.map(_process_tokens, fn_kwargs=fn_kwargs, num_proc=2) + self.assertListEqual(processed_dataset["prompt"], train_dataset["prompt"]) + self.assertListEqual(processed_dataset["completion"], train_dataset["completion"]) + self.assertListEqual(processed_dataset["label"], train_dataset["label"]) + self.assertListEqual(processed_dataset["prompt_input_ids"][0], [50256, 5377, 11141]) + self.assertListEqual(processed_dataset["prompt_attention_mask"][0], [1, 1, 1]) + self.assertListEqual( + processed_dataset["completion_input_ids"][0], [50256, 5377, 11141, 318, 1365, 621, 8253, 13, 50256] + ) + self.assertListEqual(processed_dataset["completion_attention_mask"][0], [1, 1, 1, 1, 1, 1, 1, 1, 1]) + self.assertListEqual( + processed_dataset["completion_labels"][0], [-100, -100, -100, 318, 1365, 621, 8253, 13, 50256] + ) + + def test_kto_trainer_without_providing_ref_model(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=4, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference") + + trainer = KTOTrainer( + model=self.model, + ref_model=None, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.equal(param, new_param)) + + @require_peft + def test_kto_trainer_without_providing_ref_model_with_lora(self): + from peft import LoraConfig + + lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + ) + + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=4, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference") + + trainer = KTOTrainer( + model=self.model, + ref_model=None, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + if "lora" in n: + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.equal(param, new_param)) + + @require_no_wandb + def test_kto_trainer_generate_during_eval_no_wandb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + generate_during_eval=True, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference") + + with self.assertRaisesRegex( + ValueError, + expected_regex="`generate_during_eval=True` requires Weights and Biases to be installed." + " Please install with `pip install wandb` to resolve.", + ): + KTOTrainer( + model=self.model, + ref_model=None, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + @require_peft + def test_kto_lora_save(self): + from peft import LoraConfig, get_peft_model + + lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + ) + + # lora model + model = AutoModelForCausalLM.from_pretrained(self.model_id) + model_peft = get_peft_model(model, lora_config) + + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=4, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference") + + # kto train lora model with a lora config + trainer = KTOTrainer( + model=model_peft, + ref_model=None, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + # train the model + trainer.train() + + # save peft adapter + trainer.save_model() + + # assert that the model is loaded without giving OSError + try: + AutoModelForCausalLM.from_pretrained(tmp_dir) + except OSError: + self.fail("Loading the saved peft adapter failed") diff --git a/testbed/huggingface__trl/tests/test_modeling_value_head.py b/testbed/huggingface__trl/tests/test_modeling_value_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5298e133afc1ebfc30145c68bb9374c3dd83abea --- /dev/null +++ b/testbed/huggingface__trl/tests/test_modeling_value_head.py @@ -0,0 +1,540 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import gc +import sys +import tempfile +import unittest + +import torch +from parameterized import parameterized +from transformers import AutoModel, AutoModelForCausalLM, AutoModelForSeq2SeqLM, GenerationConfig + +from trl import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead, create_reference_model + + +ALL_CAUSAL_LM_MODELS = [ + "trl-internal-testing/tiny-random-CodeGenForCausalLM", + "trl-internal-testing/tiny-random-GPTJForCausalLM", + "trl-internal-testing/tiny-random-GPTNeoForCausalLM", + "trl-internal-testing/tiny-random-GPTNeoXForCausalLM", + "trl-internal-testing/tiny-random-OPTForCausalLM", + "trl-internal-testing/tiny-random-BloomForCausalLM", + "trl-internal-testing/tiny-random-GPT2LMHeadModel", + "trl-internal-testing/tiny-random-CodeGenForCausalLM-sharded", + "trl-internal-testing/tiny-random-GPTNeoXForCausalLM-safetensors-sharded", + "trl-internal-testing/tiny-random-GPTNeoXForCausalLM-safetensors", + "trl-internal-testing/tiny-random-LlamaForCausalLM", +] + +ALL_SEQ2SEQ_MODELS = [ + "trl-internal-testing/tiny-random-BartForConditionalGeneration", + "trl-internal-testing/tiny-random-BigBirdPegasusForConditionalGeneration", + "trl-internal-testing/tiny-random-BlenderbotForConditionalGeneration", + "trl-internal-testing/tiny-random-BlenderbotSmallForConditionalGeneration", + "trl-internal-testing/tiny-random-FSMTForConditionalGeneration", + "trl-internal-testing/tiny-random-LEDForConditionalGeneration", + "trl-internal-testing/tiny-random-LongT5ForConditionalGeneration", + "trl-internal-testing/tiny-random-M2M100ForConditionalGeneration", + "trl-internal-testing/tiny-random-MarianMTModel", + "trl-internal-testing/tiny-random-MBartForConditionalGeneration", + "trl-internal-testing/tiny-random-MT5ForConditionalGeneration", + "trl-internal-testing/tiny-random-MvpForConditionalGeneration", + "trl-internal-testing/tiny-random-PegasusForConditionalGeneration", + "trl-internal-testing/tiny-random-PegasusXForConditionalGeneration", + "trl-internal-testing/tiny-random-PLBartForConditionalGeneration", + "trl-internal-testing/tiny-random-ProphetNetForConditionalGeneration", + "trl-internal-testing/tiny-random-SwitchTransformersForConditionalGeneration", + "trl-internal-testing/tiny-random-T5ForConditionalGeneration", +] + + +class BaseTester: + class VHeadModelTester(unittest.TestCase): + all_model_names = None + trl_model_class = None + transformers_model_class = None + + def test_value_head(self): + r""" + Test if the v-head is added to the model successfully + """ + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + self.assertTrue(hasattr(model, "v_head")) + + def test_value_head_shape(self): + r""" + Test if the v-head has the correct shape + """ + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + self.assertEqual(model.v_head.summary.weight.shape[0], 1) + + def test_value_head_init_random(self): + r""" + Test if the v-head has been randomly initialized. + We can check that by making sure the bias is different + than zeros by default. + """ + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + self.assertFalse( + torch.allclose(model.v_head.summary.bias, torch.zeros_like(model.v_head.summary.bias)) + ) + + def test_value_head_not_str(self): + r""" + Test if the v-head is added to the model successfully, by passing a non `PretrainedModel` + as an argument to `from_pretrained`. + """ + for model_name in self.all_model_names: + pretrained_model = self.transformers_model_class.from_pretrained(model_name) + model = self.trl_model_class.from_pretrained(pretrained_model) + self.assertTrue(hasattr(model, "v_head")) + + @unittest.skipIf(sys.platform.startswith("win"), "Skipping on Windows") + def test_from_save_trl(self): + """ + Test if the model can be saved and loaded from a directory and get the same weights + Including the additional modules (e.g. v_head) + """ + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + model_from_save = self.trl_model_class.from_pretrained(tmp_dir) + + # Check if the weights are the same + for key in model_from_save.state_dict(): + self.assertTrue(torch.allclose(model_from_save.state_dict()[key], model.state_dict()[key])) + + @unittest.skipIf(sys.platform.startswith("win"), "Skipping on Windows") + def test_from_save_trl_sharded(self): + """ + Test if the model can be saved and loaded from a directory and get the same weights - sharded case + """ + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + model_from_save = self.trl_model_class.from_pretrained(tmp_dir) + + # Check if the weights are the same + for key in model_from_save.state_dict(): + self.assertTrue(torch.allclose(model_from_save.state_dict()[key], model.state_dict()[key])) + + @unittest.skipIf(sys.platform.startswith("win"), "Skipping on Windows") + def test_from_save_transformers_sharded(self): + """ + Test if the model can be saved and loaded using transformers and get the same weights - sharded case + """ + for model_name in self.all_model_names: + transformers_model = self.trl_model_class.transformers_parent_class.from_pretrained(model_name) + + trl_model = self.trl_model_class.from_pretrained(model_name) + + with tempfile.TemporaryDirectory() as tmp_dir: + trl_model.save_pretrained(tmp_dir, max_shard_size="1MB") + transformers_model_from_save = self.trl_model_class.transformers_parent_class.from_pretrained( + tmp_dir + ) + + # Check if the weights are the same + for key in transformers_model.state_dict(): + self.assertTrue( + torch.allclose( + transformers_model_from_save.state_dict()[key], transformers_model.state_dict()[key] + ) + ) + + @unittest.skipIf(sys.platform.startswith("win"), "Skipping on Windows") + def test_from_save_transformers(self): + """ + Test if the model can be saved and loaded using transformers and get the same weights. + We override the test of the super class to check if the weights are the same. + """ + for model_name in self.all_model_names: + transformers_model = self.trl_model_class.transformers_parent_class.from_pretrained(model_name) + + trl_model = self.trl_model_class.from_pretrained(model_name) + + with tempfile.TemporaryDirectory() as tmp_dir: + trl_model.save_pretrained(tmp_dir) + transformers_model_from_save = self.trl_model_class.transformers_parent_class.from_pretrained( + tmp_dir + ) + + # Check if the weights are the same + for key in transformers_model.state_dict(): + self.assertTrue( + torch.allclose( + transformers_model_from_save.state_dict()[key], transformers_model.state_dict()[key] + ) + ) + + # Check if the trl model has the same keys as the transformers model + # except the v_head + for key in trl_model.state_dict(): + if "v_head" not in key: + self.assertIn(key, transformers_model.state_dict()) + # check if the weights are the same + self.assertTrue( + torch.allclose(trl_model.state_dict()[key], transformers_model.state_dict()[key]) + ) + + # check if they have the same modules + self.assertEqual( + set(transformers_model_from_save.state_dict().keys()), + set(transformers_model.state_dict().keys()), + ) + + +class CausalLMValueHeadModelTester(BaseTester.VHeadModelTester, unittest.TestCase): + """ + Testing suite for v-head models. + """ + + all_model_names = ALL_CAUSAL_LM_MODELS + trl_model_class = AutoModelForCausalLMWithValueHead + transformers_model_class = AutoModelForCausalLM + + def tearDown(self): + # free memory + gc.collect() + + def test_inference(self): + r""" + Test if the model can be used for inference and outputs 3 values + - logits, loss, and value states + """ + EXPECTED_OUTPUT_SIZE = 3 + + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + outputs = model(input_ids) + + # Check if the outputs are of the right size - here + # we always output 3 values - logits, loss, and value states + self.assertEqual(len(outputs), EXPECTED_OUTPUT_SIZE) + + def test_dropout_config(self): + r""" + Test if we instantiate a model by adding `summary_drop_prob` to the config + it will be added to the v_head + """ + for model_name in self.all_model_names: + pretrained_model = self.transformers_model_class.from_pretrained(model_name) + pretrained_model.config.summary_dropout_prob = 0.5 + model = self.trl_model_class.from_pretrained(pretrained_model) + + # Check if v head of the model has the same dropout as the config + self.assertEqual(model.v_head.dropout.p, pretrained_model.config.summary_dropout_prob) + + def test_dropout_kwargs(self): + r""" + Test if we instantiate a model by adding `summary_drop_prob` to the config + it will be added to the v_head + """ + for model_name in self.all_model_names: + v_head_kwargs = {"summary_dropout_prob": 0.5} + + model = self.trl_model_class.from_pretrained(model_name, **v_head_kwargs) + + # Check if v head of the model has the same dropout as the config + self.assertEqual(model.v_head.dropout.p, 0.5) + + model = self.trl_model_class.from_pretrained(model_name, summary_dropout_prob=0.5) + + # Check if v head of the model has the same dropout as the config + self.assertEqual(model.v_head.dropout.p, 0.5) + + @parameterized.expand(ALL_CAUSAL_LM_MODELS) + def test_generate(self, model_name): + r""" + Test if `generate` works for every model + """ + generation_config = GenerationConfig(max_new_tokens=9) + model = self.trl_model_class.from_pretrained(model_name) + input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + + # Just check if the generation works + _ = model.generate(input_ids, generation_config=generation_config) + + def test_raise_error_not_causallm(self): + # Test with a model without a LM head + model_id = "trl-internal-testing/tiny-random-GPT2Model" + # This should raise a ValueError + with self.assertRaises(ValueError): + pretrained_model = AutoModelForCausalLM.from_pretrained(model_id) + _ = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model.transformer) + + def test_transformers_bf16_kwargs(self): + r""" + Test if the transformers kwargs are correctly passed + Here we check that loading a model in half precision works as expected, i.e. the weights of + the `pretrained_model` attribute is loaded in half precision and you can run a dummy + forward pass without any issue. + """ + for model_name in self.all_model_names: + trl_model = self.trl_model_class.from_pretrained(model_name, torch_dtype=torch.bfloat16) + + lm_head_namings = self.trl_model_class.lm_head_namings + + self.assertTrue( + any(hasattr(trl_model.pretrained_model, lm_head_naming) for lm_head_naming in lm_head_namings) + ) + + for lm_head_naming in lm_head_namings: + if hasattr(trl_model.pretrained_model, lm_head_naming): + self.assertEqual(getattr(trl_model.pretrained_model, lm_head_naming).weight.dtype, torch.bfloat16) + + dummy_input = torch.LongTensor([[0, 1, 0, 1]]) + + # check dummy forward pass works in half precision + _ = trl_model(dummy_input) + + @unittest.skip("This test needs to be run manually due to HF token issue.") + def test_push_to_hub(self): + for model_name in self.all_model_names: + model = AutoModelForCausalLMWithValueHead.from_pretrained(model_name) + if "sharded" in model_name: + model.push_to_hub(model_name + "-ppo", use_auth_token=True, max_shard_size="1MB") + else: + model.push_to_hub(model_name + "-ppo", use_auth_token=True) + + model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(model_name + "-ppo") + # check all keys + self.assertEqual(model.state_dict().keys(), model_from_pretrained.state_dict().keys()) + + for name, param in model.state_dict().items(): + self.assertTrue( + torch.allclose(param, model_from_pretrained.state_dict()[name]), + f"Parameter {name} is not the same after push_to_hub and from_pretrained", + ) + + +class Seq2SeqValueHeadModelTester(BaseTester.VHeadModelTester, unittest.TestCase): + """ + Testing suite for v-head models. + """ + + all_model_names = ALL_SEQ2SEQ_MODELS + trl_model_class = AutoModelForSeq2SeqLMWithValueHead + transformers_model_class = AutoModelForSeq2SeqLM + + def tearDown(self): + # free memory + gc.collect() + + def test_inference(self): + r""" + Test if the model can be used for inference and outputs 3 values + - logits, loss, and value states + """ + EXPECTED_OUTPUT_SIZE = 3 + + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + decoder_input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + outputs = model(input_ids, decoder_input_ids=decoder_input_ids) + + # Check if the outputs are of the right size - here + # we always output 3 values - logits, loss, and value states + self.assertEqual(len(outputs), EXPECTED_OUTPUT_SIZE) + + def test_dropout_config(self): + r""" + Test if we instantiate a model by adding `summary_drop_prob` to the config + it will be added to the v_head + """ + for model_name in self.all_model_names: + pretrained_model = self.transformers_model_class.from_pretrained(model_name) + pretrained_model.config.summary_dropout_prob = 0.5 + model = self.trl_model_class.from_pretrained(pretrained_model) + + # Check if v head of the model has the same dropout as the config + self.assertEqual(model.v_head.dropout.p, pretrained_model.config.summary_dropout_prob) + + def test_dropout_kwargs(self): + r""" + Test if we instantiate a model by adding `summary_drop_prob` to the config + it will be added to the v_head + """ + for model_name in self.all_model_names: + v_head_kwargs = {"summary_dropout_prob": 0.5} + + model = self.trl_model_class.from_pretrained(model_name, **v_head_kwargs) + + # Check if v head of the model has the same dropout as the config + self.assertEqual(model.v_head.dropout.p, 0.5) + + model = self.trl_model_class.from_pretrained(model_name, summary_dropout_prob=0.5) + + # Check if v head of the model has the same dropout as the config + self.assertEqual(model.v_head.dropout.p, 0.5) + + @parameterized.expand(ALL_SEQ2SEQ_MODELS) + def test_generate(self, model_name): + r""" + Test if `generate` works for every model + """ + generation_config = GenerationConfig(max_new_tokens=9) + model = self.trl_model_class.from_pretrained(model_name) + input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + decoder_input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) + + # Just check if the generation works + _ = model.generate(input_ids, decoder_input_ids=decoder_input_ids, generation_config=generation_config) + + def test_raise_error_not_causallm(self): + # Test with a model without a LM head + model_id = "trl-internal-testing/tiny-random-T5Model" + # This should raise a ValueError + with self.assertRaises(ValueError): + pretrained_model = AutoModel.from_pretrained(model_id) + _ = self.trl_model_class.from_pretrained(pretrained_model) + + @unittest.skip("This test needs to be run manually due to HF token issue.") + def test_push_to_hub(self): + for model_name in self.all_model_names: + model = self.trl_model_class.from_pretrained(model_name) + if "sharded" in model_name: + model.push_to_hub(model_name + "-ppo", use_auth_token=True, max_shard_size="1MB") + else: + model.push_to_hub(model_name + "-ppo", use_auth_token=True) + + model_from_pretrained = self.trl_model_class.from_pretrained(model_name + "-ppo") + # check all keys + self.assertEqual(model.state_dict().keys(), model_from_pretrained.state_dict().keys()) + + for name, param in model.state_dict().items(): + self.assertTrue( + torch.allclose(param, model_from_pretrained.state_dict()[name]), + f"Parameter {name} is not the same after push_to_hub and from_pretrained", + ) + + def test_transformers_bf16_kwargs(self): + r""" + Test if the transformers kwargs are correctly passed + Here we check that loading a model in half precision works as expected, i.e. the weights of + the `pretrained_model` attribute is loaded in half precision and you can run a dummy + forward pass without any issue. + """ + for model_name in self.all_model_names: + trl_model = self.trl_model_class.from_pretrained(model_name, torch_dtype=torch.bfloat16) + + lm_head_namings = self.trl_model_class.lm_head_namings + + if model_name == "trl-internal-testing/tiny-random-FSMTForConditionalGeneration": + # skip the test for FSMT as it does not support mixed-prec + continue + + self.assertTrue( + any(hasattr(trl_model.pretrained_model, lm_head_naming) for lm_head_naming in lm_head_namings) + ) + + for lm_head_naming in lm_head_namings: + if hasattr(trl_model.pretrained_model, lm_head_naming): + self.assertTrue(getattr(trl_model.pretrained_model, lm_head_naming).weight.dtype == torch.bfloat16) + + dummy_input = torch.LongTensor([[0, 1, 0, 1]]) + + # check dummy forward pass works in half precision + _ = trl_model(input_ids=dummy_input, decoder_input_ids=dummy_input) + + +class ReferenceModelTest(unittest.TestCase): + def setUp(self): + self.model = AutoModelForCausalLMWithValueHead.from_pretrained( + "trl-internal-testing/tiny-random-GPT2LMHeadModel" + ) + self.test_input = torch.tensor([[0, 1, 2, 3]]) + self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=1) + self.layer_format = "pretrained_model.transformer.h.{layer}.attn.c_attn.weight" + + def test_independent_reference(self): + layer_0 = self.layer_format.format(layer=0) + layer_5 = self.layer_format.format(layer=4) + + ref_model = create_reference_model(self.model) + + first_layer_before = self.model.get_parameter(layer_0).data.clone() + last_layer_before = self.model.get_parameter(layer_5).data.clone() + + first_ref_layer_before = ref_model.get_parameter(layer_0).data.clone() + last_ref_layer_before = ref_model.get_parameter(layer_5).data.clone() + + output = self.model(input_ids=self.test_input, labels=self.test_input) + output[1].backward() + self.optimizer.step() + + first_layer_after = self.model.get_parameter(layer_0).data.clone() + last_layer_after = self.model.get_parameter(layer_5).data.clone() + + first_ref_layer_after = ref_model.get_parameter(layer_0).data.clone() + last_ref_layer_after = ref_model.get_parameter(layer_5).data.clone() + + # before optimization ref and model are identical + self.assertTrue((first_layer_before == first_ref_layer_before).all()) + self.assertTrue((last_layer_before == last_ref_layer_before).all()) + + # ref model stays identical after optimization + self.assertTrue((first_ref_layer_before == first_ref_layer_after).all()) + self.assertTrue((last_ref_layer_before == last_ref_layer_after).all()) + + # optimized model changes + self.assertFalse((first_layer_before == first_layer_after).all()) + self.assertFalse((last_layer_before == last_layer_after).all()) + + def test_shared_layers(self): + layer_0 = self.layer_format.format(layer=0) + layer_1 = self.layer_format.format(layer=1) + + ref_model = create_reference_model(self.model, num_shared_layers=1) + + first_layer_before = self.model.get_parameter(layer_0).data.clone() + second_layer_before = self.model.get_parameter(layer_1).data.clone() + + first_ref_layer_before = ref_model.get_parameter(layer_0).data.clone() + second_ref_layer_before = ref_model.get_parameter(layer_1).data.clone() + + output = self.model(input_ids=self.test_input, labels=self.test_input) + output[1].backward() + self.optimizer.step() + + first_layer_after = self.model.get_parameter(layer_0).data.clone() + second_layer_after = self.model.get_parameter(layer_1).data.clone() + + first_ref_layer_after = ref_model.get_parameter(layer_0).data.clone() + second_ref_layer_after = ref_model.get_parameter(layer_1).data.clone() + + # before optimization ref and model are identical + self.assertTrue((first_layer_before == first_ref_layer_before).all()) + self.assertTrue((second_layer_before == second_ref_layer_before).all()) + + # ref model stays identical after optimization + self.assertTrue((first_ref_layer_before == first_ref_layer_after).all()) + self.assertTrue((second_ref_layer_before == second_ref_layer_after).all()) + + # first layer of optimized model stays the same + self.assertTrue((first_layer_before == first_layer_after).all()) + + # other layers in optimized model change + self.assertFalse((second_layer_before == second_layer_after).all()) diff --git a/testbed/huggingface__trl/tests/test_nash_md_trainer.py b/testbed/huggingface__trl/tests/test_nash_md_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..362b9ad47fe705dbf50c7fd7ce79ce4aac92ef36 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_nash_md_trainer.py @@ -0,0 +1,192 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import tempfile +import unittest + +from datasets import load_dataset +from parameterized import parameterized +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer +from transformers.testing_utils import require_peft +from transformers.utils import is_peft_available + +from trl import NashMDConfig, NashMDTrainer + +from .testing_utils import RandomPairwiseJudge, require_llm_blender + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestNashMDTrainer(unittest.TestCase): + def setUp(self): + self.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.reward_model = AutoModelForSequenceClassification.from_pretrained("EleutherAI/pythia-14m", num_labels=1) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) + def test_nash_md_trainer_training(self, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = NashMDConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + trainer = NashMDTrainer( + model=self.model, + ref_model=self.ref_model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = NashMDConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = NashMDTrainer( + model=self.model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft_and_ref_model(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = NashMDConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = NashMDTrainer( + model=self.model, + ref_model=self.ref_model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft_model_and_peft_config(self): + model_lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM") + model = get_peft_model(self.model, model_lora_config) + # we want only the "train adapter" to be trained + lora_train_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = NashMDConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = NashMDTrainer( + model=model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_train_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) + @require_llm_blender + def test_nash_md_trainer_judge_training(self, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = NashMDConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + judge = RandomPairwiseJudge() + + trainer = NashMDTrainer( + model=self.model, + ref_model=self.ref_model, + judge=judge, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) diff --git a/testbed/huggingface__trl/tests/test_online_dpo_trainer.py b/testbed/huggingface__trl/tests/test_online_dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a44e6a7186282964379b20c1b37382dc5d65d449 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_online_dpo_trainer.py @@ -0,0 +1,240 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import tempfile +import unittest + +from datasets import load_dataset +from parameterized import parameterized +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer +from transformers.testing_utils import require_peft +from transformers.utils import is_peft_available + +from trl import OnlineDPOConfig, OnlineDPOTrainer, is_llm_blender_available +from trl.trainer.utils import SIMPLE_CHAT_TEMPLATE + +from .testing_utils import RandomPairwiseJudge + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestOnlineDPOTrainer(unittest.TestCase): + def setUp(self): + self.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.reward_model = AutoModelForSequenceClassification.from_pretrained("EleutherAI/pythia-14m", num_labels=1) + self.reward_tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-14m") + self.reward_tokenizer.chat_template = SIMPLE_CHAT_TEMPLATE + self.reward_tokenizer.pad_token = self.reward_tokenizer.eos_token + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) + def test_training(self, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + trainer = OnlineDPOTrainer( + model=self.model, + reward_model=self.reward_model, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + reward_processing_class=self.reward_tokenizer, + ) + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + def test_training_with_ref_model(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = OnlineDPOTrainer( + model=self.model, + ref_model=self.ref_model, + reward_model=self.reward_model, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + reward_processing_class=self.reward_tokenizer, + ) + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + def test_ref_model_is_model(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + with self.assertRaises(ValueError): + OnlineDPOTrainer( + model=self.model, + ref_model=self.model, # ref_model can't be the same as model + reward_model=self.reward_model, + args=training_args, + train_dataset=dummy_dataset["train"], + processing_class=self.tokenizer, + reward_processing_class=self.reward_tokenizer, + ) + + @require_peft + def test_training_with_peft(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = OnlineDPOTrainer( + model=self.model, + reward_model=self.reward_model, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + reward_processing_class=self.reward_tokenizer, + peft_config=lora_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft_and_ref_model(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = OnlineDPOTrainer( + model=self.model, + ref_model=self.ref_model, + reward_model=self.reward_model, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + reward_processing_class=self.reward_tokenizer, + peft_config=lora_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft_model_and_peft_config(self): + model_lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM") + model = get_peft_model(self.model, model_lora_config) + # we want only the "train adapter" to be trained + lora_train_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = OnlineDPOTrainer( + model=model, + reward_model=self.reward_model, + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + reward_processing_class=self.reward_tokenizer, + peft_config=lora_train_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @unittest.skipIf(not is_llm_blender_available(), "llm-blender is not available") + @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) + def test_training_with_judge(self, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + trainer = OnlineDPOTrainer( + model=self.model, + judge=RandomPairwiseJudge(), + args=training_args, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + processing_class=self.tokenizer, + ) + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) diff --git a/testbed/huggingface__trl/tests/test_orpo_trainer.py b/testbed/huggingface__trl/tests/test_orpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..21aa284b34a1cfddfaa091f8c4bcede2b1e4898a --- /dev/null +++ b/testbed/huggingface__trl/tests/test_orpo_trainer.py @@ -0,0 +1,147 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import tempfile +import unittest + +import torch +from datasets import load_dataset +from parameterized import parameterized +from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer +from transformers.testing_utils import require_peft + +from trl import ORPOConfig, ORPOTrainer + + +class ORPOTrainerTester(unittest.TestCase): + def setUp(self): + self.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + # get t5 as seq2seq example: + model_id = "trl-internal-testing/tiny-T5ForConditionalGeneration-correct-vocab" + self.t5_model = AutoModelForSeq2SeqLM.from_pretrained(model_id) + self.t5_tokenizer = AutoTokenizer.from_pretrained(model_id) + + @parameterized.expand( + [ + ("gpt2", "standard_preference"), + ("t5", "standard_implicit_prompt_preference"), + ("gpt2", "conversational_preference"), + ("t5", "conversational_implicit_prompt_preference"), + ] + ) + def test_orpo_trainer(self, name, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = ORPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + if name == "gpt2": + model = self.model + tokenizer = self.tokenizer + elif name == "t5": + model = self.t5_model + tokenizer = self.t5_tokenizer + training_args.is_encoder_decoder = True + + trainer = ORPOTrainer( + model=model, + args=training_args, + processing_class=tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.equal(param, new_param)) + + @parameterized.expand( + [ + ("standard_preference",), + ("standard_implicit_prompt_preference",), + ("conversational_preference",), + ("conversational_implicit_prompt_preference",), + ] + ) + @require_peft + def test_orpo_trainer_with_lora(self, config_name): + from peft import LoraConfig + + lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + ) + + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = ORPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=4, + learning_rate=9e-1, + eval_strategy="steps", + beta=0.1, + report_to="none", + ) + + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + trainer = ORPOTrainer( + model=self.model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + if "lora" in n: + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.equal(param, new_param)) diff --git a/testbed/huggingface__trl/tests/test_peft_models.py b/testbed/huggingface__trl/tests/test_peft_models.py new file mode 100644 index 0000000000000000000000000000000000000000..d37058b8392043c673b2939c6390ff25f3e7d948 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_peft_models.py @@ -0,0 +1,204 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import tempfile +import unittest + +import torch +from transformers import AutoModelForCausalLM +from transformers.testing_utils import ( + require_peft, + require_torch_gpu_if_bnb_not_multi_backend_enabled, +) +from transformers.utils import is_peft_available + +from trl import AutoModelForCausalLMWithValueHead + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +@require_peft +class PeftModelTester(unittest.TestCase): + def setUp(self): + self.causal_lm_model_id = "trl-internal-testing/tiny-random-GPTNeoXForCausalLM" + self.lora_config = LoraConfig( + r=16, + lora_alpha=32, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + ) + + def test_create_peft_model(self): + r""" + Simply creates a peft model and checks that it can be loaded. + """ + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + pretrained_model = get_peft_model(causal_lm_model, self.lora_config) + + _ = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model) + + def test_peft_requires_grad(self): + r""" + Check that the value head of the returned model has requires_grad=True. + """ + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + pretrained_model = get_peft_model(causal_lm_model, self.lora_config) + + model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model) + + # Check that the value head has requires_grad=True + self.assertTrue(model.v_head.summary.weight.requires_grad) + + def test_check_peft_model_nb_trainable_params(self): + r""" + Check that the number of trainable parameters is correct. + """ + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + pretrained_model = get_peft_model(causal_lm_model, self.lora_config) + + model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model) + + # Check that the number of trainable parameters is correct + nb_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 10273) + + # Check that the number of trainable param for the non-peft model is correct + non_peft_model = AutoModelForCausalLMWithValueHead.from_pretrained(self.causal_lm_model_id) + nb_trainable_params = sum(p.numel() for p in non_peft_model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 99578) + + def test_create_peft_model_from_config(self): + r""" + Simply creates a peft model and checks that it can be loaded. + """ + trl_model = AutoModelForCausalLMWithValueHead.from_pretrained( + self.causal_lm_model_id, peft_config=self.lora_config + ) + # Check that the number of trainable parameters is correct + nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 10273) + + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + trl_model = AutoModelForCausalLMWithValueHead.from_pretrained(causal_lm_model, peft_config=self.lora_config) + # Check that the number of trainable parameters is correct + nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 10273) + + @require_torch_gpu_if_bnb_not_multi_backend_enabled + def test_create_bnb_peft_model_from_config(self): + r""" + Simply creates a peft model and checks that it can be loaded. + """ + from bitsandbytes.nn import Linear8bitLt + + trl_model = AutoModelForCausalLMWithValueHead.from_pretrained( + self.causal_lm_model_id, peft_config=self.lora_config, load_in_8bit=True + ) + # Check that the number of trainable parameters is correct + nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 10273) + self.assertEqual(trl_model.pretrained_model.model.gpt_neox.layers[0].mlp.dense_h_to_4h.__class__, Linear8bitLt) + + causal_lm_model = AutoModelForCausalLM.from_pretrained( + self.causal_lm_model_id, load_in_8bit=True, device_map="auto" + ) + trl_model = AutoModelForCausalLMWithValueHead.from_pretrained(causal_lm_model, peft_config=self.lora_config) + # Check that the number of trainable parameters is correct + nb_trainable_params = sum(p.numel() for p in trl_model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 10273) + self.assertEqual(trl_model.pretrained_model.model.gpt_neox.layers[0].mlp.dense_h_to_4h.__class__, Linear8bitLt) + + def test_save_pretrained_peft(self): + r""" + Check that the model can be saved and loaded properly. + """ + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + pretrained_model = get_peft_model(causal_lm_model, self.lora_config) + + model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + # check that the files `adapter_model.safetensors` and `adapter_config.json` are in the directory + self.assertTrue( + os.path.isfile(f"{tmp_dir}/adapter_model.safetensors"), + f"{tmp_dir}/adapter_model.safetensors does not exist", + ) + self.assertTrue( + os.path.exists(f"{tmp_dir}/adapter_config.json"), f"{tmp_dir}/adapter_config.json does not exist" + ) + + # check also for `pytorch_model.bin` and make sure it only contains `v_head` weights + self.assertTrue( + os.path.exists(f"{tmp_dir}/pytorch_model.bin"), f"{tmp_dir}/pytorch_model.bin does not exist" + ) + + # check that only keys that starts with `v_head` are in the dict + maybe_v_head = torch.load(f"{tmp_dir}/pytorch_model.bin", weights_only=True) + self.assertTrue( + all(k.startswith("v_head") for k in maybe_v_head.keys()), + f"keys in {tmp_dir}/pytorch_model.bin do not start with `v_head`", + ) + + model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(tmp_dir) + + # check all the weights are the same + for p1, p2 in zip(model.named_parameters(), model_from_pretrained.named_parameters()): + self.assertTrue(torch.allclose(p1[1], p2[1]), f"{p1[0]} != {p2[0]}") + + def test_load_pretrained_peft(self): + r""" + Check that the model saved with peft class interface can be loaded properly. + """ + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + pretrained_model = get_peft_model(causal_lm_model, self.lora_config) + + model = AutoModelForCausalLMWithValueHead.from_pretrained(pretrained_model) + + with tempfile.TemporaryDirectory() as tmp_dir: + pretrained_model.save_pretrained(tmp_dir) + model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(tmp_dir) + + # check that the files `adapter_model.safetensors` and `adapter_config.json` are in the directory + self.assertTrue( + os.path.isfile(f"{tmp_dir}/adapter_model.safetensors"), + f"{tmp_dir}/adapter_model.safetensors does not exist", + ) + self.assertTrue( + os.path.exists(f"{tmp_dir}/adapter_config.json"), f"{tmp_dir}/adapter_config.json does not exist" + ) + + # check all the weights are the same + for p1, p2 in zip(model.named_parameters(), model_from_pretrained.named_parameters()): + if p1[0] not in ["v_head.summary.weight", "v_head.summary.bias"]: + self.assertTrue(torch.allclose(p1[1], p2[1]), f"{p1[0]} != {p2[0]}") + + def test_continue_training_peft_model(self): + r""" + Load peft and checks that it can continue training. + """ + causal_lm_model = AutoModelForCausalLM.from_pretrained(self.causal_lm_model_id) + pretrained_model = get_peft_model(causal_lm_model, self.lora_config) + + with tempfile.TemporaryDirectory() as tmp_dir: + pretrained_model.save_pretrained(tmp_dir) + # set is_trainable to True + model = AutoModelForCausalLMWithValueHead.from_pretrained(tmp_dir, is_trainable=True) + # Check that the number of trainable parameters is correct + nb_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + self.assertEqual(nb_trainable_params, 10273) diff --git a/testbed/huggingface__trl/tests/test_ppo_trainer.py b/testbed/huggingface__trl/tests/test_ppo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..aacf0f2a1cd1ca6af67c25b7b640df2c80f3dbdf --- /dev/null +++ b/testbed/huggingface__trl/tests/test_ppo_trainer.py @@ -0,0 +1,100 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import platform +import subprocess + +from transformers.testing_utils import require_peft + + +def test(): + command = """\ +python examples/scripts/ppo/ppo.py \ + --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ + --dataset_train_split descriptiveness \ + --learning_rate 3e-6 \ + --output_dir models/minimal/ppo \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --total_episodes 10 \ + --model_name_or_path EleutherAI/pythia-14m \ + --missing_eos_penalty 1.0 \ + --save_strategy no \ + --stop_token eos +""" + if platform.system() == "Windows": + # windows CI does not work with subprocesses for some reason + # e.g., https://github.com/huggingface/trl/actions/runs/9600036224/job/26475286210?pr=1743 + return + subprocess.run( + command, + shell=True, + check=True, + ) + + +def test_num_train_epochs(): + command = """\ +python examples/scripts/ppo/ppo.py \ + --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ + --dataset_train_split descriptiveness \ + --learning_rate 3e-6 \ + --output_dir models/minimal/ppo \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --num_train_epochs 0.003 \ + --model_name_or_path EleutherAI/pythia-14m \ + --missing_eos_penalty 1.0 \ + --save_strategy no \ + --stop_token eos +""" + if platform.system() == "Windows": + # windows CI does not work with subprocesses for some reason + # e.g., https://github.com/huggingface/trl/actions/runs/9600036224/job/26475286210?pr=1743 + return + subprocess.run( + command, + shell=True, + check=True, + ) + + +@require_peft +def test_peft_support(): + command = """\ +python examples/scripts/ppo/ppo.py \ + --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ + --dataset_train_split descriptiveness \ + --learning_rate 3e-6 \ + --output_dir models/minimal/ppo \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --total_episodes 10 \ + --model_name_or_path EleutherAI/pythia-14m \ + --missing_eos_penalty 1.0 \ + --save_strategy no \ + --stop_token eos \ + --use_peft \ + --lora_r 32 \ + --lora_alpha 16 \ + --lora_target_modules query_key_value dense +""" + if platform.system() == "Windows": + # windows CI does not work with subprocesses for some reason + # e.g., https://github.com/huggingface/trl/actions/runs/9600036224/job/26475286210?pr=1743 + return + subprocess.run( + command, + shell=True, + check=True, + ) diff --git a/testbed/huggingface__trl/tests/test_reward_trainer.py b/testbed/huggingface__trl/tests/test_reward_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a56b037bef58d6f22fa547bafb3b2160e043b671 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_reward_trainer.py @@ -0,0 +1,242 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import tempfile +import unittest + +import torch +from datasets import Dataset, load_dataset +from transformers import AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction +from transformers.testing_utils import require_peft +from transformers.utils import is_peft_available + +from trl import RewardConfig, RewardTrainer, maybe_apply_chat_template +from trl.trainer import compute_accuracy +from trl.trainer.reward_trainer import _tokenize + + +if is_peft_available(): + from peft import LoraConfig, TaskType + + +class RewardTrainerTester(unittest.TestCase): + def setUp(self): + self.model_id = "hf-internal-testing/tiny-random-LlamaForCausalLM" + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.chat_template = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" + self.model = AutoModelForSequenceClassification.from_pretrained(self.model_id) + + def test_accuracy_metrics(self): + dummy_eval_predictions = EvalPrediction(torch.FloatTensor([[0.1, 0.9], [0.9, 0.1]]), torch.LongTensor([0, 0])) + accuracy = compute_accuracy(dummy_eval_predictions) + self.assertEqual(accuracy["accuracy"], 0.5) + + def test_preprocessing_conversational(self): + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + training_args = RewardConfig(output_dir=tmp_dir, report_to="none") + trainer = RewardTrainer( + model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset + ) + dummy_dataset = dummy_dataset.map(maybe_apply_chat_template, fn_kwargs={"tokenizer": self.tokenizer}) + dummy_dataset = dummy_dataset.map(_tokenize, batched=True, fn_kwargs={"tokenizer": self.tokenizer}) + self.assertDictEqual(trainer.train_dataset[:], dummy_dataset[:]) + + def test_preprocessing_standard(self): + # No chat template, so we load a fresh tokenizer + tokenizer = AutoTokenizer.from_pretrained(self.model_id) + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + training_args = RewardConfig(output_dir=tmp_dir, report_to="none") + trainer = RewardTrainer( + model=self.model, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset + ) + dummy_dataset = dummy_dataset.map(_tokenize, batched=True, fn_kwargs={"tokenizer": tokenizer}) + self.assertDictEqual(trainer.train_dataset[:], dummy_dataset[:]) + + def test_train_full(self): + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + training_args = RewardConfig(output_dir=tmp_dir, max_steps=3, report_to="none") + trainer = RewardTrainer( + model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset + ) + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) + + def test_train_full_pretokenized(self): + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + dummy_dataset = dummy_dataset.map(maybe_apply_chat_template, fn_kwargs={"tokenizer": self.tokenizer}) + dummy_dataset = dummy_dataset.map(_tokenize, batched=True, fn_kwargs={"tokenizer": self.tokenizer}) + training_args = RewardConfig(output_dir=tmp_dir, max_steps=3, report_to="none") + trainer = RewardTrainer( + model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset + ) + previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + # check the params have changed - ignore 0 biases + if param.sum() != 0: + self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) + + @require_peft + def test_train_lora(self): + peft_config = LoraConfig( + task_type=TaskType.SEQ_CLS, + inference_mode=False, + r=8, + lora_alpha=32, + lora_dropout=0.1, + ) + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + training_args = RewardConfig(output_dir=tmp_dir, max_steps=3, report_to="none") + trainer = RewardTrainer( + model=self.model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset, + peft_config=peft_config, + ) + previous_trainable_params = {} + previous_non_trainable_params = {} + + # due to a change in the way the modules to save are dealt in PEFT. + trainable_params_name = ["lora", "modules_to_save"] + + # check gradients are not None + for n, param in trainer.model.named_parameters(): + if any(t in n for t in trainable_params_name): + previous_trainable_params[n] = param.clone() + else: + previous_non_trainable_params[n] = param.clone() + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[(-1)]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + self.assertFalse(torch.allclose(param, new_param, atol=1e-12, rtol=1e-12)) + + # check the non trainable params have not changed + for n, param in previous_non_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + self.assertTrue(torch.allclose(param, new_param, atol=1e-12, rtol=1e-12)) + + @require_peft + def test_train_lora_pretokenized(self): + peft_config = LoraConfig( + task_type=TaskType.SEQ_CLS, + inference_mode=False, + r=8, + lora_alpha=32, + lora_dropout=0.1, + ) + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + dummy_dataset = dummy_dataset.map(maybe_apply_chat_template, fn_kwargs={"tokenizer": self.tokenizer}) + dummy_dataset = dummy_dataset.map(_tokenize, batched=True, fn_kwargs={"tokenizer": self.tokenizer}) + training_args = RewardConfig(output_dir=tmp_dir, max_steps=3, report_to="none") + trainer = RewardTrainer( + model=self.model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset, + peft_config=peft_config, + ) + previous_trainable_params = {} + previous_non_trainable_params = {} + + # due to a change in the way the modules to save are dealt in PEFT. + trainable_params_name = ["lora", "modules_to_save"] + + # check gradients are not None + for n, param in trainer.model.named_parameters(): + if any(t in n for t in trainable_params_name): + previous_trainable_params[n] = param.clone() + else: + previous_non_trainable_params[n] = param.clone() + + trainer.train() + + self.assertIsNotNone(trainer.state.log_history[(-1)]["train_loss"]) + + # check the params have changed + for n, param in previous_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + self.assertFalse(torch.allclose(param, new_param, atol=1e-12, rtol=1e-12)) + + # check the non trainable params have not changed + for n, param in previous_non_trainable_params.items(): + new_param = trainer.model.get_parameter(n) + self.assertTrue(torch.allclose(param, new_param, atol=1e-12, rtol=1e-12)) + + def test_margin(self): + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset_dict = { + "input_ids_chosen": [ + torch.LongTensor([0, 1, 2]), + ], + "attention_mask_chosen": [ + torch.LongTensor([1, 1, 1]), + ], + "input_ids_rejected": [ + torch.LongTensor([0, 2]), + ], + "attention_mask_rejected": [ + torch.LongTensor([1, 1]), + ], + "margin": [ + torch.FloatTensor([1.0]), + ], + } + dummy_dataset = Dataset.from_dict(dummy_dataset_dict) + training_args = RewardConfig(output_dir=tmp_dir, report_to="none") + trainer = RewardTrainer( + model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset + ) + + batch = [dummy_dataset[0]] + batch = trainer.data_collator(batch) + batch = {k: v.to(trainer.model.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()} + loss, outputs = trainer.compute_loss(trainer.model, batch, return_outputs=True) + + l_val = -torch.nn.functional.logsigmoid( + outputs["rewards_chosen"] - outputs["rewards_rejected"] - batch["margin"] + ).mean() + + self.assertLess(abs(loss - l_val), 1e-6) + + def test_tags(self): + with tempfile.TemporaryDirectory() as tmp_dir: + dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference", split="train") + training_args = RewardConfig(output_dir=tmp_dir, report_to="none") + trainer = RewardTrainer( + model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset + ) + self.assertEqual(trainer.model.model_tags, trainer._tag_names) diff --git a/testbed/huggingface__trl/tests/test_rich_progress_callback.py b/testbed/huggingface__trl/tests/test_rich_progress_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..84c287a86d484c32026864bbedc69610e21028f5 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_rich_progress_callback.py @@ -0,0 +1,66 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import tempfile +import unittest + +import torch +import torch.nn as nn +from datasets import Dataset +from transformers import Trainer, TrainingArguments + +from trl.trainer.callbacks import RichProgressCallback + + +class DummyModel(nn.Module): + def __init__(self): + super().__init__() + self.a = nn.Parameter(torch.tensor(1.0)) + + def forward(self, x): + return self.a * x + + +class TestRichProgressCallback(unittest.TestCase): + def setUp(self): + self.dummy_model = DummyModel() + self.dummy_train_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 5) + self.dummy_val_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 101) + + def test_rich_progress_callback_logging(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = TrainingArguments( + output_dir=tmp_dir, + per_device_eval_batch_size=2, + per_device_train_batch_size=2, + num_train_epochs=4, + eval_strategy="steps", + eval_steps=1, + logging_strategy="steps", + logging_steps=1, + save_strategy="no", + report_to="none", + disable_tqdm=True, + ) + callbacks = [RichProgressCallback()] + trainer = Trainer( + model=self.dummy_model, + train_dataset=self.dummy_train_dataset, + eval_dataset=self.dummy_val_dataset, + args=training_args, + callbacks=callbacks, + ) + + trainer.train() + trainer.train() diff --git a/testbed/huggingface__trl/tests/test_rloo_trainer.py b/testbed/huggingface__trl/tests/test_rloo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e02a2cb418c366e50515a763125f82a6aa135ae8 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_rloo_trainer.py @@ -0,0 +1,121 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import platform +import subprocess +import tempfile +import unittest + +import torch +from datasets import Dataset +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer + +from trl import RLOOConfig, RLOOTrainer + + +def test(): + command = """\ +python examples/scripts/rloo/rloo.py \ + --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ + --dataset_train_split descriptiveness \ + --learning_rate 3e-6 \ + --output_dir models/minimal/rloo \ + --per_device_train_batch_size 4 \ + --gradient_accumulation_steps 1 \ + --total_episodes 10 \ + --model_name_or_path EleutherAI/pythia-14m \ + --sft_model_path EleutherAI/pythia-14m \ + --reward_model_path EleutherAI/pythia-14m \ + --missing_eos_penalty 1.0 \ + --save_strategy no \ + --stop_token eos +""" + if platform.system() == "Windows": + # windows CI does not work with subprocesses for some reason + # e.g., https://github.com/huggingface/trl/actions/runs/9600036224/job/26475286210?pr=1743 + return + subprocess.run( + command, + shell=True, + check=True, + ) + + +class RLOOTrainerTester(unittest.TestCase): + def setUp(self): + self.sft_model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.reward_model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + + self.policy_model = AutoModelForCausalLM.from_pretrained(self.sft_model_id) + self.reward_model = AutoModelForSequenceClassification.from_pretrained(self.reward_model_id) + self.policy_ref_model = AutoModelForCausalLM.from_pretrained(self.sft_model_id) + + self.tokenizer = AutoTokenizer.from_pretrained(self.sft_model_id, padding_side="left") + self.tokenizer.chat_template = "{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}" + self.tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + + def test_rloo_checkpoint(self): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = RLOOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + total_episodes=1, + report_to="none", + ) + + dummy_text = {"content": "Hello World!", "role": "user"} + dummy_data = self.tokenizer.apply_chat_template(dummy_text) + dummy_dataset = Dataset.from_dict({"input_ids": dummy_data}) + + trainer = RLOOTrainer( + config=training_args, + policy=self.policy_model, + reward_model=self.reward_model, + ref_policy=self.policy_ref_model, + processing_class=self.tokenizer, + train_dataset=dummy_dataset, + eval_dataset=dummy_dataset, + ) + + trainer._save_checkpoint(trainer.model, trial=None) + + def test_rloo_reward(self): + local_batch_size = 3 + rloo_k = 4 + # fmt: off + rlhf_reward = torch.tensor([ + 1, 2, 3, # first rlhf reward for three prompts + 2, 3, 4, # second rlhf reward for three prompts + 5, 6, 7, # third rlhf reward for three prompts + 8, 9, 10, # fourth rlhf reward for three prompts + ]).float() + # fmt: on + + baseline = (rlhf_reward.sum(0) - rlhf_reward) / (rloo_k - 1) + advantages = torch.zeros_like(rlhf_reward) + for i in range(0, len(advantages), local_batch_size): + other_response_rlhf_rewards = [] + for j in range(0, len(advantages), local_batch_size): + if i != j: + other_response_rlhf_rewards.append(rlhf_reward[j : j + local_batch_size]) + advantages[i : i + local_batch_size] = rlhf_reward[i : i + local_batch_size] - torch.stack( + other_response_rlhf_rewards + ).mean(0) + self.assertLess((1 - (2 + 5 + 8) / 3 - advantages[0].item()), 1e-6) + self.assertLess((6 - (3 + 2 + 9) / 3 - advantages[7].item()), 1e-6) + + # vectorized impl + rlhf_reward = rlhf_reward.reshape(rloo_k, local_batch_size) + baseline = (rlhf_reward.sum(0) - rlhf_reward) / (rloo_k - 1) + vec_advantages = rlhf_reward - baseline + torch.testing.assert_close(vec_advantages.flatten(), advantages) diff --git a/testbed/huggingface__trl/tests/test_trainers_args.py b/testbed/huggingface__trl/tests/test_trainers_args.py new file mode 100644 index 0000000000000000000000000000000000000000..2f62e658a77a28f1bf055ff5124289185c5bfe35 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_trainers_args.py @@ -0,0 +1,395 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import tempfile +import unittest + +from datasets import load_dataset +from parameterized import parameterized +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer + +from trl import ( + BCOConfig, + BCOTrainer, + CPOConfig, + CPOTrainer, + DPOConfig, + DPOTrainer, + KTOConfig, + KTOTrainer, + NashMDConfig, + NashMDTrainer, + OnlineDPOConfig, + OnlineDPOTrainer, + ORPOConfig, + ORPOTrainer, + RewardConfig, + RewardTrainer, + SFTConfig, + SFTTrainer, + XPOConfig, + XPOTrainer, +) + +from .testing_utils import require_sklearn + + +class TrainerArgTester(unittest.TestCase): + @require_sklearn + def test_bco(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = BCOConfig( + tmp_dir, + max_length=256, + max_prompt_length=64, + max_completion_length=64, + beta=0.5, + label_pad_token_id=-99, + padding_value=-99, + truncation_mode="keep_start", + # generate_during_eval=True, # ignore this one, it requires wandb + is_encoder_decoder=True, + precompute_ref_log_probs=True, + model_init_kwargs={"trust_remote_code": True}, + ref_model_init_kwargs={"trust_remote_code": True}, + dataset_num_proc=4, + prompt_sample_size=512, + min_density_ratio=0.2, + max_density_ratio=20.0, + ) + trainer = BCOTrainer( + model="gpt2", ref_model="gpt2", args=training_args, train_dataset=dataset, processing_class=tokenizer + ) + self.assertEqual(trainer.args.max_length, 256) + self.assertEqual(trainer.args.max_prompt_length, 64) + self.assertEqual(trainer.args.max_completion_length, 64) + self.assertEqual(trainer.args.beta, 0.5) + self.assertEqual(trainer.args.label_pad_token_id, -99) + self.assertEqual(trainer.args.padding_value, -99) + self.assertEqual(trainer.args.truncation_mode, "keep_start") + # self.assertEqual(trainer.args.generate_during_eval, True) + self.assertEqual(trainer.args.is_encoder_decoder, True) + self.assertEqual(trainer.args.precompute_ref_log_probs, True) + self.assertEqual(trainer.args.model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.ref_model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.dataset_num_proc, 4) + self.assertEqual(trainer.args.prompt_sample_size, 512) + self.assertEqual(trainer.args.min_density_ratio, 0.2) + self.assertEqual(trainer.args.max_density_ratio, 20.0) + + def test_cpo(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = CPOConfig( + tmp_dir, + max_length=256, + max_prompt_length=64, + max_completion_length=64, + beta=0.5, + label_smoothing=0.5, + loss_type="hinge", + disable_dropout=False, + cpo_alpha=0.5, + simpo_gamma=0.2, + label_pad_token_id=-99, + padding_value=-99, + truncation_mode="keep_start", + # generate_during_eval=True, # ignore this one, it requires wandb + is_encoder_decoder=True, + model_init_kwargs={"trust_remote_code": True}, + dataset_num_proc=4, + ) + trainer = CPOTrainer(model="gpt2", args=training_args, train_dataset=dataset, processing_class=tokenizer) + self.assertEqual(trainer.args.max_length, 256) + self.assertEqual(trainer.args.max_prompt_length, 64) + self.assertEqual(trainer.args.max_completion_length, 64) + self.assertEqual(trainer.args.beta, 0.5) + self.assertEqual(trainer.args.label_smoothing, 0.5) + self.assertEqual(trainer.args.loss_type, "hinge") + self.assertEqual(trainer.args.disable_dropout, False) + self.assertEqual(trainer.args.cpo_alpha, 0.5) + self.assertEqual(trainer.args.simpo_gamma, 0.2) + self.assertEqual(trainer.args.label_pad_token_id, -99) + self.assertEqual(trainer.args.padding_value, -99) + self.assertEqual(trainer.args.truncation_mode, "keep_start") + # self.assertEqual(trainer.args.generate_during_eval, True) + self.assertEqual(trainer.args.is_encoder_decoder, True) + self.assertEqual(trainer.args.model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.dataset_num_proc, 4) + + def test_dpo(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = DPOConfig( + tmp_dir, + beta=0.5, + label_smoothing=0.5, + loss_type="hinge", + label_pad_token_id=-99, + padding_value=-99, + truncation_mode="keep_start", + max_length=256, + max_prompt_length=64, + max_completion_length=64, + is_encoder_decoder=True, + disable_dropout=False, + # generate_during_eval=True, # ignore this one, it requires wandb + precompute_ref_log_probs=True, + dataset_num_proc=4, + model_init_kwargs={"trust_remote_code": True}, + ref_model_init_kwargs={"trust_remote_code": True}, + model_adapter_name="dummy_adapter", + ref_adapter_name="dummy_adapter", + reference_free=True, + force_use_ref_model=True, + f_divergence_type="js_divergence", + f_alpha_divergence_coef=0.5, + # sync_ref_model=True, # cannot be True when precompute_ref_log_probs=True. Don't test this. + ref_model_mixup_alpha=0.5, + ref_model_sync_steps=32, + rpo_alpha=0.5, + discopop_tau=0.1, + ) + trainer = DPOTrainer( + model="gpt2", ref_model="gpt2", args=training_args, train_dataset=dataset, processing_class=tokenizer + ) + self.assertEqual(trainer.args.beta, 0.5) + self.assertEqual(trainer.args.label_smoothing, 0.5) + self.assertEqual(trainer.args.loss_type, "hinge") + self.assertEqual(trainer.args.label_pad_token_id, -99) + self.assertEqual(trainer.args.padding_value, -99) + self.assertEqual(trainer.args.truncation_mode, "keep_start") + self.assertEqual(trainer.args.max_length, 256) + self.assertEqual(trainer.args.max_prompt_length, 64) + self.assertEqual(trainer.args.max_completion_length, 64) + self.assertEqual(trainer.args.is_encoder_decoder, True) + self.assertEqual(trainer.args.disable_dropout, False) + # self.assertEqual(trainer.args.generate_during_eval, True) + self.assertEqual(trainer.args.precompute_ref_log_probs, True) + self.assertEqual(trainer.args.dataset_num_proc, 4) + self.assertEqual(trainer.args.model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.ref_model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.model_adapter_name, "dummy_adapter") + self.assertEqual(trainer.args.ref_adapter_name, "dummy_adapter") + self.assertEqual(trainer.args.reference_free, True) + self.assertEqual(trainer.args.force_use_ref_model, True) + self.assertEqual(trainer.args.f_divergence_type, "js_divergence") + self.assertEqual(trainer.args.f_alpha_divergence_coef, 0.5) + # self.assertEqual(trainer.args.sync_ref_model, True) + self.assertEqual(trainer.args.ref_model_mixup_alpha, 0.5) + self.assertEqual(trainer.args.ref_model_sync_steps, 32) + self.assertEqual(trainer.args.rpo_alpha, 0.5) + self.assertEqual(trainer.args.discopop_tau, 0.1) + + def test_kto(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + dataset = load_dataset("trl-internal-testing/zen", "standard_unpaired_preference", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = KTOConfig( + tmp_dir, + max_length=256, + max_prompt_length=64, + max_completion_length=64, + beta=0.5, + desirable_weight=0.5, + undesirable_weight=0.5, + label_pad_token_id=-99, + padding_value=-99, + truncation_mode="keep_start", + # generate_during_eval=True, # ignore this one, it requires wandb + is_encoder_decoder=True, + precompute_ref_log_probs=True, + model_init_kwargs={"trust_remote_code": True}, + ref_model_init_kwargs={"trust_remote_code": True}, + dataset_num_proc=4, + ) + trainer = KTOTrainer( + model="gpt2", ref_model="gpt2", args=training_args, train_dataset=dataset, processing_class=tokenizer + ) + self.assertEqual(trainer.args.max_length, 256) + self.assertEqual(trainer.args.max_prompt_length, 64) + self.assertEqual(trainer.args.max_completion_length, 64) + self.assertEqual(trainer.args.beta, 0.5) + self.assertEqual(trainer.args.desirable_weight, 0.5) + self.assertEqual(trainer.args.undesirable_weight, 0.5) + self.assertEqual(trainer.args.label_pad_token_id, -99) + self.assertEqual(trainer.args.padding_value, -99) + self.assertEqual(trainer.args.truncation_mode, "keep_start") + # self.assertEqual(trainer.args.generate_during_eval, True) + self.assertEqual(trainer.args.is_encoder_decoder, True) + self.assertEqual(trainer.args.precompute_ref_log_probs, True) + self.assertEqual(trainer.args.model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.ref_model_init_kwargs, {"trust_remote_code": True}) + self.assertEqual(trainer.args.dataset_num_proc, 4) + + @parameterized.expand([(False,), (True,)]) + def test_nash_md(self, mixtures_coef_list): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = NashMDConfig( + tmp_dir, + mixture_coef=0.5 if not mixtures_coef_list else [0.5, 0.6], + ) + model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + ref_model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + reward_model = AutoModelForSequenceClassification.from_pretrained("EleutherAI/pythia-14m", num_labels=1) + tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-14m") + trainer = NashMDTrainer( + args=training_args, + processing_class=tokenizer, + model=model, + ref_model=ref_model, + reward_model=reward_model, + train_dataset=dataset, + ) + self.assertEqual(trainer.args.mixture_coef, 0.5 if not mixtures_coef_list else [0.5, 0.6]) + + @parameterized.expand([(False,), (True,)]) + def test_online_dpo(self, beta_list): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = OnlineDPOConfig( + tmp_dir, + max_new_tokens=42, + temperature=0.5, + missing_eos_penalty=0.33, + beta=0.6 if not beta_list else [0.6, 0.7], + loss_type="hinge", + dataset_num_proc=4, + ) + model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + ref_model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + reward_model = AutoModelForSequenceClassification.from_pretrained("EleutherAI/pythia-14m", num_labels=1) + tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-14m") + trainer = OnlineDPOTrainer( + model=model, + ref_model=ref_model, + reward_model=reward_model, + args=training_args, + train_dataset=dataset, + processing_class=tokenizer, + reward_processing_class=tokenizer, + ) + self.assertEqual(trainer.args.max_new_tokens, 42) + self.assertEqual(trainer.args.temperature, 0.5) + self.assertEqual(trainer.args.missing_eos_penalty, 0.33) + self.assertEqual(trainer.args.beta, 0.6 if not beta_list else [0.6, 0.7]) + self.assertEqual(trainer.args.loss_type, "hinge") + self.assertEqual(trainer.args.dataset_num_proc, 4) + + def test_orpo(self): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = ORPOConfig( + tmp_dir, + max_length=256, + max_prompt_length=64, + max_completion_length=64, + beta=0.5, + disable_dropout=False, + label_pad_token_id=-99, + padding_value=-99, + truncation_mode="keep_start", + # generate_during_eval=True, # ignore this one, it requires wandb + is_encoder_decoder=True, + model_init_kwargs={"trust_remote_code": True}, + dataset_num_proc=4, + ) + + trainer = ORPOTrainer(model="gpt2", args=training_args, train_dataset=dataset, processing_class=tokenizer) + self.assertEqual(trainer.args.max_length, 256) + self.assertEqual(trainer.args.max_prompt_length, 64) + self.assertEqual(trainer.args.max_completion_length, 64) + self.assertEqual(trainer.args.beta, 0.5) + self.assertEqual(trainer.args.disable_dropout, False) + self.assertEqual(trainer.args.label_pad_token_id, -99) + + def test_reward(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = RewardConfig( + tmp_dir, + max_length=256, + dataset_num_proc=4, + center_rewards_coefficient=0.1, + ) + model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-14m") + trainer = RewardTrainer( + model=model, + args=training_args, + train_dataset=dataset, + processing_class=tokenizer, + ) + self.assertEqual(trainer.args.max_length, 256) + self.assertEqual(trainer.args.dataset_num_proc, 4) + self.assertEqual(trainer.args.center_rewards_coefficient, 0.1) + + def test_sft(self): + dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = SFTConfig( + tmp_dir, + dataset_text_field="dummy_text_field", + packing=True, + max_seq_length=256, + dataset_num_proc=4, + dataset_batch_size=512, + neftune_noise_alpha=0.1, + model_init_kwargs={"trust_remote_code": True}, + dataset_kwargs={"append_concat_token": True, "skip_prepare_dataset": True}, + eval_packing=True, + num_of_sequences=32, + chars_per_token=4.2, + ) + trainer = SFTTrainer("gpt2", args=training_args, train_dataset=dataset) + self.assertEqual(trainer.args.dataset_text_field, "dummy_text_field") + self.assertEqual(trainer.args.packing, True) + self.assertEqual(trainer.args.max_seq_length, 256) + self.assertEqual(trainer.args.dataset_num_proc, 4) + self.assertEqual(trainer.args.dataset_batch_size, 512) + self.assertEqual(trainer.args.neftune_noise_alpha, 0.1) + self.assertEqual(trainer.args.model_init_kwargs, {"trust_remote_code": True}) + self.assertIn("append_concat_token", trainer.args.dataset_kwargs) + self.assertEqual(trainer.args.dataset_kwargs["append_concat_token"], True) + self.assertEqual(trainer.args.eval_packing, True) + self.assertEqual(trainer.args.num_of_sequences, 32) + self.assertEqual(trainer.args.chars_per_token, 4.2) + + @parameterized.expand([(False,), (True,)]) + def test_xpo(self, alpha_list): + dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = XPOConfig( + tmp_dir, + alpha=0.5 if not alpha_list else [0.5, 0.6], + ) + model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + ref_model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-14m") + reward_model = AutoModelForSequenceClassification.from_pretrained("EleutherAI/pythia-14m", num_labels=1) + tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-14m") + trainer = XPOTrainer( + args=training_args, + processing_class=tokenizer, + model=model, + ref_model=ref_model, + reward_model=reward_model, + train_dataset=dataset, + ) + self.assertEqual(trainer.args.alpha, 0.5 if not alpha_list else [0.5, 0.6]) diff --git a/testbed/huggingface__trl/tests/test_utils.py b/testbed/huggingface__trl/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1c97f501376448780187314cc7b8d19b23642894 --- /dev/null +++ b/testbed/huggingface__trl/tests/test_utils.py @@ -0,0 +1,312 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import torch +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig +from transformers.testing_utils import require_peft +from transformers.utils import is_peft_available + +from trl.trainer.model_config import ModelConfig +from trl.trainer.utils import ( + DataCollatorForChatML, + batch_generation, + decode_and_strip_padding, + generate_model_card, + get_peft_config, + pad, +) + + +if is_peft_available(): + from peft import LoraConfig + + +class TestPad(unittest.TestCase): + def test_pad_1_dim_left(self): + x = torch.tensor([1, 2, 3]) + y = torch.tensor([4, 5]) + output = pad((x, y), padding_value=0, padding_side="left") + expected = torch.tensor([[1, 2, 3], [0, 4, 5]]) + self.assertTrue(torch.equal(output, expected)) + + def test_pad_1_dim_right(self): + x = torch.tensor([1, 2, 3]) + y = torch.tensor([4, 5]) + output = pad((x, y), padding_value=0, padding_side="right") + expected = torch.tensor([[1, 2, 3], [4, 5, 0]]) + self.assertTrue(torch.equal(output, expected)) + + def test_pad_2_dim_left(self): + x = torch.tensor([[1, 2], [3, 4]]) + y = torch.tensor([[5, 6]]) + output = pad((x, y), padding_value=0, padding_side="left") + expected = torch.tensor( + [ + [[1, 2], [3, 4]], + [[0, 0], [5, 6]], + ] + ) + self.assertTrue(torch.equal(output, expected)) + + def test_pad_2_dim_right(self): + x = torch.tensor([[1, 2], [3, 4]]) + y = torch.tensor([[5, 6]]) + output = pad((x, y), padding_value=0, padding_side="right") + expected = torch.tensor( + [ + [[1, 2], [3, 4]], + [[5, 6], [0, 0]], + ] + ) + self.assertTrue(torch.equal(output, expected)) + + def test_pad_2_dim_right_multidim(self): + x = torch.tensor([[1, 2], [3, 4]]) + y = torch.tensor([[5]]) + output = pad((x, y), padding_value=0, padding_side="right") + expected = torch.tensor( + [ + [[1, 2], [3, 4]], + [[5, 0], [0, 0]], + ] + ) + self.assertTrue(torch.equal(output, expected)) + + +@require_peft +class TestGetPEFTConfig(unittest.TestCase): + def test_create_peft_config_use_peft_false(self): + """Test that when use_peft is False, the function returns None.""" + model_config = ModelConfig(use_peft=False) + peft_config = get_peft_config(model_config) + self.assertIsNone(peft_config) + + def test_create_peft_config_use_peft_true(self): + """Test that when use_peft is True, the function returns a LoraConfig object.""" + # Provide non-default values to the model config for testing + peft_kwargs = { + "lora_r": 8, + "lora_alpha": 16, + "lora_dropout": 0.1, + "lora_task_type": "SEQ_CLS", + "use_rslora": True, + "lora_target_modules": ["up_proj", "down_proj"], + "lora_modules_to_save": ["up_proj"], + } + model_config = ModelConfig(use_peft=True, **peft_kwargs) + peft_config = get_peft_config(model_config) + self.assertTrue(isinstance(peft_config, LoraConfig)) + for arg, value in peft_kwargs.items(): + # Test that lists of modules are converted to sets + if arg == "lora_target_modules": + value = set(value) + # Rename the argument to match the LoraConfig attribute name + if arg in ["lora_r", "lora_task_type", "lora_target_modules", "lora_modules_to_save"]: + arg = arg[len("lora_") :] if arg.startswith("lora_") else arg + + self.assertEqual(getattr(peft_config, arg), value) + + +class TestDecodeAndStripPadding(unittest.TestCase): + def setUp(self): + self.tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct") + + def test_example_with_padding(self): + inputs = self.tokenizer(["Hello world", "Hello"], padding=True, return_tensors="pt") + decoded = decode_and_strip_padding(inputs["input_ids"], self.tokenizer) + self.assertEqual(decoded, ["Hello world", "Hello"]) + + def test_example_without_padding(self): + inputs = self.tokenizer(["Hello", "Hello"], padding=False, return_tensors="pt") + decoded = decode_and_strip_padding(inputs["input_ids"], self.tokenizer) + self.assertEqual(decoded, ["Hello", "Hello"]) + + +class TestGenerateModelCard(unittest.TestCase): + def test_full(self): + model_card = generate_model_card( + base_model="username/my_base_model", + model_name="my_model", + hub_model_id="username/my_hub_model", + dataset_name="username/my_dataset", + tags=["trl", "trainer-tag"], + wandb_url="https://wandb.ai/username/project_id/runs/abcd1234", + trainer_name="My Trainer", + trainer_citation="@article{my_trainer, ...}", + paper_title="My Paper", + paper_id="1234.56789", + ) + card_text = str(model_card) + self.assertIn("[username/my_base_model](https://huggingface.co/username/my_base_model)", card_text) + self.assertIn("my_model", card_text) + self.assertIn('pipeline("text-generation", model="username/my_hub_model", device="cuda")', card_text) + self.assertIn("datasets: username/my_dataset", card_text) + self.assertIn("](https://wandb.ai/username/project_id/runs/abcd1234)", card_text) + self.assertIn("My Trainer", card_text) + self.assertIn("```bibtex\n@article{my_trainer, ...}\n```", card_text) + self.assertIn("[My Paper](https://huggingface.co/papers/1234.56789)", card_text) + + def test_val_none(self): + model_card = generate_model_card( + base_model=None, + model_name="my_model", + hub_model_id="username/my_hub_model", + dataset_name=None, + tags=[], + wandb_url=None, + trainer_name="My Trainer", + trainer_citation=None, + paper_title=None, + paper_id=None, + ) + card_text = str(model_card) + self.assertIn("my_model", card_text) + self.assertIn('pipeline("text-generation", model="username/my_hub_model", device="cuda")', card_text) + self.assertIn("My Trainer", card_text) + + +class TestDataCollatorForChatML(unittest.TestCase): + def setUp(self): + # Initialize the tokenizer + self.tokenizer = AutoTokenizer.from_pretrained("codellama/CodeLlama-7b-Instruct-hf") + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + # Define token IDs + self.bos_token_id = self.tokenizer.bos_token_id if self.tokenizer.bos_token_id is not None else 1 + self.eos_token_id = self.tokenizer.eos_token_id if self.tokenizer.eos_token_id is not None else 2 + # Token ID for "true", the last assistant's response in the example: + self.ignore_index = -100 + self.max_length = 1024 + self.messages_key = "messages" + + # Example input + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + self.examples = dataset.to_list() + + # Initialize the data collator + self.collator = DataCollatorForChatML( + tokenizer=self.tokenizer, + max_length=self.max_length, + ignore_index=self.ignore_index, + ) + + def test_data_collator_for_chatml(self): + # Process the data + data = self.collator(self.examples) + + # Decode input_ids and labels for verification + input_ids = data["input_ids"][0].tolist() + labels = data["labels"][0].tolist() + prompt_only = data["prompts"][0].tolist() + + # Verify that input_ids start with optional padding tokens and a single BOS token and there are no extra ones + first_non_pad = next(token for token in input_ids if token != self.tokenizer.pad_token_id) + self.assertEqual( + first_non_pad, self.bos_token_id, "The first non-padding token of input_ids should be BOS token." + ) + self.assertEqual(input_ids.count(self.bos_token_id), 1, "There should be exactly one BOS token in input_ids.") + + # Verify that the assistant's response token is present in input_ids and not in the prompt_only + last_assistant_response = self.examples[0][self.messages_key][-1]["content"] + last_assistant_response_tokens = self.tokenizer.encode(last_assistant_response, add_special_tokens=False) + response_in_input_ids = all(token in input_ids for token in last_assistant_response_tokens) + self.assertTrue(response_in_input_ids, "The assistant's response should be present in input_ids.") + + # Check if the last assistant's response tokens are not in prompt_only + response_in_prompt = all(token in prompt_only for token in last_assistant_response_tokens) + self.assertFalse(response_in_prompt, "The assistant's response should not be present in prompt_only.") + + # Verify that EOS token is at the end of input_ids + self.assertEqual(input_ids[-1], self.eos_token_id, "The last token of input_ids should be EOS token.") + + # Verify that the labels preserved the target string (last_assistant_response) + last_assistant_response = self.examples[0][self.messages_key][-1]["content"] + last_assistant_response_tokens = self.tokenizer.encode(last_assistant_response, add_special_tokens=False) + + # Find the start and end of the last assistant's response in the labels + response_start = next(i for i, label in enumerate(labels) if label != self.ignore_index) + response_end = next(i for i in range(len(labels) - 1, -1, -1) if labels[i] != self.ignore_index) + + actual_response = labels[response_start : response_end - 1] + self.assertEqual( + actual_response, + last_assistant_response_tokens, + "The labels should preserve the last assistant's response tokens.", + ) + + # Verify that EOS token is at the end of labels + self.assertEqual(labels[-1], self.eos_token_id, "The last token of labels should be EOS token.") + + +class TestBatchGeneration(unittest.TestCase): + def setUp(self): + # Initialize the tokenizer + self.model_id = "Qwen/Qwen2-0.5B-Instruct" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + + self.generation_config = GenerationConfig( + max_new_tokens=128, + temperature=0.5, + do_sample=True, + top_k=0, + pad_token_id=self.tokenizer.pad_token_id, + ) + + # Example input + dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") + self.examples = dataset["messages"] + self.mini_batch_size = 3 + + def test_mini_batch_generation(self): + batch = [ + self.tokenizer.apply_chat_template(example[:-1], add_generation_prompt=True, tokenize=False) + for example in self.examples + ] + queries = self.tokenizer(batch, padding=True, return_tensors="pt")["input_ids"] + bs, context_length = queries.shape + + query_responses, logits = batch_generation( + self.model, queries, self.mini_batch_size, self.tokenizer.pad_token_id, self.generation_config + ) + + max_length_query = query_responses.shape[1] + max_length_logits = max_length_query - context_length + + self.assertGreater(max_length_query, context_length) + self.assertEqual(query_responses.shape, (bs, max_length_query)) + self.assertEqual(logits.shape, (bs, max_length_logits, self.model.config.vocab_size)) + + def test_single_batch_generation(self): + batch = [ + self.tokenizer.apply_chat_template(example[:-1], add_generation_prompt=True, tokenize=False) + for example in self.examples + ] + queries = self.tokenizer(batch, padding=True, return_tensors="pt")["input_ids"] + bs, context_length = queries.shape + + query_responses, logits = batch_generation( + self.model, queries, bs, self.tokenizer.pad_token_id, self.generation_config + ) + + max_length_query = query_responses.shape[1] + max_length_logits = max_length_query - context_length + + self.assertGreater(max_length_query, context_length) + self.assertEqual(query_responses.shape, (bs, max_length_query)) + self.assertEqual(logits.shape, (bs, max_length_logits, self.model.config.vocab_size)) diff --git a/testbed/huggingface__trl/tests/test_xpo_trainer.py b/testbed/huggingface__trl/tests/test_xpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..60f1a3a7b793787e4049a74bfb2817d1e61c540e --- /dev/null +++ b/testbed/huggingface__trl/tests/test_xpo_trainer.py @@ -0,0 +1,192 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import tempfile +import unittest + +from datasets import load_dataset +from parameterized import parameterized +from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer +from transformers.testing_utils import require_peft +from transformers.utils import is_peft_available + +from trl import XPOConfig, XPOTrainer, is_llm_blender_available + +from .testing_utils import RandomPairwiseJudge + + +if is_peft_available(): + from peft import LoraConfig, get_peft_model + + +class TestXPOTrainer(unittest.TestCase): + def setUp(self): + self.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" + self.model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) + self.reward_model = AutoModelForSequenceClassification.from_pretrained("EleutherAI/pythia-14m", num_labels=1) + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + self.tokenizer.pad_token = self.tokenizer.eos_token + + @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) + def test_xpo_trainer_training(self, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = XPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + + trainer = XPOTrainer( + model=self.model, + ref_model=self.ref_model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = XPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = XPOTrainer( + model=self.model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft_and_ref_model(self): + lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = XPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = XPOTrainer( + model=self.model, + ref_model=self.ref_model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @require_peft + def test_training_with_peft_model_and_peft_config(self): + model_lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM") + model = get_peft_model(self.model, model_lora_config) + # we want only the "train adapter" to be trained + lora_train_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = XPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + learning_rate=5.0e-7, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") + + trainer = XPOTrainer( + model=model, + reward_model=self.reward_model, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + peft_config=lora_train_config, + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) + + @unittest.skipIf(not is_llm_blender_available(), "llm-blender is not available") + @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) + def test_xpo_trainer_judge_training(self, config_name): + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = XPOConfig( + output_dir=tmp_dir, + per_device_train_batch_size=2, + max_steps=3, + remove_unused_columns=False, + gradient_accumulation_steps=1, + learning_rate=9e-1, + eval_strategy="steps", + report_to="none", + ) + dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) + judge = RandomPairwiseJudge() + + trainer = XPOTrainer( + model=self.model, + ref_model=self.ref_model, + judge=judge, + args=training_args, + processing_class=self.tokenizer, + train_dataset=dummy_dataset["train"], + eval_dataset=dummy_dataset["test"], + ) + + trainer.train() + + # Check if training loss is available + self.assertIn("train_loss", trainer.state.log_history[-1]) diff --git a/testbed/huggingface__trl/tests/testing_constants.py b/testbed/huggingface__trl/tests/testing_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..c66f60e5697fdf04ab7748bd703f52353d722552 --- /dev/null +++ b/testbed/huggingface__trl/tests/testing_constants.py @@ -0,0 +1,18 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +CI_HUB_USER = "__DUMMY_TRANSFORMERS_USER__" +CI_HUB_USER_FULL_NAME = "Dummy User" + +CI_HUB_ENDPOINT = "https://hub-ci.huggingface.co" diff --git a/testbed/huggingface__trl/tests/testing_utils.py b/testbed/huggingface__trl/tests/testing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6ac44bc86869b4ce3d966a6d5350192323cb93 --- /dev/null +++ b/testbed/huggingface__trl/tests/testing_utils.py @@ -0,0 +1,77 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import random +import unittest + +from transformers import is_bitsandbytes_available, is_sklearn_available, is_wandb_available + +from trl import BaseBinaryJudge, BasePairwiseJudge, is_diffusers_available, is_llm_blender_available + + +# transformers.testing_utils contains a require_bitsandbytes function, but relies on pytest markers which we don't use +# in our test suite. We therefore need to implement our own version of this function. +def require_bitsandbytes(test_case): + """ + Decorator marking a test that requires bitsandbytes. Skips the test if bitsandbytes is not available. + """ + return unittest.skipUnless(is_bitsandbytes_available(), "test requires bitsandbytes")(test_case) + + +def require_diffusers(test_case): + """ + Decorator marking a test that requires diffusers. Skips the test if diffusers is not available. + """ + return unittest.skipUnless(is_diffusers_available(), "test requires diffusers")(test_case) + + +def require_no_wandb(test_case): + """ + Decorator marking a test that requires no wandb. Skips the test if wandb is available. + """ + return unittest.skipUnless(not is_wandb_available(), "test requires no wandb")(test_case) + + +def require_sklearn(test_case): + """ + Decorator marking a test that requires sklearn. Skips the test if sklearn is not available. + """ + return unittest.skipUnless(is_sklearn_available(), "test requires sklearn")(test_case) + + +def require_llm_blender(test_case): + """ + Decorator marking a test that requires llm-blender. Skips the test if llm-blender is not available. + """ + return unittest.skipUnless(is_llm_blender_available(), "test requires llm-blender")(test_case) + + +class RandomBinaryJudge(BaseBinaryJudge): + """ + Random binary judge, for testing purposes. + """ + + def judge(self, prompts, completions, gold_completions=None, shuffle_order=True): + return [random.choice([0, 1, -1]) for _ in range(len(prompts))] + + +class RandomPairwiseJudge(BasePairwiseJudge): + """ + Random pairwise judge, for testing purposes. + """ + + def judge(self, prompts, completions, shuffle_order=True, return_scores=False): + if not return_scores: + return [random.randint(0, len(completion) - 1) for completion in completions] + else: + return [random.random() for _ in range(len(prompts))] diff --git a/testbed/huggingface__trl/trl/__init__.py b/testbed/huggingface__trl/trl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9078132526128f989ce4a4a6e0f74d2e8f5466e --- /dev/null +++ b/testbed/huggingface__trl/trl/__init__.py @@ -0,0 +1,210 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "0.13.0.dev0" + +from typing import TYPE_CHECKING + +from .import_utils import OptionalDependencyNotAvailable, _LazyModule, is_diffusers_available + + +_import_structure = { + "commands.cli_utils": ["DPOScriptArguments", "SFTScriptArguments", "TrlParser", "init_zero_verbose"], + "core": ["set_seed"], + "data_utils": [ + "apply_chat_template", + "extract_prompt", + "is_conversational", + "maybe_apply_chat_template", + "maybe_extract_prompt", + "maybe_unpair_preference_dataset", + "unpair_preference_dataset", + ], + "environment": ["TextEnvironment", "TextHistory"], + "extras": ["BestOfNSampler"], + "import_utils": [ + "is_deepspeed_available", + "is_diffusers_available", + "is_llm_blender_available", + ], + "models": [ + "SUPPORTED_ARCHITECTURES", + "AutoModelForCausalLMWithValueHead", + "AutoModelForSeq2SeqLMWithValueHead", + "PreTrainedModelWrapper", + "create_reference_model", + "setup_chat_format", + ], + "trainer": [ + "AlignPropConfig", + "AlignPropTrainer", + "AllTrueJudge", + "BaseBinaryJudge", + "BaseJudge", + "BasePairwiseJudge", + "BaseRankJudge", + "BCOConfig", + "BCOTrainer", + "CPOConfig", + "CPOTrainer", + "DataCollatorForCompletionOnlyLM", + "DPOConfig", + "DPOTrainer", + "FDivergenceConstants", + "FDivergenceType", + "GKDConfig", + "GKDTrainer", + "HfPairwiseJudge", + "IterativeSFTTrainer", + "KTOConfig", + "KTOTrainer", + "LogCompletionsCallback", + "ModelConfig", + "NashMDConfig", + "NashMDTrainer", + "OnlineDPOConfig", + "OnlineDPOTrainer", + "OpenAIPairwiseJudge", + "ORPOConfig", + "ORPOTrainer", + "PairRMJudge", + "PPOConfig", + "PPOTrainer", + "RewardConfig", + "RewardTrainer", + "RLOOConfig", + "RLOOTrainer", + "SFTConfig", + "SFTTrainer", + "WinRateCallback", + "XPOConfig", + "XPOTrainer", + ], + "trainer.callbacks": ["RichProgressCallback", "SyncRefModelCallback"], + "trainer.utils": ["get_kbit_device_map", "get_peft_config", "get_quantization_config"], + "utils": ["ScriptArguments"], +} + +try: + if not is_diffusers_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["models"].extend( + [ + "DDPOPipelineOutput", + "DDPOSchedulerOutput", + "DDPOStableDiffusionPipeline", + "DefaultDDPOStableDiffusionPipeline", + ] + ) + _import_structure["trainer"].extend(["DDPOConfig", "DDPOTrainer"]) + +if TYPE_CHECKING: + from .commands.cli_utils import DPOScriptArguments, SFTScriptArguments, TrlParser, init_zero_verbose + from .core import set_seed + from .data_utils import ( + apply_chat_template, + extract_prompt, + is_conversational, + maybe_apply_chat_template, + maybe_extract_prompt, + maybe_unpair_preference_dataset, + unpair_preference_dataset, + ) + from .environment import TextEnvironment, TextHistory + from .extras import BestOfNSampler + from .import_utils import is_deepspeed_available, is_diffusers_available, is_llm_blender_available + from .models import ( + SUPPORTED_ARCHITECTURES, + AutoModelForCausalLMWithValueHead, + AutoModelForSeq2SeqLMWithValueHead, + PreTrainedModelWrapper, + create_reference_model, + setup_chat_format, + ) + from .trainer import ( + AlignPropConfig, + AlignPropTrainer, + AllTrueJudge, + BaseBinaryJudge, + BaseJudge, + BasePairwiseJudge, + BaseRankJudge, + BCOConfig, + BCOTrainer, + CPOConfig, + CPOTrainer, + DataCollatorForCompletionOnlyLM, + DPOConfig, + DPOTrainer, + FDivergenceConstants, + FDivergenceType, + GKDConfig, + GKDTrainer, + HfPairwiseJudge, + IterativeSFTTrainer, + KTOConfig, + KTOTrainer, + LogCompletionsCallback, + ModelConfig, + NashMDConfig, + NashMDTrainer, + OnlineDPOConfig, + OnlineDPOTrainer, + OpenAIPairwiseJudge, + ORPOConfig, + ORPOTrainer, + PairRMJudge, + PPOConfig, + PPOTrainer, + RewardConfig, + RewardTrainer, + RLOOConfig, + RLOOTrainer, + SFTConfig, + SFTTrainer, + WinRateCallback, + XPOConfig, + XPOTrainer, + ) + from .trainer.callbacks import RichProgressCallback, SyncRefModelCallback + from .trainer.utils import get_kbit_device_map, get_peft_config, get_quantization_config + from .utils import ScriptArguments + + try: + if not is_diffusers_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .models import ( + DDPOPipelineOutput, + DDPOSchedulerOutput, + DDPOStableDiffusionPipeline, + DefaultDDPOStableDiffusionPipeline, + ) + from .trainer import DDPOConfig, DDPOTrainer + +else: + import sys + + sys.modules[__name__] = _LazyModule( + __name__, + globals()["__file__"], + _import_structure, + module_spec=__spec__, + extra_objects={"__version__": __version__}, + ) diff --git a/testbed/huggingface__trl/trl/commands/__init__.py b/testbed/huggingface__trl/trl/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c4da312cd99ba26f4db5c43990366aaadd865a55 --- /dev/null +++ b/testbed/huggingface__trl/trl/commands/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from ..import_utils import OptionalDependencyNotAvailable, _LazyModule + + +_import_structure = { + "cli_utils": ["DPOScriptArguments", "SFTScriptArguments", "TrlParser", "YamlConfigParser", "init_zero_verbose"], +} + +if TYPE_CHECKING: + from .cli_utils import DPOScriptArguments, SFTScriptArguments, TrlParser, YamlConfigParser, init_zero_verbose +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/testbed/huggingface__trl/trl/commands/cli.py b/testbed/huggingface__trl/trl/commands/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4266e631e8186b36d54783cdbbe3f2190bd298 --- /dev/null +++ b/testbed/huggingface__trl/trl/commands/cli.py @@ -0,0 +1,143 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import platform +import subprocess +import sys +from importlib.metadata import version +from subprocess import CalledProcessError + +import torch +from accelerate.commands.config import default_config_file, load_config_from_file +from rich.console import Console +from transformers import is_bitsandbytes_available +from transformers.utils import is_liger_kernel_available, is_openai_available, is_peft_available + +from .. import __version__, is_deepspeed_available, is_diffusers_available, is_llm_blender_available +from .cli_utils import get_git_commit_hash + + +SUPPORTED_COMMANDS = ["sft", "dpo", "chat", "kto", "env"] + + +def print_env(): + if torch.cuda.is_available(): + devices = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] + + accelerate_config = accelerate_config_str = "not found" + + # Get the default from the config file. + if os.path.isfile(default_config_file): + accelerate_config = load_config_from_file(default_config_file).to_dict() + + accelerate_config_str = ( + "\n" + "\n".join([f" - {prop}: {val}" for prop, val in accelerate_config.items()]) + if isinstance(accelerate_config, dict) + else accelerate_config + ) + + commit_hash = get_git_commit_hash("trl") + + info = { + "Platform": platform.platform(), + "Python version": platform.python_version(), + "PyTorch version": version("torch"), + "CUDA device(s)": ", ".join(devices) if torch.cuda.is_available() else "not available", + "Transformers version": version("transformers"), + "Accelerate version": version("accelerate"), + "Accelerate config": accelerate_config_str, + "Datasets version": version("datasets"), + "HF Hub version": version("huggingface_hub"), + "TRL version": f"{__version__}+{commit_hash[:7]}" if commit_hash else __version__, + "bitsandbytes version": version("bitsandbytes") if is_bitsandbytes_available() else "not installed", + "DeepSpeed version": version("deepspeed") if is_deepspeed_available() else "not installed", + "Diffusers version": version("diffusers") if is_diffusers_available() else "not installed", + "Liger-Kernel version": version("liger_kernel") if is_liger_kernel_available() else "not installed", + "LLM-Blender version": version("llm_blender") if is_llm_blender_available() else "not installed", + "OpenAI version": version("openai") if is_openai_available() else "not installed", + "PEFT version": version("peft") if is_peft_available() else "not installed", + } + + info_str = "\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + print(f"\nCopy-paste the following information when reporting an issue:\n\n{info_str}\n") # noqa + + +def train(command_name): + console = Console() + # Make sure to import things locally to avoid verbose from third party libs. + with console.status("[bold purple]Welcome! Initializing the TRL CLI..."): + from trl.commands.cli_utils import init_zero_verbose + + init_zero_verbose() + command_name = sys.argv[1] + trl_examples_dir = os.path.dirname(__file__) + + command = f"accelerate launch {trl_examples_dir}/scripts/{command_name}.py {' '.join(sys.argv[2:])}" + + try: + subprocess.run( + command.split(), + text=True, + check=True, + encoding="utf-8", + cwd=os.getcwd(), + env=os.environ.copy(), + ) + except (CalledProcessError, ChildProcessError) as exc: + console.log(f"TRL - {command_name.upper()} failed on ! See the logs above for further details.") + raise ValueError("TRL CLI failed! Check the traceback above..") from exc + + +def chat(): + console = Console() + # Make sure to import things locally to avoid verbose from third party libs. + with console.status("[bold purple]Welcome! Initializing the TRL CLI..."): + from trl.commands.cli_utils import init_zero_verbose + + init_zero_verbose() + trl_examples_dir = os.path.dirname(__file__) + + command = f"python {trl_examples_dir}/scripts/chat.py {' '.join(sys.argv[2:])}" + + try: + subprocess.run( + command.split(), + text=True, + check=True, + encoding="utf-8", + cwd=os.getcwd(), + env=os.environ.copy(), + ) + except (CalledProcessError, ChildProcessError) as exc: + console.log("TRL - CHAT failed! See the logs above for further details.") + raise ValueError("TRL CLI failed! Check the traceback above..") from exc + + +def main(): + command_name = sys.argv[1] + + if command_name in ["sft", "dpo", "kto"]: + train(command_name) + elif command_name == "chat": + chat() + elif command_name == "env": + print_env() + else: + raise ValueError( + f"Please use one of the supported commands, got {command_name} - supported commands are {SUPPORTED_COMMANDS}" + ) + + +if __name__ == "__main__": + main() diff --git a/testbed/huggingface__trl/trl/commands/cli_utils.py b/testbed/huggingface__trl/trl/commands/cli_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ce930479aaf25df5a4efbf53299f7bf005dd71 --- /dev/null +++ b/testbed/huggingface__trl/trl/commands/cli_utils.py @@ -0,0 +1,257 @@ +# This file is a copy of trl/examples/scripts/sft.py so that we could +# use it together with rich and the TRL CLI in a more customizable manner. +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import importlib +import inspect +import logging +import os +import subprocess +import sys +from argparse import Namespace +from dataclasses import dataclass, field + +import yaml +from transformers import HfArgumentParser + + +logger = logging.getLogger(__name__) + + +class YamlConfigParser: + def parse_and_set_env(self, config_path): + with open(config_path) as yaml_file: + config = yaml.safe_load(yaml_file) + + if "env" in config: + env_vars = config.pop("env") + if isinstance(env_vars, dict): + for key, value in env_vars.items(): + os.environ[key] = str(value) + else: + raise ValueError("`env` field should be a dict in the YAML file.") + + return config + + def to_string(self, config): + final_string = "" + for key, value in config.items(): + if isinstance(value, (dict, list)): + if len(value) != 0: + value = str(value) + value = value.replace("'", '"') + value = f"'{value}'" + else: + continue + + final_string += f"--{key} {value} " + return final_string + + +def init_zero_verbose(): + """ + Perform zero verbose init - use this method on top of the CLI modules to make + """ + import logging + import warnings + + from rich.logging import RichHandler + + FORMAT = "%(message)s" + logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()], level=logging.ERROR) + + # Custom warning handler to redirect warnings to the logging system + def warning_handler(message, category, filename, lineno, file=None, line=None): + logging.warning(f"{filename}:{lineno}: {category.__name__}: {message}") + + # Add the custom warning handler - we need to do that before importing anything to make sure the loggers work well + warnings.showwarning = warning_handler + + +@dataclass +class ChatArguments: + # general settings + model_name_or_path: str = field(metadata={"help": "Name of the pre-trained model"}) + user: str = field(default=None, metadata={"help": "Username to display in chat interface"}) + system_prompt: str = field(default=None, metadata={"help": "System prompt"}) + save_folder: str = field(default="./chat_history/", metadata={"help": "Folder to save chat history"}) + device: str = field( + default="cpu", + metadata={"help": "device to use for inference."}, + ) + config: str = field( + default="default", + metadata={ + "help": "Config file used for setting the configs. If `default` uses examples/scripts/config/default_chat_config.yaml" + }, + ) + examples: str = field(default=None, metadata={"help": "Empty placeholder needs to be set via config."}) + # generation settings + max_new_tokens: int = field(default=256, metadata={"help": "Maximum number of tokens to generate"}) + do_sample: bool = field(default=True, metadata={"help": "Whether to sample outputs during generation"}) + num_beams: int = field(default=1, metadata={"help": "Number of beams for beam search"}) + temperature: float = field(default=1.0, metadata={"help": "Temperature parameter for generation"}) + top_k: int = field(default=50, metadata={"help": "Value of k for top-k sampling"}) + top_p: float = field(default=1.0, metadata={"help": "Value of p for nucleus sampling"}) + repetition_penalty: float = field(default=1.0, metadata={"help": "Repetition penalty"}) + eos_tokens: str = field( + default=None, + metadata={"help": "EOS tokens to stop the generation. If multiple they should be comma separated"}, + ) + eos_token_ids: str = field( + default=None, + metadata={"help": "EOS token IDs to stop the generation. If multiple they should be comma separated"}, + ) + # model loading + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + torch_dtype: str = field( + default=None, + metadata={ + "help": ( + "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " + "dtype will be automatically derived from the model's weights." + ), + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + trust_remote_code: bool = field(default=False, metadata={"help": "Trust remote code when loading a model."}) + attn_implementation: str = field( + default=None, + metadata={ + "help": ( + "Which attention implementation to use; you can run --attn_implementation=flash_attention_2, in which case you must install this manually by running `pip install flash-attn --no-build-isolation`" + ) + }, + ) + load_in_8bit: bool = field( + default=False, + metadata={"help": "use 8 bit precision for the base model - works only with LoRA"}, + ) + load_in_4bit: bool = field( + default=False, + metadata={"help": "use 4 bit precision for the base model - works only with LoRA"}, + ) + + bnb_4bit_quant_type: str = field(default="nf4", metadata={"help": "precise the quantization type (fp4 or nf4)"}) + use_bnb_nested_quant: bool = field(default=False, metadata={"help": "use nested quantization"}) + + +class TrlParser(HfArgumentParser): + def __init__(self, parsers, ignore_extra_args=False): + """ + The TRL parser parses a list of parsers (TrainingArguments, trl.ModelConfig, etc.), creates a config + parsers for users that pass a valid `config` field and merge the values that are set in the config + with the processed parsers. + + Args: + parsers (`List[argparse.ArgumentParser`]): + List of parsers. + ignore_extra_args (`bool`): + Whether to ignore extra arguments passed by the config + and not raise errors. + """ + super().__init__(parsers) + self.yaml_parser = YamlConfigParser() + self.ignore_extra_args = ignore_extra_args + + def post_process_dataclasses(self, dataclasses): + # Apply additional post-processing in case some arguments needs a special + # care + training_args = trl_args = None + training_args_index = None + + for i, dataclass_obj in enumerate(dataclasses): + if dataclass_obj.__class__.__name__ == "TrainingArguments": + training_args = dataclass_obj + training_args_index = i + elif dataclass_obj.__class__.__name__ in ("SFTScriptArguments", "DPOScriptArguments"): + trl_args = dataclass_obj + else: + ... + + if trl_args is not None and training_args is not None: + training_args.gradient_checkpointing_kwargs = dict( + use_reentrant=trl_args.gradient_checkpointing_use_reentrant + ) + dataclasses[training_args_index] = training_args + + return dataclasses + + def parse_args_and_config(self, return_remaining_strings=False): + yaml_config = None + if "--config" in sys.argv: + config_index = sys.argv.index("--config") + + _ = sys.argv.pop(config_index) # --config + config_path = sys.argv.pop(config_index) # path to config + yaml_config = self.yaml_parser.parse_and_set_env(config_path) + + self.set_defaults_with_config(**yaml_config) + + outputs = self.parse_args_into_dataclasses(return_remaining_strings=return_remaining_strings) + + if yaml_config is None: + return outputs + + if return_remaining_strings: + # if we have extra yaml config and command line strings + # outputs[-1] is remaining command line strings + # outputs[-2] is remaining yaml config as Namespace + # combine them into remaining strings object + remaining_strings = outputs[-1] + [f"{key}: {value}" for key, value in vars(outputs[-2]).items()] + return outputs[:-2], remaining_strings + else: + # outputs[-1] is either remaining yaml config as Namespace or parsed config as Dataclass + if isinstance(outputs[-1], Namespace) and not self.ignore_extra_args: + remaining_args = vars(outputs[-1]) + raise ValueError(f"Some specified config arguments are not used by the TrlParser: {remaining_args}") + + return outputs + + def set_defaults_with_config(self, **kwargs): + """Defaults we're setting with config allow us to change to required = False""" + self._defaults.update(kwargs) + + # if these defaults match any existing arguments, replace + # the previous default on the object with the new one + for action in self._actions: + if action.dest in kwargs: + action.default = kwargs[action.dest] + action.required = False + + +def get_git_commit_hash(package_name): + try: + # Import the package to locate its path + package = importlib.import_module(package_name) + # Get the path to the package using inspect + package_path = os.path.dirname(inspect.getfile(package)) + + # Navigate up to the Git repository root if the package is inside a subdirectory + git_repo_path = os.path.abspath(os.path.join(package_path, "..")) + git_dir = os.path.join(git_repo_path, ".git") + + if os.path.isdir(git_dir): + # Run the git command to get the current commit hash + commit_hash = ( + subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=git_repo_path).strip().decode("utf-8") + ) + return commit_hash + else: + return None + except Exception as e: + return f"Error: {str(e)}" diff --git a/testbed/huggingface__trl/trl/core.py b/testbed/huggingface__trl/trl/core.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7bb840f6e1465ba337509dd2a3aadf3608d4ab --- /dev/null +++ b/testbed/huggingface__trl/trl/core.py @@ -0,0 +1,318 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import gc +import random +import warnings +from contextlib import contextmanager +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.nn.utils.rnn import pad_sequence +from transformers import TopKLogitsWarper, TopPLogitsWarper, is_torch_npu_available, is_torch_xpu_available + + +try: + from collections.abc import Mapping +except ImportError: + from collections.abc import Mapping + + +WANDB_PADDING = -1 + + +def top_k_top_p_filtering( + logits: torch.FloatTensor, + top_k: int = 0, + top_p: float = 1.0, + filter_value: float = -float("Inf"), + min_tokens_to_keep: int = 1, +) -> torch.FloatTensor: + """ + Filter a distribution of logits using top-k and/or nucleus (top-p) filtering. + + Args: + logits: logits distribution shape (batch size, vocabulary size) + top_k (`int`, *optional*, defaults to 0): + If > 0, only keep the top k tokens with highest probability (top-k filtering) + top_p (`float`, *optional*, defaults to 1.0): + If < 1.0, only keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus + filtering is described in Holtzman et al. (https://huggingface.co/papers/1904.09751) + min_tokens_to_keep (`int`, *optional*, defaults to 1): + Minimumber of tokens we keep per batch example in the output. + + From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317 + """ + + if top_k > 0: + logits = TopKLogitsWarper(top_k=top_k, filter_value=filter_value, min_tokens_to_keep=min_tokens_to_keep)( + None, logits + ) + + if 0 <= top_p <= 1.0: + logits = TopPLogitsWarper(top_p=top_p, filter_value=filter_value, min_tokens_to_keep=min_tokens_to_keep)( + None, logits + ) + + return logits + + +def flatten_dict(nested: Dict, sep: str = "/") -> Dict: + """Flatten dictionary and concatenate nested keys with separator.""" + + def recurse(nest: Dict, prefix: str, into: Dict) -> None: + for k, v in nest.items(): + if sep in k: + raise ValueError(f"separator '{sep}' not allowed to be in key '{k}'") + if isinstance(v, Mapping): + recurse(v, prefix + k + sep, into) + else: + into[prefix + k] = v + + flat = {} + recurse(nested, "", flat) + return flat + + +def convert_to_scalar(stats: Dict) -> Dict: + """ + Converts the stats from a flattened dict to single scalar dicts + """ + tensorboard_stats = {} + for k, v in stats.items(): + # for tensorboard compatibility - arrays and tensors are ignored with tensorboard + # therefore we convert single element tensors to scalars + if (isinstance(v, torch.Tensor) or isinstance(v, np.ndarray)) and ( + len(v.shape) == 0 or (len(v.shape) == 1 and v.shape[0] == 1) + ): + v = v.item() + tensorboard_stats[k] = v + return tensorboard_stats + + +def stack_dicts(stats_dicts: List[Dict]) -> Dict: + """Stack the values of a dict.""" + results = dict() + for k in stats_dicts[0]: + stats_list = [torch.flatten(d[k]) for d in stats_dicts] + results[k] = pad_sequence(stats_list, batch_first=True, padding_value=WANDB_PADDING) + return results + + +def logprobs_from_logits(logits: torch.Tensor, labels: torch.Tensor, gather: bool = True) -> torch.Tensor: + """ + See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591 + """ + logp = F.log_softmax(logits, dim=2) + + if not gather: + return logp + logpy = torch.gather(logp, 2, labels.unsqueeze(2)).squeeze(-1) + return logpy + + +def whiten(values: torch.Tensor, shift_mean: bool = True) -> torch.Tensor: + """Whiten values.""" + mean, var = torch.mean(values), torch.var(values) + whitened = (values - mean) * torch.rsqrt(var + 1e-8) + if not shift_mean: + whitened += mean + return whitened + + +def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: Optional[bool] = None) -> torch.Tensor: + """Compute mean of tensor with a masked values.""" + if axis is not None: + return (values * mask).sum(axis=axis) / mask.sum(axis=axis) + else: + return (values * mask).sum() / mask.sum() + + +def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor: + """Compute variance of tensor with masked values.""" + mean = masked_mean(values, mask) + centered_values = values - mean + variance = masked_mean(centered_values**2, mask) + if unbiased: + mask_sum = mask.sum() + if mask_sum == 0: + raise ValueError( + "The sum of the mask is zero, which can happen when `mini_batch_size=1`;" + "try increase the `mini_batch_size` or `gradient_accumulation_steps`" + ) + # note that if mask_sum == 1, then there is a division by zero issue + # to avoid it you just need to use a larger minibatch_size + bessel_correction = mask_sum / (mask_sum - 1) + variance = variance * bessel_correction + return variance + + +def masked_whiten(values: torch.Tensor, mask: torch.Tensor, shift_mean: bool = True) -> torch.Tensor: + """Whiten values with masked values.""" + mean, var = masked_mean(values, mask), masked_var(values, mask) + whitened = (values - mean) * torch.rsqrt(var + 1e-8) + if not shift_mean: + whitened += mean + return whitened + + +def clip_by_value(x: torch.Tensor, tensor_min: float, tensor_max: float) -> torch.Tensor: + """ + Tensor extension to torch.clamp + https://github.com/pytorch/pytorch/issues/2793#issuecomment-428784713 + """ + clipped = torch.max(torch.min(x, tensor_max), tensor_min) + return clipped + + +def entropy_from_logits(logits: torch.Tensor) -> torch.Tensor: + """Calculate entropy from logits.""" + pd = torch.nn.functional.softmax(logits, dim=-1) + entropy = torch.logsumexp(logits, axis=-1) - torch.sum(pd * logits, axis=-1) + return entropy + + +def stats_to_np(stats_dict: Dict) -> Dict: + """Cast all torch.tensors in dict to numpy arrays.""" + new_dict = dict() + for k, v in stats_dict.items(): + if isinstance(v, torch.Tensor): + new_dict[k] = v.detach().cpu() + if new_dict[k].dtype == torch.bfloat16: + new_dict[k] = new_dict[k].float() + new_dict[k] = new_dict[k].numpy() + else: + new_dict[k] = v + if np.isscalar(new_dict[k]): + new_dict[k] = float(new_dict[k]) + return new_dict + + +def respond_to_batch( + model: nn.Module, queries: List[torch.LongTensor], txt_len: int = 20, top_k: int = 0, top_p: float = 1.0 +) -> torch.LongTensor: + """Sample text from language model.""" + input_ids = queries + for _i in range(txt_len): + # Get Logits + outputs = model(input_ids) + next_token_logits = outputs[0][:, -1, :] + next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p) + # Sample + probs = F.softmax(next_token_logits, dim=-1) + next_token = torch.multinomial(probs, num_samples=1).squeeze(1) + input_ids = torch.cat([input_ids, next_token.unsqueeze(-1)], dim=-1) + return input_ids[:, -txt_len:] + + +def set_seed(seed: int) -> None: + """ + Helper function for reproducible behavior to set the seed in `random`, `numpy`, and `torch`. + + Args: + seed (`int`): The seed to set. + """ + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if is_torch_xpu_available(): + torch.xpu.manual_seed_all(seed) + elif is_torch_npu_available(): + torch.npu.manual_seed_all(seed) + else: + torch.cuda.manual_seed_all(seed) + + +class LengthSampler: + """ + Samples a length + """ + + def __init__(self, min_value: int, max_value: int): + self.values = list(range(min_value, max_value)) + + def __call__(self) -> int: + return np.random.choice(self.values) + + +class PPODecorators: + optimize_device_cache = False + + @classmethod + @contextmanager + def empty_device_cache(cls): + yield + if cls.optimize_device_cache: + if is_torch_xpu_available(): + gc.collect() + torch.xpu.empty_cache() + gc.collect() + elif is_torch_npu_available(): + gc.collect() + torch.npu.empty_cache() + gc.collect() + elif torch.cuda.is_available(): + gc.collect() + torch.cuda.empty_cache() + gc.collect() + + +def randn_tensor( + shape: Union[Tuple, List], + generator: Optional[Union[List[torch.Generator], torch.Generator]] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + layout: Optional[torch.layout] = None, +) -> torch.Tensor: + """A helper function to create random tensors on the desired `device` with the desired `dtype`. When + passing a list of generators, you can seed each batch size individually. If CPU generators are passed, the tensor + is always created on the CPU. + """ + # device on which tensor is created defaults to device + rand_device = device + batch_size = shape[0] + + layout = layout or torch.strided + device = device or torch.device("cpu") + + if generator is not None: + gen_device_type = generator.device.type if not isinstance(generator, list) else generator[0].device.type + if gen_device_type != device.type and gen_device_type == "cpu": + rand_device = "cpu" + if device != "mps": + warnings.warn( + f"The passed generator was created on 'cpu' even though a tensor on {device} was expected." + f" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably" + f" slighly speed up this function by passing a generator that was created on the {device} device." + ) + elif gen_device_type != device.type and gen_device_type == "cuda": + raise ValueError(f"Cannot generate a {device} tensor from a generator of type {gen_device_type}.") + + # make sure generator list of length 1 is treated like a non-list + if isinstance(generator, list) and len(generator) == 1: + generator = generator[0] + + if isinstance(generator, list): + shape = (1,) + shape[1:] + latents = [ + torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype, layout=layout) + for i in range(batch_size) + ] + latents = torch.cat(latents, dim=0).to(device) + else: + latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype, layout=layout).to(device) + + return latents diff --git a/testbed/huggingface__trl/trl/data_utils.py b/testbed/huggingface__trl/trl/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..146466bd6bfe3e49be74f43a39d5bb24f4dfede4 --- /dev/null +++ b/testbed/huggingface__trl/trl/data_utils.py @@ -0,0 +1,399 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Dict, List, Optional, Sequence, TypeVar + +from datasets import Dataset, DatasetDict +from transformers import PreTrainedTokenizer + + +DatasetType = TypeVar("DatasetType", Dataset, DatasetDict) + + +def is_conversational(example: Dict[str, Any]) -> bool: + r""" + Check if the example is in a conversational format. + + Args: + example (`Dict[str, Any]`): + A single data entry of a dataset. The example can have different keys depending on the + dataset type. + + Returns: + `bool`: `True` if the data is in a conversational format, `False` otherwise. + + Examples: + + ```python + >>> example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]} + >>> is_conversational(example) + True + >>> example = {"prompt": "The sky is"}) + >>> is_conversational(example) + False + ``` + """ + supported_keys = ["prompt", "chosen", "rejected", "completion", "messages"] + example_keys = {key for key in example.keys() if key in supported_keys} + + # It must have one of the supported keys + if example_keys: + key = example_keys.pop() # take the first supported key + maybe_messages = example[key] + # It must be a list of messages, + if isinstance(maybe_messages, list): + maybe_message = maybe_messages[0] + # Each message must a list of dictionaries with keys "role" and "content" + if isinstance(maybe_message, dict) and "role" in maybe_message and "content" in maybe_message: + return True + + return False + + +def apply_chat_template(example: Dict[str, List[Dict[str, str]]], tokenizer: PreTrainedTokenizer) -> Dict[str, str]: + r""" + Apply a chat template to a conversational example. + + For more details, see [`maybe_apply_chat_template`]. + """ + # Check that the example has the correct keys + supported_keys = ["prompt", "chosen", "rejected", "completion", "messages", "label"] + example_keys = {key for key in example.keys() if key in supported_keys} + if example_keys not in [ + {"messages"}, # language modeling + {"prompt"}, # prompt-only + {"prompt", "completion"}, # prompt-completion + {"prompt", "chosen", "rejected"}, # preference + {"chosen", "rejected"}, # preference with implicit prompt + {"prompt", "completion", "label"}, # unpaired preference + ]: + raise KeyError(f"Invalid keys in the example: {example_keys}") + + # Apply the chat template to the whole conversation + if "messages" in example: + messages = tokenizer.apply_chat_template(example["messages"], tokenize=False) + + # Apply the chat template to the prompt, adding the generation prompt + if "prompt" in example: + prompt = tokenizer.apply_chat_template(example["prompt"], tokenize=False, add_generation_prompt=True) + + # Apply the chat template to the entire prompt + completion + if "prompt" in example: # explicit prompt and prompt-completion case + if "chosen" in example: + prompt_chosen = tokenizer.apply_chat_template(example["prompt"] + example["chosen"], tokenize=False) + chosen = prompt_chosen[len(prompt) :] + if "rejected" in example and "prompt" in example: # explicit prompt + prompt_rejected = tokenizer.apply_chat_template(example["prompt"] + example["rejected"], tokenize=False) + rejected = prompt_rejected[len(prompt) :] + if "completion" in example: + prompt_completion = tokenizer.apply_chat_template( + example["prompt"] + example["completion"], tokenize=False + ) + completion = prompt_completion[len(prompt) :] + else: # implicit prompt case + if "chosen" in example: + chosen = tokenizer.apply_chat_template(example["chosen"], tokenize=False) + if "rejected" in example: + rejected = tokenizer.apply_chat_template(example["rejected"], tokenize=False) + + # Ensure that the prompt is the initial part of the prompt-completion string + if "prompt" in example: + error_message = ( + "The chat template applied to the prompt + completion does not start with the chat template applied to " + "the prompt alone. This can indicate that the chat template is not supported by TRL." + "\n**Prompt**:\n{}\n\n**Prompt + Completion**:\n{}" + ) + if "chosen" in example and not prompt_chosen.startswith(prompt): + raise ValueError(error_message.format(prompt, prompt_chosen)) + if "rejected" in example and not prompt_rejected.startswith(prompt): + raise ValueError(error_message.format(prompt, prompt_rejected)) + if "completion" in example and not prompt_completion.startswith(prompt): + raise ValueError(error_message.format(prompt, prompt_completion)) + + # Extract the completion by removing the prompt part from the prompt-completion string + output = {} + if "messages" in example: + output["text"] = messages + if "prompt" in example: + output["prompt"] = prompt + if "chosen" in example: + output["chosen"] = chosen + if "rejected" in example: + output["rejected"] = rejected + if "completion" in example: + output["completion"] = completion + if "label" in example: + output["label"] = example["label"] + + return output + + +def maybe_apply_chat_template( + example: Dict[str, List[Dict[str, str]]], tokenizer: PreTrainedTokenizer +) -> Dict[str, str]: + r""" + If the example is in a conversational format, apply a chat template to it. + + Args: + example (`Dict[str, List[Dict[str, str]]`): + Dictionary representing a single data entry of a conversational dataset. Each data entry can have different + keys depending on the dataset type. The supported dataset types are: + + - Language modeling dataset: `"messages"`. + - Prompt-only dataset: `"prompt"`. + - Prompt-completion dataset: `"prompt"` and `"completion"`. + - Preference dataset: `"prompt"`, `"chosen"`, and `"rejected"`. + - Preference dataset with implicit prompt: `"chosen"` and `"rejected"`. + - Unpaired preference dataset: `"prompt"`, `"completion"`, and `"label"`. + + For keys `"messages"`, `"prompt"`, `"chosen"`, `"rejected"`, and `"completion"`, the values are lists of + messages, where each message is a dictionary with keys `"role"` and `"content"`. + + tokenizer (`PreTrainedTokenizer`): + The tokenizer to apply the chat template with. + + Returns: + `Dict[str, str]`: The formatted example with the chat template applied. + + Note: + This function does not alter the keys, except for Language modeling dataset, where `"messages"` is replaced by + `"text"`. + + Example: + + ```python + >>> from transformers import AutoTokenizer + >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct") + >>> example = { + ... "prompt": [{"role": "user", "content": "What color is the sky?"}], + ... "completion": [{"role": "assistant", "content": "It is blue."}] + ... } + >>> apply_chat_template(example, tokenizer) + {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n', 'completion': 'It is blue.<|end|>\n<|endoftext|>'} + ``` + """ + if is_conversational(example): + return apply_chat_template(example, tokenizer) + else: + return example + + +def _unpair_row(examples: List[Dict[str, List[Dict[str, str]]]]) -> List[Dict[str, List[Dict[str, str]]]]: + batch_size = len(examples["chosen"]) + new_rows = { + "completion": examples["chosen"] + examples["rejected"], + "label": [True] * batch_size + [False] * batch_size, + } + if "prompt" in examples: + new_rows["prompt"] = examples["prompt"] + examples["prompt"] + return new_rows + + +def unpair_preference_dataset( + dataset: DatasetType, num_proc: Optional[int] = None, desc: Optional[str] = None +) -> DatasetType: + r""" + Unpair a preference dataset. + + Args: + dataset (`Dataset` or `DatasetDict`): + Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally + `"prompt"`. + num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + desc (`str` or `None`, *optional*, defaults to `None`): + Meaningful description to be displayed alongside with the progress bar while mapping examples. + + Returns: + `Dataset`: The unpaired preference dataset. + + Example: + + ```python + >>> from datasets import Dataset + >>> dataset_dict = { + ... "prompt": ["The sky is", "The sun is"] + ... "chosen": [" blue.", "in the sky."], + ... "rejected": [" green.", " in the sea."] + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = unpair_preference_dataset(dataset) + >>> dataset + Dataset({ + features: ['prompt', 'completion', 'label'], + num_rows: 4 + }) + >>> dataset[0] + {'prompt': 'The sky is', 'completion': ' blue.', 'label': True} + ``` + """ + return dataset.map(_unpair_row, batched=True, remove_columns=["chosen", "rejected"], num_proc=num_proc, desc=desc) + + +def maybe_unpair_preference_dataset( + dataset: DatasetType, num_proc: Optional[int] = None, desc: Optional[str] = None +) -> DatasetType: + r""" + Unpair a preference dataset if it is paired. + + Args: + dataset (`Dataset` or `DatasetDict`): + Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and optionally + `"prompt"`. + num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + desc (`str` or `None`, *optional*, defaults to `None`): + Meaningful description to be displayed alongside with the progress bar while mapping examples. + + Returns: + `Dataset` or `DatasetDict`: The unpaired preference dataset if it was paired, otherwise the original dataset. + + Example: + + ```python + >>> from datasets import Dataset + >>> dataset_dict = { + ... "prompt": ["The sky is", "The sun is"] + ... "chosen": [" blue.", "in the sky."], + ... "rejected": [" green.", " in the sea."] + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = unpair_preference_dataset(dataset) + >>> dataset + Dataset({ + features: ['prompt', 'completion', 'label'], + num_rows: 4 + }) + >>> dataset[0] + {'prompt': 'The sky is', 'completion': ' blue.', 'label': True} + ``` + """ + if isinstance(dataset, DatasetDict): + column_names = dataset[list(dataset.keys())[0]].column_names + else: + column_names = dataset.column_names + if "chosen" in column_names and "rejected" in column_names: + return unpair_preference_dataset(dataset, num_proc=num_proc, desc=desc) + else: + return dataset + + +def extract_prompt(example: Dict[str, Sequence]) -> Dict[str, Sequence]: + r""" + Extracts the shared prompt from a preference data example, where the prompt is implicit within both + the chosen and rejected completions. + + For more details, see [`maybe_extract_prompt`]. + """ + for idx in range(min(len(example["chosen"]), len(example["rejected"]))): + if example["chosen"][idx] != example["rejected"][idx]: + if example["chosen"][idx - 1] == " ": # remove space before the prompt + idx -= 1 + break + return { + "prompt": example["chosen"][:idx], + "chosen": example["chosen"][idx:], + "rejected": example["rejected"][idx:], + } + + +def maybe_extract_prompt(example: Dict[str, List]) -> Dict[str, List]: + r""" + Extracts the shared prompt from a preference data example, where the prompt is implicit within both + the chosen and rejected completions. + + If the example already contains a `"prompt"` key, the function returns the example as is. Else, the function + identifies the longest common sequence (prefix) of conversation turns between the "chosen" and "rejected" + completions and extracts this as the prompt. It then removes this prompt from the respective "chosen" and + "rejected" completions. + + Args: + example (`Dict[str, List]`): + A dictionary representing a single data entry in the preference dataset. It must contain the keys + `"chosen"` and `"rejected"`, where each value is either conversational or standard (`str`). + + Returns: + `Dict[str, List]`: A dictionary containing: + - `"prompt"`: The longest common prefix between the "chosen" and "rejected" completions. + - `"chosen"`: The remainder of the "chosen" completion, with the prompt removed. + - `"rejected"`: The remainder of the "rejected" completion, with the prompt removed. + + Examples: + + ```python + >>> example = { + ... "chosen": [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is blue."} + ... ], + ... "rejected": [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is green."} + ... ] + ... } + >>> extract_prompt(example) + {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} + ``` + + Or, with the `map` method of `datasets.Dataset`: + + ```python + >>> from trl import extract_prompt + >>> from datasets import Dataset + >>> dataset_dict = { + ... "chosen": [ + ... [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is blue."}, + ... ], + ... [ + ... {"role": "user", "content": "Where is the sun?"}, + ... {"role": "assistant", "content": "In the sky."}, + ... ], + ... ], + ... "rejected": [ + ... [ + ... {"role": "user", "content": "What color is the sky?"}, + ... {"role": "assistant", "content": "It is green."}, + ... ], + ... [ + ... {"role": "user", "content": "Where is the sun?"}, + ... {"role": "assistant", "content": "In the sea."}, + ... ], + ... ], + ... } + >>> dataset = Dataset.from_dict(dataset_dict) + >>> dataset = dataset.map(extract_prompt) + >>> dataset[0] + {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], + 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}], + 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]} + ``` + """ + # Some dataset add a `"prompt"` column, even though the prompt is implicit and included in the "chosen" and + # "rejected" completions. E.g.: + # {"prompt": "What color is the sky?", + # "chosen": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}], + # "rejected": [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}]} + # That's why we check if the prompt is also conversational before deciding not to extract it. + if "chosen" not in example or "rejected" not in example: # not a preference example + return example + if "prompt" in example: + # Both conversational or both non-conversational + chosen_conv = is_conversational({"chosen": example["chosen"]}) + prompt_conv = is_conversational({"prompt": example["prompt"]}) + if (chosen_conv and prompt_conv) or (not chosen_conv and not prompt_conv): + return example + return extract_prompt({"chosen": example["chosen"], "rejected": example["rejected"]}) diff --git a/testbed/huggingface__trl/trl/env_utils.py b/testbed/huggingface__trl/trl/env_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..64e98199e0268bdc479053dafc0ff93e26db1e48 --- /dev/null +++ b/testbed/huggingface__trl/trl/env_utils.py @@ -0,0 +1,34 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Function `strtobool` copied and adapted from `distutils` (as deprected +# in Python 3.10). +# Reference: https://github.com/python/cpython/blob/48f9d3e3faec5faaa4f7c9849fecd27eae4da213/Lib/distutils/util.py#L308-L321 + + +def strtobool(val: str) -> bool: + """Convert a string representation of truth to True or False booleans. + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. + + Raises: + ValueError: if 'val' is anything else. + """ + val = val.lower() + if val in ("y", "yes", "t", "true", "on", "1"): + return True + if val in ("n", "no", "f", "false", "off", "0"): + return False + raise ValueError(f"Invalid truth value, it should be a string but {val} was provided instead.") diff --git a/testbed/huggingface__trl/trl/environment/__init__.py b/testbed/huggingface__trl/trl/environment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a39d747eab2f68569625384402b6c27b4206c4 --- /dev/null +++ b/testbed/huggingface__trl/trl/environment/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from ..import_utils import _LazyModule + + +_import_structure = { + "base_environment": ["TextEnvironment", "TextHistory"], +} + +if TYPE_CHECKING: + from .base_environment import TextEnvironment, TextHistory +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/testbed/huggingface__trl/trl/environment/base_environment.py b/testbed/huggingface__trl/trl/environment/base_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c5658d2d991e4b86e598626530c6012f15c425 --- /dev/null +++ b/testbed/huggingface__trl/trl/environment/base_environment.py @@ -0,0 +1,474 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +import warnings +from typing import Optional + +import torch +from accelerate.utils import extract_model_from_parallel +from transformers import StoppingCriteria, StoppingCriteriaList + +from ..import_utils import is_rich_available + + +if is_rich_available(): + from rich import print + from rich.text import Text + + +class StringStoppingCriteria(StoppingCriteria): + """Custom `StoppingCriteria` which checks if all generations in the batch are completed.""" + + def __init__(self, stop_strings, tokenizer): + self.stop_strings = stop_strings + self.tokenizer = tokenizer + self.first_call = True + + def __call__(self, input_ids, scores, **kwargs): + """Returns true if all generated sequences contain any of the stop strings.""" + if self.first_call: + self.generated_tokens = [1 for _ in range(input_ids.shape[0])] + self.start_length = input_ids.shape[-1] - 1 + self.first_call = False + decoded_generations = self.tokenizer.batch_decode(input_ids[:, self.start_length :]) + done = [] + + for i, decoded_generation in enumerate(decoded_generations): + sequence_complete = any(stop_string in decoded_generation for stop_string in self.stop_strings) + done.append(sequence_complete) + if not sequence_complete: + self.generated_tokens[i] += 1 + + if all(done): + self.first_call = True + + return all(done) + + +class TextHistory: + """The TextHistory class keeps track of the history of an interaction between the language model and the environment.""" + + def __init__(self, text, tokens, system=True): + """ + Initialize TextHistory. + + Args: + text (`str`): The text of the first segment. + tokens (`torch.LongTensor`): The tokens of the first segment. + system (`bool`, *optional*): Whether the first segment is a system or user segment. + """ + self.system_spans = [] + self.text_spans = [] + self.token_spans = [] + self.token_masks = torch.tensor([], dtype=torch.long).to(tokens.device) + self.text = "" + self.tokens = torch.tensor([], dtype=torch.long).to(tokens.device) + self.completed = False + self.truncated = False + self.reward = 0.0 + + self.prompt_color = "black on grey85" + self.system_color = "black on cyan3" + self.model_color = "black on deep_sky_blue1" + self.reward_color = "black on plum1" + + self.append_segment(text, tokens, system=system) + + def append_segment(self, text, tokens, system=True): + """ + Append a new segment to the history. + + Args: + text (`str`): The text of the new segment. + tokens (`torch.LongTensor`): The tokens of the new segment. + system (`bool`, *optional*): Whether the new segment is a system or user segment. + """ + + if len(text) == 0 or len(tokens) == 0: + raise ValueError("Can't append empty text or token list to history.") + + original_text_length = len(self.text) + + self.text += text + self.text_spans.append((original_text_length, len(self.text))) + self.system_spans.append(system) + + original_token_length = len(self.tokens) + + self.tokens = torch.cat((self.tokens, tokens)) + if system: + self.token_masks = torch.cat((self.token_masks, torch.zeros_like(tokens))) + else: + self.token_masks = torch.cat((self.token_masks, torch.ones_like(tokens))) + self.token_spans.append((original_token_length, len(self.tokens))) + + def complete(self, truncated=False): + """ + Mark the history as completed. + """ + self.completed = True + self.truncated = truncated + + @property + def last_text_segment(self): + """ + Get the last text segment. + """ + start, end = self.text_spans[-1] + return self.text[start:end] + + def split_query_response_tokens(self): + """ + Split the tokens into query and response tokens. + """ + split_index = self.token_spans[0][1] + query = self.tokens[:split_index] + response = self.tokens[split_index:] + mask = self.token_masks[split_index:] + + return query, response, mask + + def show_text(self, show_legend=False): + """ + Print the text history. + """ + if not is_rich_available(): + warnings.warn("install rich to display text") + return + + text = Text(self.text) + text.stylize(self.prompt_color, self.text_spans[0][0], self.text_spans[1][0]) + for i, (start, end) in enumerate(self.text_spans[1:]): + if self.system_spans[i + 1]: + text.stylize(self.system_color, start, end) + else: + text.stylize(self.model_color, start, end) + + text.append(f"\n\nReward: {self.reward}", style=self.reward_color) + print(text) + + if show_legend: + self.show_colour_legend() + + def show_tokens(self, tokenizer, show_legend=False): + """ + Print the history tokens. + """ + if not is_rich_available(): + warnings.warn("install rich to display tokens") + return + + text = Text() + prompt_end = self.token_spans[0][1] + for i, (token, mask) in enumerate(zip(self.tokens, self.token_masks)): + if i < prompt_end: + text.append(tokenizer.convert_ids_to_tokens(token.item()), style=self.prompt_color) + text.append(" ") + elif mask == 0: + text.append(tokenizer.convert_ids_to_tokens(token.item()), style=self.system_color) + text.append(" ") + else: + text.append(tokenizer.convert_ids_to_tokens(token.item()), style=self.model_color) + text.append(" ") + text.append(f"\n\nReward: {self.reward}", style=self.reward_color) + print(text) + if show_legend: + self.show_colour_legend() + + def show_colour_legend(self): + """ + Print the colour legend. + """ + if not is_rich_available(): + warnings.warn("install rich to display colour legend") + return + text = Text("\n\n(Colour Legend: ") + text.append("Prompt", style=self.prompt_color) + text.append("|") + text.append("System", style=self.system_color) + text.append("|") + text.append("Model", style=self.model_color) + text.append("|") + text.append("Reward", style=self.reward_color) + text.append(")") + print(text) + + +class TextEnvironment: + """ + The TextEnvironment enables interaction of a LLM with an environment using tools. + """ + + def __init__( + self, + model=None, + tokenizer=None, + tools=None, + reward_fn=None, + prompt=None, + max_turns=4, + max_tool_reponse=100, + max_length=None, + generation_kwargs=None, + ): + """ + Initialize TextEnvironment. + + Args: + model (`PreTrainedModelWrapper`): The model to use for generation. + tokenizer (`transformers.PreTrainedTokenizer`): The tokenizer to use for generation. + tools (list): A list of tools to use for interaction. + reward_fn (function): A function that takes a string and returns a reward. + prompt (str): The base prompt to use for generation. Is prepended to the tasks. + max_turns (Optional[int]): The maximum number of turns to allow. + max_tool_response (Optional[int]): The maximum number of characters to allow in a tool response. + max_length (Optional[int]): The maximum number of tokens to allow in an episode. + generation_kwargs (Optional[dict]): A dictionary of keyword arguments to pass to the model's generate method. + """ + self.model = model + self.tokenizer = tokenizer + self.prompt = prompt + if isinstance(tools, dict): + self.tools = tools + else: + self.tools = {tool.__class__.__name__: tool for tool in tools} + self.reward_fn = reward_fn + self.max_length = max_length + self.request_token = "" + self.call_token = "" + self.response_token = "" + self.submit_token = "" + self.max_turns = max_turns + self.max_tool_response = max_tool_reponse + + if generation_kwargs is None: + self.generation_kwargs = dict() + else: + self.generation_kwargs = generation_kwargs + + self.is_encoder_decoder = hasattr(self.model, "is_encoder_decoder") + self.current_device = extract_model_from_parallel(self.model).pretrained_model.device + + def run(self, queries, **rewards_kwargs): + """ + Run the environment on a list of queries. + + Args: + queries (list[str]): A list of queries to run the model in the environment on. + """ + turns = 0 + + queries = [self.prompt + task for task in queries] + queries_tokens = [ + self.tokenizer(query, return_tensors="pt").input_ids[0].to(self.model.pretrained_model.device) + for query in queries + ] + + histories = [TextHistory(q, qt, system=True) for q, qt in zip(queries, queries_tokens)] + + while any(not history.completed for history in histories) and turns < self.max_turns: + histories = self.generate(histories) + histories = self.tasks_end_check(histories) + # TODO: make this parallel rather than for-loop + for i in range(len(histories)): + histories[i] = self.step(histories[i]) + histories = self.tasks_end_check(histories, model_turn=False) + turns += 1 + self.compute_reward(histories, **rewards_kwargs) + + # convert a list of (q, r, m) tuples to lists of all qs, rs, and ms respectively + queries, responses, masks = map(list, zip(*[history.split_query_response_tokens() for history in histories])) + + rewards = [history.reward for history in histories] + return queries, responses, masks, rewards, histories + + def step(self, history): + """ + Step the environment forward one turn. + + Args: + history (`TextHistory`): The history to step forward. + """ + truncated, ended = self.task_end_check(history) + if ended: + history.complete(truncated=truncated) + if history.completed: + return history + + tool, query = self.parse_tool_call(history.last_text_segment) + if tool is None or query is None: + response = f"Unknown tool call: {history.last_text_segment}" + else: + if tool not in self.tools: + response = f"Unknown tool {tool}." + try: + response = self.tools[tool](query) + except Exception as error: + response = f"Tool error: {str(error)}" + + if len(response) > self.max_tool_response: + response = response[: (self.max_tool_response - 3)] + "..." + + history.append_segment( + response + self.response_token, + self.tokenizer(response + self.response_token, return_tensors="pt") + .input_ids[0] + .to(self.model.pretrained_model.device), + system=True, + ) + + return history + + def parse_tool_call(self, text): + """ + Parse request string. Expected format: query + """ + result = re.search(f"(?<={self.request_token}).*?(?={self.call_token})", text, re.DOTALL) + + # if we can't find a / span we return none + if result is None: + return None, None + else: + extracted_text = result.group() + + result = re.search(r"<(.*?)>", extracted_text) + + # if we can't find a tool name we return none + if result is None: + return None, None + else: + tool = result.group(1) + + # split off the tool name + query = ">".join(extracted_text.split(">")[1:]) + + return tool, query + + def compute_reward(self, histories, **reward_kwargs): + """ + Compute the reward for a list of histories. + """ + rewards = self.reward_fn([history.last_text_segment for history in histories], **reward_kwargs) + for history, reward in zip(histories, rewards): + history.reward = reward + return histories + + def generate(self, histories): + """ + Generate responses for a list of histories. + """ + active_histories = [i for i, history in enumerate(histories) if not history.completed] + + query_tensors = [histories[i].tokens for i in active_histories] + response_tensors = self._generate_batched(query_tensors) + response_texts = self.tokenizer.batch_decode(response_tensors) + + for i, response_text, response_tensor in zip(active_histories, response_texts, response_tensors): + histories[i].append_segment(response_text, response_tensor, system=False) + + return histories + + def tasks_end_check(self, histories, model_turn=True): + """ + Check if the current generation sequences have finished. + """ + for history in histories: + if not history.completed: + truncated, ended = self.task_end_check(history, model_turn=model_turn) + if ended: + history.complete(truncated=truncated) + return histories + + def task_end_check(self, history, model_turn=True): + """ + Check if the current generation sequence has finished. + """ + truncated = False + ended = False + if history.completed: + return truncated, ended + if self.max_length is not None and len(self.tokenizer(history.text).input_ids[0]) > self.max_length: + truncated = True + ended = True + elif self.tokenizer.eos_token in history.text: + ended = True + elif model_turn and not ( + (self.request_token in history.last_text_segment and self.call_token in history.last_text_segment) + or self.submit_token in history.last_text_segment + ): + ended = True + elif self.submit_token in history.last_text_segment: + ended = True + return truncated, ended + + def _generate_batched( + self, + query_tensors, + batch_size: int = 16, + pad_to_multiple_of: Optional[int] = None, + ): + """ + Generate responses for a list of query tensors. + + Args: + query_tensors (list[torch.Tensor]): A list of query tensors to generate responses for. + batch_size (int): The batch size to use for generation. + pad_to_multiple_of (int): The padding length to use for generation. + """ + outputs = [] + padding_side_default = self.tokenizer.padding_side + if not self.is_encoder_decoder: + self.tokenizer.padding_side = "left" + + # in case we have fewer examples than bs + batch_size = min(len(query_tensors), batch_size) + + for i in range(0, len(query_tensors), batch_size): + # prevent overflow if query tensors are not even multiple of bs + end_index = min(len(query_tensors), i + batch_size) + + batch = query_tensors[i:end_index] + batch_mask = [torch.ones_like(element) for element in batch] + inputs = {"input_ids": batch, "attention_mask": batch_mask} + + padded_inputs = self.tokenizer.pad( + inputs, + padding=True, + max_length=None, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ).to(self.current_device) + + stopping_criteria = StringStoppingCriteria([self.call_token, self.submit_token], self.tokenizer) + + self.generation_kwargs["stopping_criteria"] = StoppingCriteriaList([stopping_criteria]) + + generations = extract_model_from_parallel(self.model).generate(**padded_inputs, **self.generation_kwargs) + + for generation, mask, generated_tokens in zip( + generations, padded_inputs["attention_mask"], stopping_criteria.generated_tokens + ): + if not self.is_encoder_decoder: + output = generation[(1 - mask).sum() :] # remove padding + else: + output = generation + + if not self.is_encoder_decoder: + output = output[(mask).sum() :] # remove prompt + + # remove chunk generated after stopping criteria in batch mode + outputs.append(output[:generated_tokens]) + self.tokenizer.padding_side = padding_side_default + return outputs diff --git a/testbed/huggingface__trl/trl/extras/__init__.py b/testbed/huggingface__trl/trl/extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..beedbd53f0a4fb0ea57228e839d34b6b1c7c10a4 --- /dev/null +++ b/testbed/huggingface__trl/trl/extras/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from ..import_utils import _LazyModule + + +_import_structure = { + "best_of_n_sampler": ["BestOfNSampler"], +} + +if TYPE_CHECKING: + from .best_of_n_sampler import BestOfNSampler +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/testbed/huggingface__trl/trl/extras/best_of_n_sampler.py b/testbed/huggingface__trl/trl/extras/best_of_n_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..5f3363f4c9933e2b75151618729d756bfda94ab8 --- /dev/null +++ b/testbed/huggingface__trl/trl/extras/best_of_n_sampler.py @@ -0,0 +1,131 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Callable, List, Optional, Union + +import torch +from transformers import GenerationConfig, PreTrainedTokenizer, PreTrainedTokenizerFast + +from ..core import set_seed +from ..models import SUPPORTED_ARCHITECTURES, PreTrainedModelWrapper + + +class BestOfNSampler: + def __init__( + self, + model: PreTrainedModelWrapper, + tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], + queries_to_scores: Callable[[List[str]], List[float]], + length_sampler: Any, + sample_size: int = 4, + seed: Optional[int] = None, + n_candidates: int = 1, + generation_config: Optional[GenerationConfig] = None, + ) -> None: + r""" + Initialize the sampler for best-of-n generation + + Args: + model (`PreTrainedModelWrapper`): + The pretrained model to use for generation + tokenizer (`PreTrainedTokenizer` or `PreTrainedTokenizerFast`): + Tokenizer associated with the pretrained model + queries_to_scores (`Callable[[List[str]], List[float]]`): + Callable that takes a list of generated texts and returns the associated reward scores + length_sampler (`Any`): + Sampler used to sample the length of the generated text + sample_size (`int`): + Number of samples to generate for each query + seed (`int`, *optional*): + Random seed used to control generation + n_candidates (`int`): + Number of candidates to return for each query + generation_config (`GenerationConfig`, *optional*): + Generation config passed to the underlying model's `generate` method. + See `GenerationConfig` (https://huggingface.co/docs/transformers/v4.29.1/en/main_classes/text_generation#transformers.GenerationConfig) for more details + """ + if seed is not None: + set_seed(seed) + + if not isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)): + raise ValueError( + f"tokenizer must be a PreTrainedTokenizer or PreTrainedTokenizerFast, got {type(tokenizer)}" + ) + if not isinstance(model, (SUPPORTED_ARCHITECTURES)): + raise ValueError( + f"model must be a PreTrainedModelWrapper, got {type(model)} - supported architectures are: {SUPPORTED_ARCHITECTURES}" + ) + + self.model = model + self.tokenizer = tokenizer + + self.queries_to_scores = queries_to_scores + self.length_sampler = length_sampler + self.gen_config = generation_config + self.sample_size = sample_size + self.n_candidates = n_candidates + + def generate( + self, + tokenized_query: Union[List[int], torch.Tensor, List[torch.Tensor], List[List[int]]], + skip_special_tokens: bool = True, + device: Optional[Union[str, torch.device]] = None, + **generation_kwargs, + ) -> List[List[str]]: + r""" + Generate the best of n samples for input queries + + Args: + tokenized_query (`List[int]` or `torch.Tensor` or `List[torch.Tensor]` or `List[int]`): + represents either a single tokenized query (a single tensor or a list of integers) or a batch of tokenized queries (a list of tensors or a list of lists of integers) + skip_special_tokens (`bool`): + Whether to remove the special tokens from the output + device (`str` or `torch.device`, *optional*): + The device on which the model will be loaded + **generation_kwargs (`dict`, *optional*): + Additional keyword arguments passed along to the underlying model's `generate` method. + This is used to override generation config + + Returns: + List[List[str]]: A list of lists of generated texts + """ + queries = None + + if isinstance(tokenized_query, torch.Tensor) and tokenized_query.ndim == 1: + queries = tokenized_query.unsqueeze(0) + elif isinstance(tokenized_query, List): + element_type = type(tokenized_query[0]) + if element_type is int: + queries = torch.tensor(tokenized_query).unsqueeze(0) + elif element_type is torch.Tensor: + queries = [tensor.reshape((1, -1)) for tensor in tokenized_query] + else: + queries = [torch.tensor(query).reshape((1, -1)) for query in tokenized_query] + + result = [] + + for query in queries: + queries = query.repeat((self.sample_size, 1)) + output = self.model.generate( + queries.to(device), + max_new_tokens=self.length_sampler(), + generation_config=self.gen_config, + **generation_kwargs, + ).squeeze() + output = self.tokenizer.batch_decode(output, skip_special_tokens=skip_special_tokens) + scores = torch.tensor(self.queries_to_scores(output)) + output = [output[i] for i in scores.topk(self.n_candidates).indices] + result.append(output) + + return result diff --git a/testbed/huggingface__trl/trl/extras/dataset_formatting.py b/testbed/huggingface__trl/trl/extras/dataset_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..d84db4b49e264b841aeb5399956c284366e333b6 --- /dev/null +++ b/testbed/huggingface__trl/trl/extras/dataset_formatting.py @@ -0,0 +1,102 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +from typing import Callable, Literal, Optional, Union + +from datasets import Dataset, Value +from transformers import AutoTokenizer + +from ..trainer.utils import ConstantLengthDataset + + +FORMAT_MAPPING = { + "chatml": [{"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}], + "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)}, +} + + +def conversations_formatting_function(tokenizer: AutoTokenizer, messages_field: Literal["messages", "conversations"]): + r""" + return a callable function that takes in a "messages" dataset and returns a formatted dataset, based on the tokenizer + apply chat template to the dataset + """ + + def format_dataset(examples): + if isinstance(examples[messages_field][0], list): + output_texts = [] + for i in range(len(examples[messages_field])): + output_texts.append(tokenizer.apply_chat_template(examples[messages_field][i], tokenize=False)) + return output_texts + else: + return tokenizer.apply_chat_template(examples[messages_field], tokenize=False) + + return format_dataset + + +def instructions_formatting_function(tokenizer: AutoTokenizer): + r""" + return a callable function that takes in an "instructions" dataset and returns a formatted dataset, based on the tokenizer + apply chat template to the dataset + """ + + def format_dataset(examples): + if isinstance(examples["prompt"], list): + output_texts = [] + for i in range(len(examples["prompt"])): + converted_sample = [ + {"role": "user", "content": examples["prompt"][i]}, + {"role": "assistant", "content": examples["completion"][i]}, + ] + output_texts.append(tokenizer.apply_chat_template(converted_sample, tokenize=False)) + return output_texts + else: + converted_sample = [ + {"role": "user", "content": examples["prompt"]}, + {"role": "assistant", "content": examples["completion"]}, + ] + return tokenizer.apply_chat_template(converted_sample, tokenize=False) + + return format_dataset + + +def get_formatting_func_from_dataset( + dataset: Union[Dataset, ConstantLengthDataset], tokenizer: AutoTokenizer +) -> Optional[Callable]: + r""" + Finds the correct formatting function based on the dataset structure. Currently supported datasets are: + - `ChatML` with [{"role": str, "content": str}] + - `instruction` with [{"prompt": str, "completion": str}] + + Args: + dataset (Dataset): User dataset + tokenizer (AutoTokenizer): Tokenizer used for formatting + + Returns: + Callable: Formatting function if the dataset format is supported else None + """ + if isinstance(dataset, Dataset): + if "messages" in dataset.features: + if dataset.features["messages"] == FORMAT_MAPPING["chatml"]: + logging.info("Formatting dataset with chatml format") + return conversations_formatting_function(tokenizer, "messages") + if "conversations" in dataset.features: + if dataset.features["conversations"] == FORMAT_MAPPING["chatml"]: + logging.info("Formatting dataset with chatml format") + return conversations_formatting_function(tokenizer, "conversations") + elif dataset.features == FORMAT_MAPPING["instruction"]: + logging.info("Formatting dataset with instruction format") + return instructions_formatting_function(tokenizer) + + return None diff --git a/testbed/huggingface__trl/trl/import_utils.py b/testbed/huggingface__trl/trl/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..15560a8c28dcb35c67f05ee8ceff91bd7503a6d8 --- /dev/null +++ b/testbed/huggingface__trl/trl/import_utils.py @@ -0,0 +1,112 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import importlib +import os +from itertools import chain +from types import ModuleType +from typing import Any + +from transformers.utils.import_utils import _is_package_available + + +# Use same as transformers.utils.import_utils +_deepspeed_available = _is_package_available("deepspeed") +_diffusers_available = _is_package_available("diffusers") +_llm_blender_available = _is_package_available("llm_blender") +_rich_available = _is_package_available("rich") +_unsloth_available = _is_package_available("unsloth") + + +def is_deepspeed_available() -> bool: + return _deepspeed_available + + +def is_diffusers_available() -> bool: + return _diffusers_available + + +def is_llm_blender_available() -> bool: + return _llm_blender_available + + +def is_rich_available() -> bool: + return _rich_available + + +def is_unsloth_available() -> bool: + return _unsloth_available + + +class _LazyModule(ModuleType): + """ + Module class that surfaces all objects but only performs associated imports when the objects are requested. + """ + + # Very heavily inspired by optuna.integration._IntegrationModule + # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py + def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): + super().__init__(name) + self._modules = set(import_structure.keys()) + self._class_to_module = {} + for key, values in import_structure.items(): + for value in values: + self._class_to_module[value] = key + # Needed for autocompletion in an IDE + self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) + self.__file__ = module_file + self.__spec__ = module_spec + self.__path__ = [os.path.dirname(module_file)] + self._objects = {} if extra_objects is None else extra_objects + self._name = name + self._import_structure = import_structure + + # Needed for autocompletion in an IDE + def __dir__(self): + result = super().__dir__() + # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether + # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. + for attr in self.__all__: + if attr not in result: + result.append(attr) + return result + + def __getattr__(self, name: str) -> Any: + if name in self._objects: + return self._objects[name] + if name in self._modules: + value = self._get_module(name) + elif name in self._class_to_module.keys(): + module = self._get_module(self._class_to_module[name]) + value = getattr(module, name) + else: + raise AttributeError(f"module {self.__name__} has no attribute {name}") + + setattr(self, name, value) + return value + + def _get_module(self, module_name: str): + try: + return importlib.import_module("." + module_name, self.__name__) + except Exception as e: + raise RuntimeError( + f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" + f" traceback):\n{e}" + ) from e + + def __reduce__(self): + return (self.__class__, (self._name, self.__file__, self._import_structure)) + + +class OptionalDependencyNotAvailable(BaseException): + """Internally used error class for signalling an optional dependency was not found.""" diff --git a/testbed/huggingface__trl/trl/models/__init__.py b/testbed/huggingface__trl/trl/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4cbfc0a51148000f39fb27094839e388eac2f26f --- /dev/null +++ b/testbed/huggingface__trl/trl/models/__init__.py @@ -0,0 +1,59 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import TYPE_CHECKING + +from ..import_utils import OptionalDependencyNotAvailable, _LazyModule, is_diffusers_available + + +_import_structure = { + "modeling_base": ["GeometricMixtureWrapper", "PreTrainedModelWrapper", "create_reference_model"], + "modeling_value_head": ["AutoModelForCausalLMWithValueHead", "AutoModelForSeq2SeqLMWithValueHead"], + "utils": ["SUPPORTED_ARCHITECTURES", "setup_chat_format", "unwrap_model_for_generation"], +} + +try: + if not is_diffusers_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_sd_base"] = [ + "DDPOPipelineOutput", + "DDPOSchedulerOutput", + "DDPOStableDiffusionPipeline", + "DefaultDDPOStableDiffusionPipeline", + ] + +if TYPE_CHECKING: + from .modeling_base import GeometricMixtureWrapper, PreTrainedModelWrapper, create_reference_model + from .modeling_value_head import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead + from .utils import SUPPORTED_ARCHITECTURES, setup_chat_format, unwrap_model_for_generation + + try: + if not is_diffusers_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_sd_base import ( + DDPOPipelineOutput, + DDPOSchedulerOutput, + DDPOStableDiffusionPipeline, + DefaultDDPOStableDiffusionPipeline, + ) +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/testbed/huggingface__trl/trl/models/auxiliary_modules.py b/testbed/huggingface__trl/trl/models/auxiliary_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..98c400c7ccfaa95f25181593dcc145ca035ee8bb --- /dev/null +++ b/testbed/huggingface__trl/trl/models/auxiliary_modules.py @@ -0,0 +1,95 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os + +import torch +import torch.nn as nn +import torchvision +from huggingface_hub import hf_hub_download +from huggingface_hub.utils import EntryNotFoundError +from transformers import CLIPModel, is_torch_npu_available, is_torch_xpu_available + + +class MLP(nn.Module): + def __init__(self): + super().__init__() + self.layers = nn.Sequential( + nn.Linear(768, 1024), + nn.Dropout(0.2), + nn.Linear(1024, 128), + nn.Dropout(0.2), + nn.Linear(128, 64), + nn.Dropout(0.1), + nn.Linear(64, 16), + nn.Linear(16, 1), + ) + + def forward(self, embed): + return self.layers(embed) + + +class AestheticScorer(torch.nn.Module): + """ + This model attempts to predict the aesthetic score of an image. The aesthetic score + is a numerical approximation of how much a specific image is liked by humans on average. + This is from https://github.com/christophschuhmann/improved-aesthetic-predictor + """ + + def __init__(self, *, dtype, model_id, model_filename): + super().__init__() + self.clip = CLIPModel.from_pretrained("openai/clip-vit-large-patch14") + self.normalize = torchvision.transforms.Normalize( + mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711] + ) + self.target_size = 224 + self.mlp = MLP() + try: + cached_path = hf_hub_download(model_id, model_filename) + except EntryNotFoundError: + cached_path = os.path.join(model_id, model_filename) + state_dict = torch.load(cached_path, map_location=torch.device("cpu"), weights_only=True) + self.mlp.load_state_dict(state_dict) + self.dtype = dtype + self.eval() + + def __call__(self, images): + device = next(self.parameters()).device + images = torchvision.transforms.Resize(self.target_size)(images) + images = self.normalize(images).to(self.dtype).to(device) + embed = self.clip.get_image_features(pixel_values=images) + # normalize embedding + embed = embed / torch.linalg.vector_norm(embed, dim=-1, keepdim=True) + reward = self.mlp(embed).squeeze(1) + return reward + + +def aesthetic_scorer(hub_model_id, model_filename): + scorer = AestheticScorer( + model_id=hub_model_id, + model_filename=model_filename, + dtype=torch.float32, + ) + if is_torch_npu_available(): + scorer = scorer.npu() + elif is_torch_xpu_available(): + scorer = scorer.xpu() + else: + scorer = scorer.cuda() + + def _fn(images, prompts, metadata): + images = (images).clamp(0, 1) + scores = scorer(images) + return scores, {} + + return _fn diff --git a/testbed/huggingface__trl/trl/models/modeling_base.py b/testbed/huggingface__trl/trl/models/modeling_base.py new file mode 100644 index 0000000000000000000000000000000000000000..9db77d8089b1897575479a39eeef22f887c55292 --- /dev/null +++ b/testbed/huggingface__trl/trl/models/modeling_base.py @@ -0,0 +1,731 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import logging +import os +from copy import deepcopy +from typing import Optional + +import torch +import torch.nn as nn +from accelerate import PartialState +from huggingface_hub import hf_hub_download +from huggingface_hub.utils import ( + EntryNotFoundError, + HFValidationError, + LocalEntryNotFoundError, + RepositoryNotFoundError, +) +from safetensors.torch import load_file as safe_load_file +from transformers import GenerationMixin, PreTrainedModel, is_torch_npu_available, is_torch_xpu_available +from transformers.utils import is_peft_available + + +if is_peft_available(): + from peft import ( + PeftConfig, + PeftModel, + PeftModelForCausalLM, + PeftModelForSeq2SeqLM, + PromptLearningConfig, + get_peft_model, + prepare_model_for_kbit_training, + ) + + +from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled + + +LAYER_PATTERNS = [ + "transformer.h.{layer}", + "model.decoder.layers.{layer}", + "gpt_neox.layers.{layer}", + "model.layers.{layer}", +] + + +class PreTrainedModelWrapper(nn.Module): + r""" + A wrapper class around a (`transformers.PreTrainedModel`) to be compatible with the + (`~transformers.PreTrained`) class in order to keep some attributes and methods of the + (`~transformers.PreTrainedModel`) class. + + Attributes: + pretrained_model (`transformers.PreTrainedModel`): + The model to be wrapped. + parent_class (`transformers.PreTrainedModel`): + The parent class of the model to be wrapped. + supported_args (`list`): + The list of arguments that are supported by the wrapper class. + """ + + transformers_parent_class = None + supported_args = None + supported_modules = ("v_head",) + supported_rm_modules = ("score",) + supported_pretrained_model_architectures = ( + (PreTrainedModel) + if not is_peft_available() + else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM) + ) + + def __init__( + self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs + ): + super().__init__() + self.pretrained_model = pretrained_model + + self.config = pretrained_model.config + self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation + self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False) + self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False) + self.is_sequential_parallel = False + + if hasattr(pretrained_model, "gradient_checkpointing_disable"): + self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable + + if hasattr(pretrained_model, "gradient_checkpointing_enable"): + self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable + + if hasattr(pretrained_model, "enable_input_require_grads"): + self.enable_input_require_grads = pretrained_model.enable_input_require_grads + + self.supports_rm_adapter = supports_rm_adapter + self.rm_adapter_name = rm_adapter_name + self.policy_adapter_name = "default" + if score_module is not None: + self.score = score_module + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): + r""" + Instantiates a new model from a pretrained model from `transformers`. The + pretrained model is loaded using the `from_pretrained` method of the + `transformers.PreTrainedModel` class. The arguments that are specific to the + `transformers.PreTrainedModel` class are passed along this method and filtered + out from the `kwargs` argument. + + Args: + pretrained_model_name_or_path (`str` or `transformers.PreTrainedModel`): + The path to the pretrained model or its name. + *model_args (`list`, *optional*)): + Additional positional arguments passed along to the underlying model's + `from_pretrained` method. + **kwargs (`dict`, *optional*): + Additional keyword arguments passed along to the underlying model's + `from_pretrained` method. We also pre-process the kwargs to extract + the arguments that are specific to the `transformers.PreTrainedModel` + class and the arguments that are specific to trl models. The kwargs + also support `prepare_model_for_kbit_training` arguments from + `peft` library. + """ + if kwargs is not None: + peft_config = kwargs.pop("peft_config", None) + reward_adapter = kwargs.pop("reward_adapter", None) + reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter") + is_trainable = kwargs.pop("is_trainable", False) + trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs) + token = pretrained_kwargs.get("token", None) + else: + peft_config = None + is_trainable = False + trl_model_args = {} + pretrained_kwargs = {} + peft_quantization_kwargs = {} + token = None + + if reward_adapter is not None and not isinstance(reward_adapter, str): + raise ValueError( + "The `reward_adapter` argument should be a string representing the name of local path or the Hub id to the Reward Modeling adapter." + ) + + is_peft_model = False + + current_device = cls._get_current_device() + if isinstance(pretrained_model_name_or_path, str): + is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False + is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False + else: + is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False) + is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False) + + if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs: + # warn users + logging.warning( + "The `device_map` argument is not provided. We will override the device_map argument." + " to set the entire" + " model on the current device. If you want to set the model on multiple devices, please provide" + " a custom `device_map` argument." + ) + pretrained_kwargs["device_map"] = {"": current_device} + + if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig): + raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.") + + # First, load the pre-trained model using the parent-class + # either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM` + if isinstance(pretrained_model_name_or_path, str): + if is_peft_available(): + try: + # If there is a trained peft adapter in the hub, load its config. + remote_adapter_config = hf_hub_download( + pretrained_model_name_or_path, + "adapter_config.json", + token=token, + ) + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + remote_adapter_config = None + else: + remote_adapter_config = None + + local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json")) + + if (local_adapter_present or remote_adapter_config is not None) and is_peft_available(): + if peft_config is not None: + logging.warning( + "`peft_config` argument ignored since a peft config file was found in " + f"{pretrained_model_name_or_path}" + ) + + # Load the trained peft adapter config + if local_adapter_present: + trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path) + else: + remote_adapter_dir = os.path.dirname(remote_adapter_config) + trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir) + + # Load the pretrained base model + pretrained_model = cls.transformers_parent_class.from_pretrained( + trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs + ) + + # Wrap the pretrained model with the trained peft adapter + pretrained_model = PeftModel.from_pretrained( + pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable, token=token + ) + logging.info("Trained peft adapter loaded") + else: + pretrained_model = cls.transformers_parent_class.from_pretrained( + pretrained_model_name_or_path, *model_args, **pretrained_kwargs + ) + + if peft_config is not None: + # Initialize a new peft adapter with the given config + if is_loaded_in_8bit or is_loaded_in_4bit: + pretrained_model = prepare_model_for_kbit_training( + pretrained_model, + **peft_quantization_kwargs, + ) + pretrained_model = get_peft_model(pretrained_model, peft_config) + logging.info("peft adapter initialised") + + elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures): + pretrained_model = pretrained_model_name_or_path + + if peft_config is not None and isinstance(pretrained_model, PreTrainedModel): + # Initialize a new peft adapter with the given config + if is_loaded_in_8bit or is_loaded_in_4bit: + pretrained_model = prepare_model_for_kbit_training( + pretrained_model, + **peft_quantization_kwargs, + ) + pretrained_model = get_peft_model(pretrained_model, peft_config) + logging.info("peft adapter initialised") + else: + raise ValueError( + "pretrained_model_name_or_path should be a string or a PreTrainedModel, " + f"but is {type(pretrained_model_name_or_path)}" + ) + + if is_peft_available(): + if isinstance(pretrained_model, PeftModel): + is_peft_model = True + # for backward compatibility + if hasattr(pretrained_model, "active_peft_config") and isinstance( + pretrained_model.active_peft_config, PromptLearningConfig + ): + raise ValueError("PromptLearningConfig is not supported for PPO training.") + + # Add reward modeling adapter if specified + if not is_peft_model and reward_adapter is not None: + raise ValueError("reward_adapter can only be used with a PeftModel. ") + elif is_peft_model and reward_adapter is not None: + score_module = cls.add_and_load_reward_modeling_adapter( + pretrained_model, reward_adapter, reward_adapter_name, token=token + ) + multi_adapter_args = { + "score_module": score_module, + "supports_rm_adapter": True, + "rm_adapter_name": reward_adapter_name, + } + else: + multi_adapter_args = {"supports_rm_adapter": False} + + # Then, create the full model by instantiating the wrapper class + model = cls(pretrained_model, **multi_adapter_args, **trl_model_args) + + # if resume_training, load the state_dict again - this is ok since the + # state_dict is removed from the model after loading it. + is_resuming_training = True + if isinstance(pretrained_model_name_or_path, str): + safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors") + filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") + + sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json") + safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json") + is_sharded = False + use_safe = os.path.exists(safe_filename) + + if not (os.path.exists(filename) or os.path.exists(safe_filename)): + # Try with `pytorch_model.bin` + filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub( + pretrained_model, + pretrained_model_name_or_path, + sharded_index_filename, + token=token, + ) + # Try with safetensors + if filename is None and files_to_download is None: + safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub( + pretrained_model, + pretrained_model_name_or_path, + safe_sharded_index_filename, + token=token, + model_name="model.safetensors", + model_index_name="model.safetensors.index.json", + ) + use_safe = True + else: + use_safe = False + + loading_func = safe_load_file if use_safe else torch.load + load_kwargs = {} if use_safe else {"map_location": "cpu", "weights_only": True} + + if is_resuming_training: + if is_sharded: + # download each file and add it to the state_dict + state_dict = {} + + for shard_file in files_to_download: + filename = hf_hub_download( + pretrained_model_name_or_path, + shard_file, + token=token, + ) + state_dict.update(loading_func(filename, **load_kwargs)) + else: + state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs) + + else: + state_dict = pretrained_model_name_or_path.state_dict() + + model.is_peft_model = is_peft_model + model.current_device = current_device + + if is_resuming_training: + model.post_init(state_dict=state_dict) + + return model + + @classmethod + def _get_checkpoint_from_hub( + cls, + pretrained_model, + pretrained_model_name_or_path, + index_filename, + token=None, + model_name="pytorch_model.bin", + model_index_name="pytorch_model.bin.index.json", + ): + files_to_download = None + filename = None + is_resuming_training = True + is_sharded = False + + try: + filename = hf_hub_download( + pretrained_model_name_or_path, + model_name, + token=token, + ) + # sharded + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + if os.path.exists(index_filename): + index_file_name = index_filename + else: + try: + index_file_name = hf_hub_download( + pretrained_model_name_or_path, + model_index_name, + token=token, + ) + except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError): + # not continue training, do not have v_head weight + is_resuming_training = False + logging.warning( + f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', " + f"and no v_head weight is found. This IS expected if you are not resuming PPO training." + ) + # load json + if is_resuming_training: + with open(index_file_name) as f: + index = json.load(f) + # check filename with `v_head` or any known extra module: + files_to_download = set() + for k, v in index["weight_map"].items(): + if any(module in k for module in cls.supported_modules): + files_to_download.add(v) + is_sharded = True + + return filename, files_to_download, is_sharded, is_resuming_training + + @classmethod + def _get_current_device(cls): + r""" + Get the current device. For GPU, we return the local process index using the `accelerate.PartialState` + object to handle corner cases when running scripts in distributed environments. + + Returns: + current_device (`Union[int, str]`): + The current device. + """ + state = PartialState() + if is_torch_xpu_available(): + return f"xpu:{state.local_process_index}" + elif is_torch_npu_available(): + return f"npu:{state.local_process_index}" + else: + return state.local_process_index if torch.cuda.is_available() else "cpu" + + @classmethod + def _split_kwargs(cls, kwargs): + """ + Separate the kwargs from the arguments that we support inside + `supported_args` and the ones that we don't. + """ + check_peft_kwargs = False + + if is_peft_available(): + from peft import prepare_model_for_kbit_training + + check_peft_kwargs = True + + supported_kwargs = {} + unsupported_kwargs = {} + peft_kwargs = {} + + for key, value in kwargs.items(): + if key in cls.supported_args: + supported_kwargs[key] = value + else: + unsupported_kwargs[key] = value + + if check_peft_kwargs: + if key in prepare_model_for_kbit_training.__code__.co_varnames: + peft_kwargs[key] = value + if key in unsupported_kwargs: + unsupported_kwargs.pop(key) + + return supported_kwargs, unsupported_kwargs, peft_kwargs + + @classmethod + def add_and_load_reward_modeling_adapter( + cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None + ): + r""" + Add and load a reward modeling adapter. This method can only be used if the + model is a `PeftModel` and if you have initialized the model with the `reward_modeling_adapter_id` + argument, pointing to the id of the reward modeling adapter. The latest needs also to contain the + score head in order to produce the reward. + """ + pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False) + pretrained_model.train() + + filename = os.path.join(adapter_model_id, "adapter_model.bin") + safe_loading = False + if not os.path.exists(filename): + try: + local_filename = hf_hub_download( + adapter_model_id, + "adapter_model.bin", + token=token, + ) + except Exception: + filename = os.path.join(adapter_model_id, "adapter_model.safetensors") + safe_loading = True + if not os.path.exists(filename): + try: + local_filename = hf_hub_download( + adapter_model_id, + "adapter_model.safetensors", + token=token, + ) + except Exception as exc: + raise ValueError( + "Could not find adapter model in the Hub, " + "make sure you have the correct adapter model id." + ) from exc + else: + local_filename = filename + else: + local_filename = filename + + loading_func = safe_load_file if safe_loading else torch.load + load_kwargs = {} if safe_loading else {"map_location": "cpu", "weights_only": True} + + adapter_state_dict = loading_func(local_filename, **load_kwargs) + + for score_name_candidate in cls.supported_rm_modules: + if any(score_name_candidate in name for name in adapter_state_dict.keys()): + score_name = score_name_candidate + # we have found the correct head name and can break + break + + score_dict = {} + + for name, param in adapter_state_dict.items(): + if score_name in name: + key_name = ".".join(name.split(".")[-1:]) + score_dict[key_name] = param.to(cls._get_current_device()) + + num_labels, hidden_dim = score_dict["weight"].shape + has_bias = any("bias" in name for name in adapter_state_dict.keys()) + + score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to( + device=cls._get_current_device(), + dtype=pretrained_model.dtype, + ) + score.load_state_dict(score_dict) + for param in score.parameters(): + param.requires_grad = False + + return score + + def push_to_hub(self, *args, **kwargs): + r""" + Push the pretrained model to the hub. This method is a wrapper around + `transformers.PreTrainedModel.push_to_hub`. Please refer to the documentation + of `transformers.PreTrainedModel.push_to_hub` for more information. + + Args: + *args (`list`, *optional*): + Positional arguments passed along to the underlying model's + `push_to_hub` method. + **kwargs (`dict`, *optional*): + Keyword arguments passed along to the underlying model's + `push_to_hub` method. + """ + raise NotImplementedError + + def save_pretrained(self, *args, **kwargs): + r""" + Save the pretrained model to a directory. This method is a wrapper around + `transformers.PreTrainedModel.save_pretrained`. Please refer to the documentation + of `transformers.PreTrainedModel.save_pretrained` for more information. + + Args: + *args (`list`, *optional*): + Positional arguments passed along to the underlying model's + `save_pretrained` method. + **kwargs (`dict`, *optional*): + Keyword arguments passed along to the underlying model's + `save_pretrained` method. + """ + state_dict = kwargs.get("state_dict") + if state_dict is None: + state_dict = self.state_dict() + kwargs["state_dict"] = state_dict + + # if it is a peft model only save the `v_head` state_dict and + # pop the `state_dict` from the kwargs to avoid slient bugs with `peft` + if self.is_peft_model: + save_path = args[0] + save_path = os.path.join(save_path, "pytorch_model.bin") + torch.save(state_dict, save_path) + _ = kwargs.pop("state_dict", None) + + return self.pretrained_model.save_pretrained(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Return the state_dict of the pretrained model. + """ + raise NotImplementedError + + def post_init(self, *args, **kwargs): + r""" + Post initialization method. This method is called after the model is + instantiated and loaded from a checkpoint. It can be used to perform + additional operations such as loading the state_dict. + """ + raise NotImplementedError + + def compute_reward_score(self, input_ids, attention_mask=None, **kwargs): + r""" + Computes the reward score for a given input. The method has first to enable the adapter + and then compute the reward score. After that the model disables the reward modeling + adapter and enables the default ppo adapter again. + """ + if not self.supports_rm_adapter: + raise ValueError("This model does not support reward modeling adapter.") + + # enable rm adapter + self.pretrained_model.set_adapter(self.rm_adapter_name) + self.pretrained_model.eval() + + with torch.no_grad(): + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, + return_dict=True, + **kwargs, + ) + + last_hidden_states = base_model_output.hidden_states[-1] + scores = self.score(last_hidden_states) + + self.pretrained_model.set_adapter(self.policy_adapter_name) + self.pretrained_model.eval() + + return scores + + +def create_reference_model( + model: PreTrainedModelWrapper, num_shared_layers: Optional[int] = None, pattern: Optional[str] = None +) -> PreTrainedModelWrapper: + """ + Creates a static reference copy of a model. Note that model will be in `.eval()` mode. + + Args: + model (`PreTrainedModelWrapper`): The model to be copied. + num_shared_layers (`int`, *optional*): The number of initial layers that are shared between both models and kept frozen. + pattern (`str`, *optional*): The shared layers are selected with a string pattern + (e.g. "transformer.h.{layer}" for GPT2) and if a custom pattern is necessary it can be passed here. + + Returns: + `PreTrainedModelWrapper` + """ + if is_deepspeed_zero3_enabled(): + raise ValueError( + "DeepSpeed ZeRO-3 is enabled and is not compatible with `create_reference_model()`. Please instantiate your reference model directly with `AutoCausalLM.from_pretrained()`." + ) + + parameter_names = [n for n, _ in model.named_parameters()] + ref_model = deepcopy(model) + + # if no layers are shared, return copy of model + if num_shared_layers is None: + for param_name in parameter_names: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + return ref_model.eval() + + # identify layer name pattern + if pattern is not None: + pattern = pattern.format(layer=num_shared_layers) + else: + for pattern_candidate in LAYER_PATTERNS: + pattern_candidate = pattern_candidate.format(layer=num_shared_layers) + if any(pattern_candidate in name for name in parameter_names): + pattern = pattern_candidate + break + + if pattern is None: + raise ValueError("Layer pattern could not be matched.") + + # divide parameters in shared and unshared parameter lists + shared_param_list = [] + unshared_param_list = [] + + shared_parameter = True + for name, _param in model.named_parameters(): + if pattern in name: + shared_parameter = False + if shared_parameter: + shared_param_list.append(name) + else: + unshared_param_list.append(name) + + # create reference of the original parameter if they are shared + for param_name in shared_param_list: + param = model.get_parameter(param_name) + param.requires_grad = False + + _ref_param = ref_model.get_parameter(param_name) + + # for all other parameters just make sure they don't use gradients + for param_name in unshared_param_list: + param = ref_model.get_parameter(param_name) + param.requires_grad = False + + if pattern is not None and len(unshared_param_list) == 0: + logging.warning("Pattern passed or found, but no layers matched in the model. Check for a typo.") + + return ref_model.eval() + + +class GeometricMixtureWrapper(GenerationMixin): + r""" + Geometric Mixture generation wrapper that samples from the logits of two model's geometric mixture. + + Args: + model (`PreTrainedModel`): The model to be wrapped. + ref_model (`PreTrainedModel`): The reference model. + generation_config (`GenerationConfig`): The generation config. + mixture_coef (`float`, *optional* - default: 0.5): The mixture coefficient. + """ + + main_input_name = "input_ids" + _supports_cache_class = False + _supports_static_cache = False + + def __init__(self, model, ref_model, generation_config, mixture_coef=0.5, device=None): + super().__init__() + + self.model = model + self.config = model.config + self.ref_model = ref_model + self.generation_config = generation_config + self.mixture_coef = mixture_coef + self.device = device + + def __call__(self, *args, **kwargs): + return self.forward(*args, **kwargs) + + @torch.inference_mode() + def forward(self, *args, **kwargs): + model_outputs = self.model(*args, **kwargs) + model_logits = model_outputs.logits + ref_model_logits = self.ref_model(*args, **kwargs).logits + + model_outputs.logits = torch.nn.functional.log_softmax( + self.mixture_coef * ref_model_logits + (1 - self.mixture_coef) * model_logits, dim=-1 + ) + + return model_outputs + + def prepare_inputs_for_generation(self, *args, **kwargs): + # turn off cache in the generation config + kwargs["use_cache"] = False + model_inputs = self.model.prepare_inputs_for_generation(*args, **kwargs) + _ = self.ref_model.prepare_inputs_for_generation(*args, **kwargs) + + return model_inputs + + def _validate_model_class(self): + self.model._validate_model_class() + + def _validate_model_kwargs(self, model_kwargs): + return self.model._validate_model_kwargs(model_kwargs) diff --git a/testbed/huggingface__trl/trl/models/modeling_sd_base.py b/testbed/huggingface__trl/trl/models/modeling_sd_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2fee8d6b8bbcd317c43f49a7c778a612d43ecb63 --- /dev/null +++ b/testbed/huggingface__trl/trl/models/modeling_sd_base.py @@ -0,0 +1,910 @@ +# Copyright 2023 DDPO-pytorch authors (Kevin Black), The HuggingFace Team, metric-space. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import os +import random +import warnings +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, Union + +import numpy as np +import torch +import torch.utils.checkpoint as checkpoint +from diffusers import DDIMScheduler, StableDiffusionPipeline, UNet2DConditionModel +from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg +from transformers.utils import is_peft_available + +from ..core import randn_tensor +from .sd_utils import convert_state_dict_to_diffusers + + +if is_peft_available(): + from peft import LoraConfig + from peft.utils import get_peft_model_state_dict + + +@dataclass +class DDPOPipelineOutput: + """ + Output class for the diffusers pipeline to be finetuned with the DDPO trainer + + Args: + images (`torch.Tensor`): + The generated images. + latents (`List[torch.Tensor]`): + The latents used to generate the images. + log_probs (`List[torch.Tensor]`): + The log probabilities of the latents. + + """ + + images: torch.Tensor + latents: torch.Tensor + log_probs: torch.Tensor + + +@dataclass +class DDPOSchedulerOutput: + """ + Output class for the diffusers scheduler to be finetuned with the DDPO trainer + + Args: + latents (`torch.Tensor`): + Predicted sample at the previous timestep. Shape: `(batch_size, num_channels, height, width)` + log_probs (`torch.Tensor`): + Log probability of the above mentioned sample. Shape: `(batch_size)` + """ + + latents: torch.Tensor + log_probs: torch.Tensor + + +class DDPOStableDiffusionPipeline: + """ + Main class for the diffusers pipeline to be finetuned with the DDPO trainer + """ + + def __call__(self, *args, **kwargs) -> DDPOPipelineOutput: + raise NotImplementedError + + def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput: + raise NotImplementedError + + @property + def unet(self): + """ + Returns the 2d U-Net model used for diffusion. + """ + raise NotImplementedError + + @property + def vae(self): + """ + Returns the Variational Autoencoder model used from mapping images to and from the latent space + """ + raise NotImplementedError + + @property + def tokenizer(self): + """ + Returns the tokenizer used for tokenizing text inputs + """ + raise NotImplementedError + + @property + def scheduler(self): + """ + Returns the scheduler associated with the pipeline used for the diffusion process + """ + raise NotImplementedError + + @property + def text_encoder(self): + """ + Returns the text encoder used for encoding text inputs + """ + raise NotImplementedError + + @property + def autocast(self): + """ + Returns the autocast context manager + """ + raise NotImplementedError + + def set_progress_bar_config(self, *args, **kwargs): + """ + Sets the progress bar config for the pipeline + """ + raise NotImplementedError + + def save_pretrained(self, *args, **kwargs): + """ + Saves all of the model weights + """ + raise NotImplementedError + + def get_trainable_layers(self, *args, **kwargs): + """ + Returns the trainable parameters of the pipeline + """ + raise NotImplementedError + + def save_checkpoint(self, *args, **kwargs): + """ + Light wrapper around accelerate's register_save_state_pre_hook which is run before saving state + """ + raise NotImplementedError + + def load_checkpoint(self, *args, **kwargs): + """ + Light wrapper around accelerate's register_lad_state_pre_hook which is run before loading state + """ + raise NotImplementedError + + +def _left_broadcast(input_tensor, shape): + """ + As opposed to the default direction of broadcasting (right to left), this function broadcasts + from left to right + Args: + input_tensor (`torch.FloatTensor`): is the tensor to broadcast + shape (`Tuple[int]`): is the shape to broadcast to + """ + input_ndim = input_tensor.ndim + if input_ndim > len(shape): + raise ValueError( + "The number of dimensions of the tensor to broadcast cannot be greater than the length of the shape to broadcast to" + ) + return input_tensor.reshape(input_tensor.shape + (1,) * (len(shape) - input_ndim)).broadcast_to(shape) + + +def _get_variance(self, timestep, prev_timestep): + alpha_prod_t = torch.gather(self.alphas_cumprod, 0, timestep.cpu()).to(timestep.device) + alpha_prod_t_prev = torch.where( + prev_timestep.cpu() >= 0, + self.alphas_cumprod.gather(0, prev_timestep.cpu()), + self.final_alpha_cumprod, + ).to(timestep.device) + beta_prod_t = 1 - alpha_prod_t + beta_prod_t_prev = 1 - alpha_prod_t_prev + + variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev) + + return variance + + +def scheduler_step( + self, + model_output: torch.FloatTensor, + timestep: int, + sample: torch.FloatTensor, + eta: float = 0.0, + use_clipped_model_output: bool = False, + generator=None, + prev_sample: Optional[torch.FloatTensor] = None, +) -> DDPOSchedulerOutput: + """ + + Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion + process from the learned model outputs (most often the predicted noise). + + Args: + model_output (`torch.FloatTensor`): direct output from learned diffusion model. + timestep (`int`): current discrete timestep in the diffusion chain. + sample (`torch.FloatTensor`): + current instance of sample being created by diffusion process. + eta (`float`): weight of noise for added noise in diffusion step. + use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped + predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when + `self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would + coincide with the one provided as input and `use_clipped_model_output` will have not effect. + generator: random number generator. + variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we + can directly provide the noise for the variance itself. This is useful for methods such as + CycleDiffusion. (https://huggingface.co/papers/2210.05559) + + Returns: + `DDPOSchedulerOutput`: the predicted sample at the previous timestep and the log probability of the sample + """ + + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + # See formulas (12) and (16) of DDIM paper https://huggingface.co/papers/2010.02502 + # Ideally, read DDIM paper in-detail understanding + + # Notation ( -> + # - pred_noise_t -> e_theta(x_t, t) + # - pred_original_sample -> f_theta(x_t, t) or x_0 + # - std_dev_t -> sigma_t + # - eta -> η + # - pred_sample_direction -> "direction pointing to x_t" + # - pred_prev_sample -> "x_t-1" + # 1. get previous step value (=t-1) + prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps + # to prevent OOB on gather + prev_timestep = torch.clamp(prev_timestep, 0, self.config.num_train_timesteps - 1) + + # 2. compute alphas, betas + alpha_prod_t = self.alphas_cumprod.gather(0, timestep.cpu()) + alpha_prod_t_prev = torch.where( + prev_timestep.cpu() >= 0, + self.alphas_cumprod.gather(0, prev_timestep.cpu()), + self.final_alpha_cumprod, + ) + alpha_prod_t = _left_broadcast(alpha_prod_t, sample.shape).to(sample.device) + alpha_prod_t_prev = _left_broadcast(alpha_prod_t_prev, sample.shape).to(sample.device) + + beta_prod_t = 1 - alpha_prod_t + + # 3. compute predicted original sample from predicted noise also called + # "predicted x_0" of formula (12) from https://huggingface.co/papers/2010.02502 + if self.config.prediction_type == "epsilon": + pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) + pred_epsilon = model_output + elif self.config.prediction_type == "sample": + pred_original_sample = model_output + pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5) + elif self.config.prediction_type == "v_prediction": + pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output + pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" + " `v_prediction`" + ) + + # 4. Clip or threshold "predicted x_0" + if self.config.thresholding: + pred_original_sample = self._threshold_sample(pred_original_sample) + elif self.config.clip_sample: + pred_original_sample = pred_original_sample.clamp( + -self.config.clip_sample_range, self.config.clip_sample_range + ) + + # 5. compute variance: "sigma_t(η)" -> see formula (16) + # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) + variance = _get_variance(self, timestep, prev_timestep) + std_dev_t = eta * variance ** (0.5) + std_dev_t = _left_broadcast(std_dev_t, sample.shape).to(sample.device) + + if use_clipped_model_output: + # the pred_epsilon is always re-derived from the clipped x_0 in Glide + pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5) + + # 6. compute "direction pointing to x_t" of formula (12) from https://huggingface.co/papers/2010.02502 + pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon + + # 7. compute x_t without "random noise" of formula (12) from https://huggingface.co/papers/2010.02502 + prev_sample_mean = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction + + if prev_sample is not None and generator is not None: + raise ValueError( + "Cannot pass both generator and prev_sample. Please make sure that either `generator` or" + " `prev_sample` stays `None`." + ) + + if prev_sample is None: + variance_noise = randn_tensor( + model_output.shape, + generator=generator, + device=model_output.device, + dtype=model_output.dtype, + ) + prev_sample = prev_sample_mean + std_dev_t * variance_noise + + # log prob of prev_sample given prev_sample_mean and std_dev_t + log_prob = ( + -((prev_sample.detach() - prev_sample_mean) ** 2) / (2 * (std_dev_t**2)) + - torch.log(std_dev_t) + - torch.log(torch.sqrt(2 * torch.as_tensor(np.pi))) + ) + # mean along all but batch dimension + log_prob = log_prob.mean(dim=tuple(range(1, log_prob.ndim))) + + return DDPOSchedulerOutput(prev_sample.type(sample.dtype), log_prob) + + +# 1. The output type for call is different as the logprobs are now returned +# 2. An extra method called `scheduler_step` is added which is used to constraint the scheduler output +@torch.no_grad() +def pipeline_step( + self, + prompt: Optional[Union[str, List[str]]] = None, + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_prompt: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + guidance_rescale: float = 0.0, +): + r""" + Function invoked when calling the pipeline for generation. Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead. height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): The height in pixels of the generated image. + width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The width in pixels of the generated image. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py). + guidance_rescale (`float`, *optional*, defaults to 0.7): + Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are + Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of + [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). + Guidance rescale factor should fix overexposure when using zero terminal SNR. + + Examples: + + Returns: + `DDPOPipelineOutput`: The generated image, the predicted latents used to generate the image and the associated log probabilities + """ + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + height, + width, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_encoder_lora_scale = cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None + prompt_embeds = self._encode_prompt( + prompt, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. Prepare timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps = self.scheduler.timesteps + + # 5. Prepare latent variables + num_channels_latents = self.unet.config.in_channels + latents = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + ) + + # 6. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + all_latents = [latents] + all_log_probs = [] + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + # predict the noise residual + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + if do_classifier_free_guidance and guidance_rescale > 0.0: + # Based on 3.4. in https://huggingface.co/papers/2305.08891 + noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) + + # compute the previous noisy sample x_t -> x_t-1 + scheduler_output = scheduler_step(self.scheduler, noise_pred, t, latents, eta) + latents = scheduler_output.latents + log_prob = scheduler_output.log_probs + + all_latents.append(latents) + all_log_probs.append(log_prob) + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + if not output_type == "latent": + image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] + image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + return DDPOPipelineOutput(image, all_latents, all_log_probs) + + +def pipeline_step_with_grad( + pipeline, + prompt: Optional[Union[str, List[str]]] = None, + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + truncated_backprop: bool = True, + truncated_backprop_rand: bool = True, + gradient_checkpoint: bool = True, + truncated_backprop_timestep: int = 49, + truncated_rand_backprop_minmax: tuple = (0, 50), + negative_prompt: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + guidance_rescale: float = 0.0, +): + r""" + Function to get RGB image with gradients attached to the model weights. + + Args: + prompt (`str` or `List[str]`, *optional*, defaults to `None`): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds` instead. + height (`int`, *optional*, defaults to `pipeline.unet.config.sample_size * pipeline.vae_scale_factor`): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to `pipeline.unet.config.sample_size * pipeline.vae_scale_factor`): + The width in pixels of the generated image. + num_inference_steps (`int`, *optional*, defaults to `50`): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to `7.5`): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + truncated_backprop (`bool`, *optional*, defaults to True): + Truncated Backpropation to fixed timesteps, helps prevent collapse during diffusion reward training as shown in AlignProp (https://huggingface.co/papers/2310.03739). + truncated_backprop_rand (`bool`, *optional*, defaults to True): + Truncated Randomized Backpropation randomizes truncation to different diffusion timesteps, this helps prevent collapse during diffusion reward training as shown in AlignProp (https://huggingface.co/papers/2310.03739). + Enabling truncated_backprop_rand allows adapting earlier timesteps in diffusion while not resulting in a collapse. + gradient_checkpoint (`bool`, *optional*, defaults to True): + Adds gradient checkpointing to Unet forward pass. Reduces GPU memory consumption while slightly increasing the training time. + truncated_backprop_timestep (`int`, *optional*, defaults to 49): + Absolute timestep to which the gradients are being backpropagated. Higher number reduces the memory usage and reduces the chances of collapse. + While a lower value, allows more semantic changes in the diffusion generations, as the earlier diffusion timesteps are getting updated. + However it also increases the chances of collapse. + truncated_rand_backprop_minmax (`Tuple`, *optional*, defaults to (0,50)): + Range for randomized backprop. Here the value at 0 index indicates the earlier diffusion timestep to update (closer to noise), while the value + at index 1 indicates the later diffusion timestep to update. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `pipeline.processor` in + [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py). + guidance_rescale (`float`, *optional*, defaults to 0.7): + Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are + Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of + [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). + Guidance rescale factor should fix overexposure when using zero terminal SNR. + + Examples: + + Returns: + `DDPOPipelineOutput`: The generated image, the predicted latents used to generate the image and the associated log probabilities + """ + # 0. Default height and width to unet + height = height or pipeline.unet.config.sample_size * pipeline.vae_scale_factor + width = width or pipeline.unet.config.sample_size * pipeline.vae_scale_factor + + with torch.no_grad(): + # 1. Check inputs. Raise error if not correct + pipeline.check_inputs( + prompt, + height, + width, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = pipeline._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None + ) + prompt_embeds = pipeline._encode_prompt( + prompt, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. Prepare timesteps + pipeline.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps = pipeline.scheduler.timesteps + + # 5. Prepare latent variables + num_channels_latents = pipeline.unet.config.in_channels + latents = pipeline.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + ) + # 6. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * pipeline.scheduler.order + all_latents = [latents] + all_log_probs = [] + with pipeline.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + latent_model_input = pipeline.scheduler.scale_model_input(latent_model_input, t) + + # predict the noise residual + if gradient_checkpoint: + noise_pred = checkpoint.checkpoint( + pipeline.unet, + latent_model_input, + t, + prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + use_reentrant=False, + )[0] + else: + noise_pred = pipeline.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + )[0] + + # truncating backpropagation is critical for preventing overoptimization (https://huggingface.co/papers/2304.05977). + if truncated_backprop: + # Randomized truncation randomizes the truncation process (https://huggingface.co/papers/2310.03739) + # the range of truncation is defined by truncated_rand_backprop_minmax + # Setting truncated_rand_backprop_minmax[0] to be low will allow the model to update earlier timesteps in the diffusion chain, while setitng it high will reduce the memory usage. + if truncated_backprop_rand: + rand_timestep = random.randint( + truncated_rand_backprop_minmax[0], truncated_rand_backprop_minmax[1] + ) + if i < rand_timestep: + noise_pred = noise_pred.detach() + else: + # fixed truncation process + if i < truncated_backprop_timestep: + noise_pred = noise_pred.detach() + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + if do_classifier_free_guidance and guidance_rescale > 0.0: + # Based on 3.4. in https://huggingface.co/papers/2305.08891 + noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) + + # compute the previous noisy sample x_t -> x_t-1 + scheduler_output = scheduler_step(pipeline.scheduler, noise_pred, t, latents, eta) + latents = scheduler_output.latents + log_prob = scheduler_output.log_probs + + all_latents.append(latents) + all_log_probs.append(log_prob) + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % pipeline.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + if not output_type == "latent": + image = pipeline.vae.decode(latents / pipeline.vae.config.scaling_factor, return_dict=False)[0] + image, has_nsfw_concept = pipeline.run_safety_checker(image, device, prompt_embeds.dtype) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = pipeline.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) + + # Offload last model to CPU + if hasattr(pipeline, "final_offload_hook") and pipeline.final_offload_hook is not None: + pipeline.final_offload_hook.offload() + + return DDPOPipelineOutput(image, all_latents, all_log_probs) + + +class DefaultDDPOStableDiffusionPipeline(DDPOStableDiffusionPipeline): + def __init__(self, pretrained_model_name: str, *, pretrained_model_revision: str = "main", use_lora: bool = True): + self.sd_pipeline = StableDiffusionPipeline.from_pretrained( + pretrained_model_name, revision=pretrained_model_revision + ) + + self.use_lora = use_lora + self.pretrained_model = pretrained_model_name + self.pretrained_revision = pretrained_model_revision + + try: + self.sd_pipeline.load_lora_weights( + pretrained_model_name, + weight_name="pytorch_lora_weights.safetensors", + revision=pretrained_model_revision, + ) + self.use_lora = True + except OSError: + if use_lora: + warnings.warn( + "If you are aware that the pretrained model has no lora weights to it, ignore this message. " + "Otherwise please check the if `pytorch_lora_weights.safetensors` exists in the model folder." + ) + + self.sd_pipeline.scheduler = DDIMScheduler.from_config(self.sd_pipeline.scheduler.config) + self.sd_pipeline.safety_checker = None + + # memory optimization + self.sd_pipeline.vae.requires_grad_(False) + self.sd_pipeline.text_encoder.requires_grad_(False) + self.sd_pipeline.unet.requires_grad_(not self.use_lora) + + def __call__(self, *args, **kwargs) -> DDPOPipelineOutput: + return pipeline_step(self.sd_pipeline, *args, **kwargs) + + def rgb_with_grad(self, *args, **kwargs) -> DDPOPipelineOutput: + return pipeline_step_with_grad(self.sd_pipeline, *args, **kwargs) + + def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput: + return scheduler_step(self.sd_pipeline.scheduler, *args, **kwargs) + + @property + def unet(self): + return self.sd_pipeline.unet + + @property + def vae(self): + return self.sd_pipeline.vae + + @property + def tokenizer(self): + return self.sd_pipeline.tokenizer + + @property + def scheduler(self): + return self.sd_pipeline.scheduler + + @property + def text_encoder(self): + return self.sd_pipeline.text_encoder + + @property + def autocast(self): + return contextlib.nullcontext if self.use_lora else None + + def save_pretrained(self, output_dir): + if self.use_lora: + state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(self.sd_pipeline.unet)) + self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict) + self.sd_pipeline.save_pretrained(output_dir) + + def set_progress_bar_config(self, *args, **kwargs): + self.sd_pipeline.set_progress_bar_config(*args, **kwargs) + + def get_trainable_layers(self): + if self.use_lora: + lora_config = LoraConfig( + r=4, + lora_alpha=4, + init_lora_weights="gaussian", + target_modules=["to_k", "to_q", "to_v", "to_out.0"], + ) + self.sd_pipeline.unet.add_adapter(lora_config) + + # To avoid accelerate unscaling problems in FP16. + for param in self.sd_pipeline.unet.parameters(): + # only upcast trainable parameters (LoRA) into fp32 + if param.requires_grad: + param.data = param.to(torch.float32) + return self.sd_pipeline.unet + else: + return self.sd_pipeline.unet + + def save_checkpoint(self, models, weights, output_dir): + if len(models) != 1: + raise ValueError("Given how the trainable params were set, this should be of length 1") + if self.use_lora and hasattr(models[0], "peft_config") and getattr(models[0], "peft_config", None) is not None: + state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(models[0])) + self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict) + elif not self.use_lora and isinstance(models[0], UNet2DConditionModel): + models[0].save_pretrained(os.path.join(output_dir, "unet")) + else: + raise ValueError(f"Unknown model type {type(models[0])}") + + def load_checkpoint(self, models, input_dir): + if len(models) != 1: + raise ValueError("Given how the trainable params were set, this should be of length 1") + if self.use_lora: + lora_state_dict, network_alphas = self.sd_pipeline.lora_state_dict( + input_dir, weight_name="pytorch_lora_weights.safetensors" + ) + self.sd_pipeline.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=models[0]) + + elif not self.use_lora and isinstance(models[0], UNet2DConditionModel): + load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet") + models[0].register_to_config(**load_model.config) + models[0].load_state_dict(load_model.state_dict()) + del load_model + else: + raise ValueError(f"Unknown model type {type(models[0])}") diff --git a/testbed/huggingface__trl/trl/models/modeling_value_head.py b/testbed/huggingface__trl/trl/models/modeling_value_head.py new file mode 100644 index 0000000000000000000000000000000000000000..07977940135067cc06842dacecd24169dc4ed7a7 --- /dev/null +++ b/testbed/huggingface__trl/trl/models/modeling_value_head.py @@ -0,0 +1,445 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +import torch.nn as nn +from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, is_torch_npu_available, is_torch_xpu_available + +from .modeling_base import PreTrainedModelWrapper + + +class ValueHead(nn.Module): + r""" + The ValueHead class implements a head for GPT2 that returns a scalar for each output token. + """ + + def __init__(self, config, **kwargs): + super().__init__() + if not hasattr(config, "summary_dropout_prob"): + summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1) + else: + summary_dropout_prob = config.summary_dropout_prob + + self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity() + + # some models such as OPT have a projection layer before the word embeddings - e.g. OPT-350m + if hasattr(config, "hidden_size"): + hidden_size = config.hidden_size + if hasattr(config, "word_embed_proj_dim"): + hidden_size = config.word_embed_proj_dim + elif hasattr(config, "is_encoder_decoder"): + if config.is_encoder_decoder and hasattr(config, "decoder"): + if hasattr(config.decoder, "hidden_size"): + hidden_size = config.decoder.hidden_size + + self.summary = nn.Linear(hidden_size, 1) + + self.flatten = nn.Flatten() + + def forward(self, hidden_states): + output = self.dropout(hidden_states) + + # For now force upcast in fp32 if needed. Let's keep the + # output in fp32 for numerical stability. + if output.dtype != self.summary.weight.dtype: + output = output.to(self.summary.weight.dtype) + + output = self.summary(output) + return output + + +class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper): + r""" + An autoregressive model with a value head in addition to the language model head. + This class inherits from `~trl.PreTrainedModelWrapper` and wraps a + `transformers.PreTrainedModel` class. The wrapper class supports classic functions + such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped + model, simply manipulate the `pretrained_model` attribute of this class. + + Class attributes: + - **transformers_parent_class** (`transformers.PreTrainedModel`) -- The parent class of the wrapped model. This + should be set to `transformers.AutoModelForCausalLM` for this class. + - **lm_head_namings** (`tuple`) -- A tuple of strings that are used to identify the language model head of the + wrapped model. This is set to `("lm_head", "embed_out", "output_layer")` for this class but can be changed + for other models in the future + - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported + by the `ValueHead` class. Currently, the supported args are: + - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the + `ValueHead` class. + - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the + `ValueHead` if a specific initialization strategy is selected. + - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the + `ValueHead`. Currently, the supported strategies are: + - **`None`** -- Initializes the weights of the `ValueHead` with a random distribution. This is the default + strategy. + - **"normal"** -- Initializes the weights of the `ValueHead` with a normal distribution. + """ + + transformers_parent_class = AutoModelForCausalLM + lm_head_namings = ["lm_head", "embed_out", "output_layer"] + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + r""" + Initializes the model. + + Args: + pretrained_model (`transformers.PreTrainedModel`): + The model to wrap. It should be a causal language model such as GPT2. + or any model mapped inside the `AutoModelForCausalLM` class. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the `ValueHead` class. + """ + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + + if not any(hasattr(self.pretrained_model, attribute) for attribute in self.lm_head_namings): + raise ValueError("The model does not have a language model head, please use a model that has one.") + + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + + self._init_weights(**v_head_kwargs) + + def _init_weights(self, **kwargs): + r""" + Initializes the weights of the value head. The default initialization strategy is random. + Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument + when calling `.from_pretrained`. Supported strategies are: + - `normal`: initializes the weights with a normal distribution. + + Args: + **kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the `ValueHead` class. These arguments + can contain the `v_head_init_strategy` argument as well as the `v_head_initializer_range` + argument. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + return_past_key_values=False, + **kwargs, + ): + r""" + Applies a forward pass to the wrapped model and returns the logits of the value head. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. + past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`): + Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model + (see `past_key_values` input) to speed up sequential decoding. + attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + return_past_key_values (bool): A flag indicating if the computed hidden-states should be returned. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the wrapped model. + """ + kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples + kwargs["past_key_values"] = past_key_values + + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + **kwargs, + ) + + last_hidden_state = base_model_output.hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + if last_hidden_state.device != self.v_head.summary.weight.device: + last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device) + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + if return_past_key_values: + return (lm_logits, loss, value, base_model_output.past_key_values) + else: + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + A simple wrapper around the `generate` method of the wrapped model. + Please refer to the [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) + method of the wrapped model for more information about the supported arguments. + + Args: + *args (`list`, *optional*): + Positional arguments passed to the `generate` method of the wrapped model. + **kwargs (`dict`, *optional*): + Keyword arguments passed to the `generate` method of the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head + to the state dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + self.pretrained_model.v_head = self.v_head + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model + by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the + keys of the value head state dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if ( + "cpu" in self.pretrained_model.hf_device_map.values() + or "disk" in self.pretrained_model.hf_device_map.values() + ): + raise ValueError( + "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." + ) + + first_device = list(set(self.pretrained_model.hf_device_map.values()))[0] + if isinstance(first_device, int): + if is_torch_npu_available(): + first_device = f"npu:{first_device}" + elif is_torch_xpu_available(): + first_device = f"xpu:{first_device}" + else: + first_device = f"cuda:{first_device}" + self.v_head = self.v_head.to(first_device) + + def set_device_hook(module, input, outputs): + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(first_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + + self.is_sequential_parallel = True + + +class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper): + r""" + A seq2seq model with a value head in addition to the language model head. + This class inherits from `~trl.PreTrainedModelWrapper` and wraps a + `transformers.PreTrainedModel` class. The wrapper class supports classic functions + such as `from_pretrained` and `push_to_hub` and also provides some additional + functionalities such as `generate`. + + Args: + pretrained_model (`transformers.PreTrainedModel`): + The model to wrap. It should be a causal language model such as GPT2. + or any model mapped inside the `AutoModelForSeq2SeqLM` class. + kwargs: + Additional keyword arguments passed along to the `ValueHead` class. + """ + + transformers_parent_class = AutoModelForSeq2SeqLM + lm_head_namings = ["lm_head", "embed_out", "output_projection"] + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + self.is_encoder_decoder = True + + if not self._has_lm_head(): + raise ValueError("The model does not have a language model head, please use a model that has one.") + + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + + self._init_weights(**v_head_kwargs) + + def _has_lm_head(self): + # check module names of all modules inside `pretrained_model` to find the language model head + for name, _module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + return True + return False + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model + by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the + keys of the value head state dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if ( + "cpu" in self.pretrained_model.hf_device_map.values() + or "disk" in self.pretrained_model.hf_device_map.values() + ): + raise ValueError( + "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." + ) + + # get the lm_head device + for name, module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + lm_head_device = module.weight.device + break + + # put v_head on the same device as the lm_head to avoid issues + self.v_head = self.v_head.to(lm_head_device) + + def set_device_hook(module, input, outputs): + r""" + A hook that sets the device of the output of the model to the device of the first + parameter of the model. + + Args: + module (`nn.Module`): + The module to which the hook is attached. + input (`tuple`): + The input to the module. + outputs (`tuple`): + The output of the module. + """ + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(lm_head_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + self.is_sequential_parallel = True + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head + to the state dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + self.pretrained_model.v_head = self.v_head + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def _init_weights(self, **kwargs): + r""" + We initialize the weights of the value head. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + return_past_key_values=False, + **kwargs, + ): + kwargs["past_key_values"] = past_key_values + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, # We force the model to output hidden states + **kwargs, + ) + + last_hidden_state = base_model_output.decoder_hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + if return_past_key_values: + return (lm_logits, loss, value, base_model_output.past_key_values) + else: + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + We call `generate` on the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) diff --git a/testbed/huggingface__trl/trl/models/sd_utils.py b/testbed/huggingface__trl/trl/models/sd_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a6bbbebf407a09be00061c5ddc6b0d8e89e50e36 --- /dev/null +++ b/testbed/huggingface__trl/trl/models/sd_utils.py @@ -0,0 +1,149 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +State dict utilities: utility methods for converting state dicts easily +File copied from diffusers to avoid import issues and make TRL compatible +with most of diffusers versions. +""" + +import enum + + +class StateDictType(enum.Enum): + """ + The mode to use when converting state dicts. + """ + + DIFFUSERS_OLD = "diffusers_old" + PEFT = "peft" + + +PEFT_TO_DIFFUSERS = { + ".q_proj.lora_B": ".q_proj.lora_linear_layer.up", + ".q_proj.lora_A": ".q_proj.lora_linear_layer.down", + ".k_proj.lora_B": ".k_proj.lora_linear_layer.up", + ".k_proj.lora_A": ".k_proj.lora_linear_layer.down", + ".v_proj.lora_B": ".v_proj.lora_linear_layer.up", + ".v_proj.lora_A": ".v_proj.lora_linear_layer.down", + ".out_proj.lora_B": ".out_proj.lora_linear_layer.up", + ".out_proj.lora_A": ".out_proj.lora_linear_layer.down", + "to_k.lora_A": "to_k.lora.down", + "to_k.lora_B": "to_k.lora.up", + "to_q.lora_A": "to_q.lora.down", + "to_q.lora_B": "to_q.lora.up", + "to_v.lora_A": "to_v.lora.down", + "to_v.lora_B": "to_v.lora.up", + "to_out.0.lora_A": "to_out.0.lora.down", + "to_out.0.lora_B": "to_out.0.lora.up", +} + +DIFFUSERS_OLD_TO_DIFFUSERS = { + ".to_q_lora.up": ".q_proj.lora_linear_layer.up", + ".to_q_lora.down": ".q_proj.lora_linear_layer.down", + ".to_k_lora.up": ".k_proj.lora_linear_layer.up", + ".to_k_lora.down": ".k_proj.lora_linear_layer.down", + ".to_v_lora.up": ".v_proj.lora_linear_layer.up", + ".to_v_lora.down": ".v_proj.lora_linear_layer.down", + ".to_out_lora.up": ".out_proj.lora_linear_layer.up", + ".to_out_lora.down": ".out_proj.lora_linear_layer.down", +} + +DIFFUSERS_STATE_DICT_MAPPINGS = { + StateDictType.DIFFUSERS_OLD: DIFFUSERS_OLD_TO_DIFFUSERS, + StateDictType.PEFT: PEFT_TO_DIFFUSERS, +} + +KEYS_TO_ALWAYS_REPLACE = { + ".processor.": ".", +} + + +def convert_state_dict(state_dict, mapping): + r""" + Simply iterates over the state dict and replaces the patterns in `mapping` with the corresponding values. + + Args: + state_dict (`dict[str, torch.Tensor]`): + The state dict to convert. + mapping (`dict[str, str]`): + The mapping to use for conversion, the mapping should be a dictionary with the following structure: + - key: the pattern to replace + - value: the pattern to replace with + + Returns: + converted_state_dict (`dict`) + The converted state dict. + """ + converted_state_dict = {} + for k, v in state_dict.items(): + # First, filter out the keys that we always want to replace + for pattern in KEYS_TO_ALWAYS_REPLACE.keys(): + if pattern in k: + new_pattern = KEYS_TO_ALWAYS_REPLACE[pattern] + k = k.replace(pattern, new_pattern) + + for pattern in mapping.keys(): + if pattern in k: + new_pattern = mapping[pattern] + k = k.replace(pattern, new_pattern) + break + converted_state_dict[k] = v + return converted_state_dict + + +def convert_state_dict_to_diffusers(state_dict, original_type=None, **kwargs): + r""" + Converts a state dict to new diffusers format. The state dict can be from previous diffusers format + (`OLD_DIFFUSERS`), or PEFT format (`PEFT`) or new diffusers format (`DIFFUSERS`). In the last case the method will + return the state dict as is. + + The method only supports the conversion from diffusers old, PEFT to diffusers new for now. + + Args: + state_dict (`dict[str, torch.Tensor]`): + The state dict to convert. + original_type (`StateDictType`, *optional*): + The original type of the state dict, if not provided, the method will try to infer it automatically. + kwargs (`dict`, *args*): + Additional arguments to pass to the method. + + - **adapter_name**: For example, in case of PEFT, some keys will be pre-pended + with the adapter name, therefore needs a special handling. By default PEFT also takes care of that in + `get_peft_model_state_dict` method: + https://github.com/huggingface/peft/blob/ba0477f2985b1ba311b83459d29895c809404e99/src/peft/utils/save_and_load.py#L92 + but we add it here in case we don't want to rely on that method. + """ + peft_adapter_name = kwargs.pop("adapter_name", None) + if peft_adapter_name is not None: + peft_adapter_name = "." + peft_adapter_name + else: + peft_adapter_name = "" + + if original_type is None: + # Old diffusers to PEFT + if any("to_out_lora" in k for k in state_dict.keys()): + original_type = StateDictType.DIFFUSERS_OLD + elif any(f".lora_A{peft_adapter_name}.weight" in k for k in state_dict.keys()): + original_type = StateDictType.PEFT + elif any("lora_linear_layer" in k for k in state_dict.keys()): + # nothing to do + return state_dict + else: + raise ValueError("Could not automatically infer state dict type") + + if original_type not in DIFFUSERS_STATE_DICT_MAPPINGS.keys(): + raise ValueError(f"Original type {original_type} is not supported") + + mapping = DIFFUSERS_STATE_DICT_MAPPINGS[original_type] + return convert_state_dict(state_dict, mapping) diff --git a/testbed/huggingface__trl/trl/models/utils.py b/testbed/huggingface__trl/trl/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..562b8617ed6f8ddfda8b26ba3c5d002acf185567 --- /dev/null +++ b/testbed/huggingface__trl/trl/models/utils.py @@ -0,0 +1,189 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import itertools +from contextlib import contextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal, Optional, Tuple, Union + +from accelerate.utils import is_deepspeed_available +from transformers import PreTrainedModel, PreTrainedTokenizer + +from .modeling_value_head import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead + + +SUPPORTED_ARCHITECTURES = ( + AutoModelForCausalLMWithValueHead, + AutoModelForSeq2SeqLMWithValueHead, +) + +if is_deepspeed_available(): + import deepspeed + +if TYPE_CHECKING: + from accelerate import Accelerator + from deepspeed.runtime.engine import DeepSpeedEngine + from torch.nn.parallel.distributed import DistributedDataParallel + + from .modeling_base import PreTrainedModelWrapper + + +# TODO: Add Abstract Base Class if more formats are added +@dataclass +class ChatMlSpecialTokens: + """Dataclass for special tokens used in ChatML, including system, user, assistant, bos, eos, and pad tokens.""" + + bos_token: str = "<|im_start|>" + eos_token: str = "<|im_end|>" + pad_token: str = "<|im_end|>" + + @property + def system(self): + return f"{self.bos_token}system" + + @property + def user(self): + return f"{self.bos_token}user" + + @property + def assistant(self): + return f"{self.bos_token}assistant" + + @property + def chat_template(self): + return ( + "{% for message in messages %}" + f"{{{{'{self.bos_token}' + message['role'] + '\n' + message['content'] + '{self.eos_token}' + '\n'}}}}" + "{% endfor %}" + "{% if add_generation_prompt %}" + f"{{{{ '{self.assistant}\n' }}}}" + "{% endif %}" + ) + + +FORMAT_MAPPING = {"chatml": ChatMlSpecialTokens} + + +def setup_chat_format( + model: PreTrainedModel, + tokenizer: PreTrainedTokenizer, + format: Optional[Literal["chatml"]] = "chatml", + resize_to_multiple_of: Optional[int] = None, +) -> Tuple[PreTrainedModel, PreTrainedTokenizer]: + """ + Setup chat format by adding special tokens to the tokenizer, setting the correct format, and extending the embedding layer of the model based on the new special tokens. + + If the model already has a chat template, this will throw an error. If you want to overwrite it, please set `tokenizer.chat_template` to `None`. + + Args: + model (`~transformers.PreTrainedModel`): The model to be modified. + tokenizer (`~transformers.PreTrainedTokenizer`): The tokenizer to be modified. + format (`Optional[Literal["chatml"]]`): The format to be set. Defaults to "chatml". + resize_to_multiple_of (`Optional[int]`): Number to resize the embedding layer to. Defaults to None. + + Returns: + model (`~transformers.PreTrainedModel`): The modified model. + tokenizer (`~transformers.PreTrainedTokenizer`): The modified tokenizer. + """ + # check if model already had a chat template + if tokenizer.chat_template is not None: + raise ValueError( + "Chat template is already added to the tokenizer. If you want to overwrite it, please set it to None" + ) + + # check if format available and retrieve + if format not in FORMAT_MAPPING: + raise ValueError(f"Format {format} not available. Please use one of {FORMAT_MAPPING.keys()}") + + chat_format = FORMAT_MAPPING[format]() + + # set special tokens and them + tokenizer.eos_token = chat_format.eos_token + tokenizer.pad_token = chat_format.pad_token + tokenizer.bos_token = chat_format.bos_token + tokenizer.add_special_tokens({"additional_special_tokens": [chat_format.bos_token, chat_format.eos_token]}) + # set chat format for tokenizer + tokenizer.chat_template = chat_format.chat_template + + # resize embedding layer to a multiple of 64, https://x.com/karpathy/status/1621578354024677377 + model.resize_token_embeddings( + len(tokenizer), pad_to_multiple_of=resize_to_multiple_of if resize_to_multiple_of is not None else None + ) + # Update the model config to use the new eos & bos tokens + if getattr(model, "config", None) is not None: + model.config.pad_token_id = tokenizer.pad_token_id + model.config.bos_token_id = tokenizer.bos_token_id + model.config.eos_token_id = tokenizer.eos_token_id + # Update the generation config to use the new eos & bos token + if getattr(model, "generation_config", None) is not None: + model.generation_config.bos_token_id = tokenizer.bos_token_id + model.generation_config.eos_token_id = tokenizer.eos_token_id + model.generation_config.pad_token_id = tokenizer.pad_token_id + + return model, tokenizer + + +def remove_hooks(model: "DeepSpeedEngine") -> None: + """Removes the optimizer hooks from a DeepSpeed ZeRO-3 model.""" + if model.optimizer is not None and hasattr(model.optimizer, "parameter_offload"): + optimizer_offload = model.optimizer.parameter_offload + elif model.optimizer is not None: + optimizer_offload = model.optimizer + + for param in iter_params(optimizer_offload.module, recurse=True): + param.ds_active_sub_modules.clear() + + for hook in optimizer_offload.forward_hooks: + hook.remove() + for hook in optimizer_offload.backward_hooks: + hook.remove() + + optimizer_offload.forward_hooks = [] + optimizer_offload.backward_hooks = [] + + +def get_all_parameters(sub_module, recurse=False): + return itertools.chain(sub_module.named_parameters(recurse=recurse), sub_module.ds_external_parameters()) + + +def iter_params(module, recurse=False): + return [param for _, param in get_all_parameters(module, recurse)] + + +def add_hooks(model: "DeepSpeedEngine") -> None: + """Adds the optimizer hooks from a DeepSpeed ZeRO-3 model.""" + if model.optimizer is not None and hasattr(model.optimizer, "parameter_offload"): + optimizer_offload = model.optimizer.parameter_offload + elif model.optimizer is not None: + optimizer_offload = model.optimizer + optimizer_offload._register_hooks_recursively(optimizer_offload.module) + + +@contextmanager +def unwrap_model_for_generation( + model: Union["DistributedDataParallel", "DeepSpeedEngine"], accelerator: "Accelerator", is_peft_model: bool = False +) -> Union["PreTrainedModelWrapper", "DeepSpeedEngine"]: + """Context manager to unwrap a model for generation. + For ZeRO-3 models, we gather the weights once to speed up generation. + """ + unwrapped_model = accelerator.unwrap_model(model) + if is_peft_model: + unwrapped_model.pretrained_model.disable_adapter() + if accelerator.state.deepspeed_plugin is not None and accelerator.state.deepspeed_plugin.zero_stage == 3: + with deepspeed.zero.GatheredParameters(model.parameters()): + remove_hooks(model) + yield accelerator.unwrap_model(model) + add_hooks(model) + else: + yield unwrapped_model diff --git a/testbed/huggingface__trl/trl/templates/lm_model_card.md b/testbed/huggingface__trl/trl/templates/lm_model_card.md new file mode 100644 index 0000000000000000000000000000000000000000..316c5d829e843627d244711cce4f1f564361d445 --- /dev/null +++ b/testbed/huggingface__trl/trl/templates/lm_model_card.md @@ -0,0 +1,54 @@ +--- +{{ card_data }} +--- + +# Model Card for {{ model_name }} + +This model is a fine-tuned version of [{{ base_model }}](https://huggingface.co/{{ base_model }}){% if dataset_name %} on the [{{ dataset_name }}](https://huggingface.co/datasets/{{ dataset_name }}) dataset{% endif %}. +It has been trained using [TRL](https://github.com/huggingface/trl). + +## Quick start + +```python +from transformers import pipeline + +question = "If you had a time machine, but could only go to the past or the future once and never return, which would you choose and why?" +generator = pipeline("text-generation", model="{{ hub_model_id }}", device="cuda") +output = generator([{"role": "user", "content": question}], max_new_tokens=128, return_full_text=False)[0] +print(output["generated_text"]) +``` + +## Training procedure + +{% if wandb_url %}[Visualize in Weights & Biases]({{ wandb_url }}){% endif %} + +This model was trained with {{ trainer_name }}{% if paper_id %}, a method introduced in [{{ paper_title }}](https://huggingface.co/papers/{{ paper_id }}){% endif %}. + +### Framework versions + +- TRL: {{ trl_version }} +- Transformers: {{ transformers_version }} +- Pytorch: {{ pytorch_version }} +- Datasets: {{ datasets_version }} +- Tokenizers: {{ tokenizers_version }} + +## Citations + +{% if trainer_citation %}Cite {{ trainer_name }} as: + +```bibtex +{{ trainer_citation }} +```{% endif %} + +Cite TRL as: + +```bibtex +{% raw %}@misc{vonwerra2022trl, + title = {{TRL: Transformer Reinforcement Learning}}, + author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallouédec}, + year = 2020, + journal = {GitHub repository}, + publisher = {GitHub}, + howpublished = {\url{https://github.com/huggingface/trl}} +}{% endraw %} +``` diff --git a/testbed/huggingface__trl/trl/trainer/__init__.py b/testbed/huggingface__trl/trl/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e57b86dddd8113408cdfcb64e55bf9da7c23d69c --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/__init__.py @@ -0,0 +1,150 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# There is a circular import in the PPOTrainer if we let isort sort these +from typing import TYPE_CHECKING + +from ..import_utils import OptionalDependencyNotAvailable, _LazyModule, is_diffusers_available + + +_import_structure = { + "alignprop_config": ["AlignPropConfig"], + "alignprop_trainer": ["AlignPropTrainer"], + "base": ["BaseTrainer"], + "bco_config": ["BCOConfig"], + "bco_trainer": ["BCOTrainer"], + "callbacks": ["LogCompletionsCallback", "RichProgressCallback", "SyncRefModelCallback", "WinRateCallback"], + "cpo_config": ["CPOConfig"], + "cpo_trainer": ["CPOTrainer"], + "ddpo_config": ["DDPOConfig"], + "dpo_config": ["DPOConfig", "FDivergenceConstants", "FDivergenceType"], + "dpo_trainer": ["DPOTrainer"], + "gkd_config": ["GKDConfig"], + "gkd_trainer": ["GKDTrainer"], + "iterative_sft_trainer": ["IterativeSFTTrainer"], + "judges": [ + "AllTrueJudge", + "BaseJudge", + "BaseBinaryJudge", + "BasePairwiseJudge", + "BaseRankJudge", + "HfPairwiseJudge", + "OpenAIPairwiseJudge", + "PairRMJudge", + ], + "kto_config": ["KTOConfig"], + "kto_trainer": ["KTOTrainer"], + "model_config": ["ModelConfig"], + "nash_md_config": ["NashMDConfig"], + "nash_md_trainer": ["NashMDTrainer"], + "online_dpo_config": ["OnlineDPOConfig"], + "online_dpo_trainer": ["OnlineDPOTrainer"], + "orpo_config": ["ORPOConfig"], + "orpo_trainer": ["ORPOTrainer"], + "ppo_config": ["PPOConfig"], + "ppo_trainer": ["PPOTrainer"], + "ppov2_config": ["PPOv2Config"], + "ppov2_trainer": ["PPOv2Trainer"], + "reward_config": ["RewardConfig"], + "reward_trainer": ["RewardTrainer", "compute_accuracy"], + "rloo_config": ["RLOOConfig"], + "rloo_trainer": ["RLOOTrainer"], + "sft_config": ["SFTConfig"], + "sft_trainer": ["SFTTrainer"], + "utils": [ + "AdaptiveKLController", + "ConstantLengthDataset", + "DataCollatorForCompletionOnlyLM", + "FixedKLController", + "RunningMoments", + "disable_dropout_in_model", + "peft_module_casting_to_bf16", + ], + "xpo_config": ["XPOConfig"], + "xpo_trainer": ["XPOTrainer"], +} +try: + if not is_diffusers_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["ddpo_trainer"] = ["DDPOTrainer"] + +if TYPE_CHECKING: + from .alignprop_config import AlignPropConfig + from .alignprop_trainer import AlignPropTrainer + from .base import BaseTrainer + from .bco_config import BCOConfig + from .bco_trainer import BCOTrainer + from .callbacks import LogCompletionsCallback, RichProgressCallback, SyncRefModelCallback, WinRateCallback + from .cpo_config import CPOConfig + from .cpo_trainer import CPOTrainer + from .ddpo_config import DDPOConfig + from .dpo_config import DPOConfig, FDivergenceConstants, FDivergenceType + from .dpo_trainer import DPOTrainer + from .gkd_config import GKDConfig + from .gkd_trainer import GKDTrainer + from .iterative_sft_trainer import IterativeSFTTrainer + from .judges import ( + AllTrueJudge, + BaseBinaryJudge, + BaseJudge, + BasePairwiseJudge, + BaseRankJudge, + HfPairwiseJudge, + OpenAIPairwiseJudge, + PairRMJudge, + ) + from .kto_config import KTOConfig + from .kto_trainer import KTOTrainer + from .model_config import ModelConfig + from .nash_md_config import NashMDConfig + from .nash_md_trainer import NashMDTrainer + from .online_dpo_config import OnlineDPOConfig + from .online_dpo_trainer import OnlineDPOTrainer + from .orpo_config import ORPOConfig + from .orpo_trainer import ORPOTrainer + from .ppo_config import PPOConfig + from .ppo_trainer import PPOTrainer + from .reward_config import RewardConfig + from .reward_trainer import RewardTrainer, compute_accuracy + from .rloo_config import RLOOConfig + from .rloo_trainer import RLOOTrainer + from .sft_config import SFTConfig + from .sft_trainer import SFTTrainer + from .utils import ( + AdaptiveKLController, + ConstantLengthDataset, + DataCollatorForCompletionOnlyLM, + FixedKLController, + RunningMoments, + disable_dropout_in_model, + empty_cache, + peft_module_casting_to_bf16, + ) + from .xpo_config import XPOConfig + from .xpo_trainer import XPOTrainer + + try: + if not is_diffusers_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .ddpo_trainer import DDPOTrainer +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/testbed/huggingface__trl/trl/trainer/alignprop_config.py b/testbed/huggingface__trl/trl/trainer/alignprop_config.py new file mode 100644 index 0000000000000000000000000000000000000000..899958a2fe6c4f007e6fc276e21a62f4997a9df5 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/alignprop_config.py @@ -0,0 +1,154 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys +import warnings +from dataclasses import dataclass, field +from typing import Any, Dict, Literal, Optional, Tuple + +from transformers import is_bitsandbytes_available, is_torchvision_available + +from ..core import flatten_dict + + +@dataclass +class AlignPropConfig: + r""" + Configuration class for the [`AlignPropTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + exp_name (`str`, *optional*, defaults to `os.path.basename(sys.argv[0])[: -len(".py")]`): + Name of this experiment (defaults to the file name without the extension). + run_name (`str`, *optional*, defaults to `""`): + Name of this run. + log_with (`Optional[Literal["wandb", "tensorboard"]]`, *optional*, defaults to `None`): + Log with either `"wandb"` or `"tensorboard"`. Check + [tracking](https://huggingface.co/docs/accelerate/usage_guides/tracking) for more details. + log_image_freq (`int`, *optional*, defaults to `1`): + Frequency for logging images. + tracker_kwargs (`Dict[str, Any]`, *optional*, defaults to `{}`): + Keyword arguments for the tracker (e.g., `wandb_project`). + accelerator_kwargs (`Dict[str, Any]`, *optional*, defaults to `{}`): + Keyword arguments for the accelerator. + project_kwargs (`Dict[str, Any]`, *optional*, defaults to `{}`): + Keyword arguments for the accelerator project config (e.g., `logging_dir`). + tracker_project_name (`str`, *optional*, defaults to `"trl"`): + Name of project to use for tracking. + logdir (`str`, *optional*, defaults to `"logs"`): + Top-level logging directory for checkpoint saving. + num_epochs (`int`, *optional*, defaults to `100`): + Number of epochs to train. + save_freq (`int`, *optional*, defaults to `1`): + Number of epochs between saving model checkpoints. + num_checkpoint_limit (`int`, *optional*, defaults to `5`): + Number of checkpoints to keep before overwriting old ones. + mixed_precision (`str`, *optional*, defaults to `"fp16"`): + Mixed precision training. + allow_tf32 (`bool`, *optional*, defaults to `True`): + Allow `tf32` on Ampere GPUs. + resume_from (`str`, *optional*, defaults to `""`): + Path to resume training from a checkpoint. + sample_num_steps (`int`, *optional*, defaults to `50`): + Number of sampler inference steps. + sample_eta (`float`, *optional*, defaults to `1.0`): + Eta parameter for the DDIM sampler. + sample_guidance_scale (`float`, *optional*, defaults to `5.0`): + Classifier-free guidance weight. + train_use_8bit_adam (`bool`, *optional*, defaults to `False`): + Whether to use the 8bit Adam optimizer from `bitsandbytes`. + train_learning_rate (`float`, *optional*, defaults to `1e-3`): + Learning rate. + train_adam_beta1 (`float`, *optional*, defaults to `0.9`): + Beta1 for Adam optimizer. + train_adam_beta2 (`float`, *optional*, defaults to `0.999`): + Beta2 for Adam optimizer. + train_adam_weight_decay (`float`, *optional*, defaults to `1e-4`): + Weight decay for Adam optimizer. + train_adam_epsilon (`float`, *optional*, defaults to `1e-8`): + Epsilon value for Adam optimizer. + train_gradient_accumulation_steps (`int`, *optional*, defaults to `1`): + Number of gradient accumulation steps. + train_max_grad_norm (`float`, *optional*, defaults to `1.0`): + Maximum gradient norm for gradient clipping. + negative_prompts (`Optional[str]`, *optional*, defaults to `None`): + Comma-separated list of prompts to use as negative examples. + truncated_backprop_rand (`bool`, *optional*, defaults to `True`): + If `True`, randomized truncation to different diffusion timesteps is used. + truncated_backprop_timestep (`int`, *optional*, defaults to `49`): + Absolute timestep to which the gradients are backpropagated. Used only if `truncated_backprop_rand=False`. + truncated_rand_backprop_minmax (`Tuple[int, int]`, *optional*, defaults to `(0, 50)`): + Range of diffusion timesteps for randomized truncated backpropagation. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the final model to the Hub. + """ + + exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")] + run_name: str = "" + seed: int = 0 + log_with: Optional[Literal["wandb", "tensorboard"]] = None + log_image_freq: int = 1 + tracker_kwargs: Dict[str, Any] = field(default_factory=dict) + accelerator_kwargs: Dict[str, Any] = field(default_factory=dict) + project_kwargs: Dict[str, Any] = field(default_factory=dict) + tracker_project_name: str = "trl" + logdir: str = "logs" + num_epochs: int = 100 + save_freq: int = 1 + num_checkpoint_limit: int = 5 + mixed_precision: str = "fp16" + allow_tf32: bool = True + resume_from: str = "" + sample_num_steps: int = 50 + sample_eta: float = 1.0 + sample_guidance_scale: float = 5.0 + train_batch_size: int = 1 + train_use_8bit_adam: bool = False + train_learning_rate: float = 1e-3 + train_adam_beta1: float = 0.9 + train_adam_beta2: float = 0.999 + train_adam_weight_decay: float = 1e-4 + train_adam_epsilon: float = 1e-8 + train_gradient_accumulation_steps: int = 1 + train_max_grad_norm: float = 1.0 + negative_prompts: Optional[str] = None + truncated_backprop_rand: bool = True + truncated_backprop_timestep: int = 49 + truncated_rand_backprop_minmax: Tuple[int, int] = (0, 50) + push_to_hub: bool = False + + def to_dict(self): + output_dict = {} + for key, value in self.__dict__.items(): + output_dict[key] = value + return flatten_dict(output_dict) + + def __post_init__(self): + if self.log_with not in ["wandb", "tensorboard"]: + warnings.warn( + "Accelerator tracking only supports image logging if `log_with` is set to 'wandb' or 'tensorboard'." + ) + + if self.log_with == "wandb" and not is_torchvision_available(): + warnings.warn("Wandb image logging requires torchvision to be installed") + + if self.train_use_8bit_adam and not is_bitsandbytes_available(): + raise ImportError( + "You need to install bitsandbytes to use 8bit Adam. " + "You can install it with `pip install bitsandbytes`." + ) diff --git a/testbed/huggingface__trl/trl/trainer/alignprop_trainer.py b/testbed/huggingface__trl/trl/trainer/alignprop_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..84776a026bda00d80fce874965084f172619b400 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/alignprop_trainer.py @@ -0,0 +1,446 @@ +# Copyright 2023 AlignProp-pytorch authors (Mihir Prabhudesai), metric-space, The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import textwrap +from collections import defaultdict +from typing import Any, Callable, List, Optional, Tuple, Union +from warnings import warn + +import torch +from accelerate import Accelerator +from accelerate.logging import get_logger +from accelerate.utils import ProjectConfiguration, set_seed +from transformers import is_wandb_available + +from ..models import DDPOStableDiffusionPipeline +from . import AlignPropConfig, BaseTrainer +from .utils import generate_model_card + + +if is_wandb_available(): + import wandb + +logger = get_logger(__name__) + + +class AlignPropTrainer(BaseTrainer): + """ + The AlignPropTrainer uses Deep Diffusion Policy Optimization to optimise diffusion models. + Note, this trainer is heavily inspired by the work here: https://github.com/mihirp1998/AlignProp/ + As of now only Stable Diffusion based pipelines are supported + + Attributes: + config (`AlignPropConfig`): + Configuration object for AlignPropTrainer. Check the documentation of `PPOConfig` for more details. + reward_function (`Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor]`): + Reward function to be used + prompt_function (`Callable[[], Tuple[str, Any]]`): + Function to generate prompts to guide model + sd_pipeline (`DDPOStableDiffusionPipeline`): + Stable Diffusion pipeline to be used for training. + image_samples_hook (`Optional[Callable[[Any, Any, Any], Any]]`): + Hook to be called to log images + """ + + _tag_names = ["trl", "alignprop"] + + def __init__( + self, + config: AlignPropConfig, + reward_function: Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor], + prompt_function: Callable[[], Tuple[str, Any]], + sd_pipeline: DDPOStableDiffusionPipeline, + image_samples_hook: Optional[Callable[[Any, Any, Any], Any]] = None, + ): + if image_samples_hook is None: + warn("No image_samples_hook provided; no images will be logged") + + self.prompt_fn = prompt_function + self.reward_fn = reward_function + self.config = config + self.image_samples_callback = image_samples_hook + + accelerator_project_config = ProjectConfiguration(**self.config.project_kwargs) + + if self.config.resume_from: + self.config.resume_from = os.path.normpath(os.path.expanduser(self.config.resume_from)) + if "checkpoint_" not in os.path.basename(self.config.resume_from): + # get the most recent checkpoint in this directory + checkpoints = list( + filter( + lambda x: "checkpoint_" in x, + os.listdir(self.config.resume_from), + ) + ) + if len(checkpoints) == 0: + raise ValueError(f"No checkpoints found in {self.config.resume_from}") + checkpoint_numbers = sorted([int(x.split("_")[-1]) for x in checkpoints]) + self.config.resume_from = os.path.join( + self.config.resume_from, + f"checkpoint_{checkpoint_numbers[-1]}", + ) + + accelerator_project_config.iteration = checkpoint_numbers[-1] + 1 + + self.accelerator = Accelerator( + log_with=self.config.log_with, + mixed_precision=self.config.mixed_precision, + project_config=accelerator_project_config, + # we always accumulate gradients across timesteps; we want config.train.gradient_accumulation_steps to be the + # number of *samples* we accumulate across, so we need to multiply by the number of training timesteps to get + # the total number of optimizer steps to accumulate across. + gradient_accumulation_steps=self.config.train_gradient_accumulation_steps, + **self.config.accelerator_kwargs, + ) + + is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard" + + if self.accelerator.is_main_process: + self.accelerator.init_trackers( + self.config.tracker_project_name, + config=dict(alignprop_trainer_config=config.to_dict()) + if not is_using_tensorboard + else config.to_dict(), + init_kwargs=self.config.tracker_kwargs, + ) + + logger.info(f"\n{config}") + + set_seed(self.config.seed, device_specific=True) + + self.sd_pipeline = sd_pipeline + + self.sd_pipeline.set_progress_bar_config( + position=1, + disable=not self.accelerator.is_local_main_process, + leave=False, + desc="Timestep", + dynamic_ncols=True, + ) + + # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision + # as these weights are only used for inference, keeping weights in full precision is not required. + if self.accelerator.mixed_precision == "fp16": + inference_dtype = torch.float16 + elif self.accelerator.mixed_precision == "bf16": + inference_dtype = torch.bfloat16 + else: + inference_dtype = torch.float32 + + self.sd_pipeline.vae.to(self.accelerator.device, dtype=inference_dtype) + self.sd_pipeline.text_encoder.to(self.accelerator.device, dtype=inference_dtype) + self.sd_pipeline.unet.to(self.accelerator.device, dtype=inference_dtype) + + trainable_layers = self.sd_pipeline.get_trainable_layers() + + self.accelerator.register_save_state_pre_hook(self._save_model_hook) + self.accelerator.register_load_state_pre_hook(self._load_model_hook) + + # Enable TF32 for faster training on Ampere GPUs, + # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices + if self.config.allow_tf32: + torch.backends.cuda.matmul.allow_tf32 = True + + self.optimizer = self._setup_optimizer( + trainable_layers.parameters() if not isinstance(trainable_layers, list) else trainable_layers + ) + + self.neg_prompt_embed = self.sd_pipeline.text_encoder( + self.sd_pipeline.tokenizer( + [""] if self.config.negative_prompts is None else self.config.negative_prompts, + return_tensors="pt", + padding="max_length", + truncation=True, + max_length=self.sd_pipeline.tokenizer.model_max_length, + ).input_ids.to(self.accelerator.device) + )[0] + + # NOTE: for some reason, autocast is necessary for non-lora training but for lora training it isn't necessary and it uses + # more memory + self.autocast = self.sd_pipeline.autocast or self.accelerator.autocast + + if hasattr(self.sd_pipeline, "use_lora") and self.sd_pipeline.use_lora: + unet, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer) + self.trainable_layers = list(filter(lambda p: p.requires_grad, unet.parameters())) + else: + self.trainable_layers, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer) + + if config.resume_from: + logger.info(f"Resuming from {config.resume_from}") + self.accelerator.load_state(config.resume_from) + self.first_epoch = int(config.resume_from.split("_")[-1]) + 1 + else: + self.first_epoch = 0 + + def compute_rewards(self, prompt_image_pairs): + reward, reward_metadata = self.reward_fn( + prompt_image_pairs["images"], prompt_image_pairs["prompts"], prompt_image_pairs["prompt_metadata"] + ) + return reward + + def step(self, epoch: int, global_step: int): + """ + Perform a single step of training. + + Args: + epoch (int): The current epoch. + global_step (int): The current global step. + + Side Effects: + - Model weights are updated + - Logs the statistics to the accelerator trackers. + - If `self.image_samples_callback` is not None, it will be called with the prompt_image_pairs, global_step, and the accelerator tracker. + + Returns: + global_step (int): The updated global step. + """ + info = defaultdict(list) + + self.sd_pipeline.unet.train() + + for _ in range(self.config.train_gradient_accumulation_steps): + with self.accelerator.accumulate(self.sd_pipeline.unet), self.autocast(), torch.enable_grad(): + prompt_image_pairs = self._generate_samples( + batch_size=self.config.train_batch_size, + ) + + rewards = self.compute_rewards(prompt_image_pairs) + + prompt_image_pairs["rewards"] = rewards + + rewards_vis = self.accelerator.gather(rewards).detach().cpu().numpy() + + loss = self.calculate_loss(rewards) + + self.accelerator.backward(loss) + + if self.accelerator.sync_gradients: + self.accelerator.clip_grad_norm_( + self.trainable_layers.parameters() + if not isinstance(self.trainable_layers, list) + else self.trainable_layers, + self.config.train_max_grad_norm, + ) + + self.optimizer.step() + self.optimizer.zero_grad() + + info["reward_mean"].append(rewards_vis.mean()) + info["reward_std"].append(rewards_vis.std()) + info["loss"].append(loss.item()) + + # Checks if the accelerator has performed an optimization step behind the scenes + if self.accelerator.sync_gradients: + # log training-related stuff + info = {k: torch.mean(torch.tensor(v)) for k, v in info.items()} + info = self.accelerator.reduce(info, reduction="mean") + info.update({"epoch": epoch}) + self.accelerator.log(info, step=global_step) + global_step += 1 + info = defaultdict(list) + else: + raise ValueError( + "Optimization step should have been performed by this point. Please check calculated gradient accumulation settings." + ) + # Logs generated images + if self.image_samples_callback is not None and global_step % self.config.log_image_freq == 0: + self.image_samples_callback(prompt_image_pairs, global_step, self.accelerator.trackers[0]) + + if epoch != 0 and epoch % self.config.save_freq == 0 and self.accelerator.is_main_process: + self.accelerator.save_state() + + return global_step + + def calculate_loss(self, rewards): + """ + Calculate the loss for a batch of an unpacked sample + + Args: + rewards (torch.Tensor): + Differentiable reward scalars for each generated image, shape: [batch_size] + + Returns: + loss (torch.Tensor) + (all of these are of shape (1,)) + """ + # Loss is specific to Aesthetic Reward function used in AlignProp (https://huggingface.co/papers/2310.03739) + loss = 10.0 - (rewards).mean() + return loss + + def loss( + self, + advantages: torch.Tensor, + clip_range: float, + ratio: torch.Tensor, + ): + unclipped_loss = -advantages * ratio + clipped_loss = -advantages * torch.clamp( + ratio, + 1.0 - clip_range, + 1.0 + clip_range, + ) + return torch.mean(torch.maximum(unclipped_loss, clipped_loss)) + + def _setup_optimizer(self, trainable_layers_parameters): + if self.config.train_use_8bit_adam: + import bitsandbytes + + optimizer_cls = bitsandbytes.optim.AdamW8bit + else: + optimizer_cls = torch.optim.AdamW + + return optimizer_cls( + trainable_layers_parameters, + lr=self.config.train_learning_rate, + betas=(self.config.train_adam_beta1, self.config.train_adam_beta2), + weight_decay=self.config.train_adam_weight_decay, + eps=self.config.train_adam_epsilon, + ) + + def _save_model_hook(self, models, weights, output_dir): + self.sd_pipeline.save_checkpoint(models, weights, output_dir) + weights.pop() # ensures that accelerate doesn't try to handle saving of the model + + def _load_model_hook(self, models, input_dir): + self.sd_pipeline.load_checkpoint(models, input_dir) + models.pop() # ensures that accelerate doesn't try to handle loading of the model + + def _generate_samples(self, batch_size, with_grad=True, prompts=None): + """ + Generate samples from the model + + Args: + batch_size (int): Batch size to use for sampling + with_grad (bool): Whether the generated RGBs should have gradients attached to it. + + Returns: + prompt_image_pairs (Dict[Any]) + """ + prompt_image_pairs = {} + + sample_neg_prompt_embeds = self.neg_prompt_embed.repeat(batch_size, 1, 1) + + if prompts is None: + prompts, prompt_metadata = zip(*[self.prompt_fn() for _ in range(batch_size)]) + else: + prompt_metadata = [{} for _ in range(batch_size)] + + prompt_ids = self.sd_pipeline.tokenizer( + prompts, + return_tensors="pt", + padding="max_length", + truncation=True, + max_length=self.sd_pipeline.tokenizer.model_max_length, + ).input_ids.to(self.accelerator.device) + + prompt_embeds = self.sd_pipeline.text_encoder(prompt_ids)[0] + + if with_grad: + sd_output = self.sd_pipeline.rgb_with_grad( + prompt_embeds=prompt_embeds, + negative_prompt_embeds=sample_neg_prompt_embeds, + num_inference_steps=self.config.sample_num_steps, + guidance_scale=self.config.sample_guidance_scale, + eta=self.config.sample_eta, + truncated_backprop_rand=self.config.truncated_backprop_rand, + truncated_backprop_timestep=self.config.truncated_backprop_timestep, + truncated_rand_backprop_minmax=self.config.truncated_rand_backprop_minmax, + output_type="pt", + ) + else: + sd_output = self.sd_pipeline( + prompt_embeds=prompt_embeds, + negative_prompt_embeds=sample_neg_prompt_embeds, + num_inference_steps=self.config.sample_num_steps, + guidance_scale=self.config.sample_guidance_scale, + eta=self.config.sample_eta, + output_type="pt", + ) + + images = sd_output.images + + prompt_image_pairs["images"] = images + prompt_image_pairs["prompts"] = prompts + prompt_image_pairs["prompt_metadata"] = prompt_metadata + + return prompt_image_pairs + + def train(self, epochs: Optional[int] = None): + """ + Train the model for a given number of epochs + """ + global_step = 0 + if epochs is None: + epochs = self.config.num_epochs + for epoch in range(self.first_epoch, epochs): + global_step = self.step(epoch, global_step) + + def _save_pretrained(self, save_directory): + self.sd_pipeline.save_pretrained(save_directory) + self.create_model_card() + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{prabhudesai2024aligning, + title = {{Aligning Text-to-Image Diffusion Models with Reward Backpropagation}}, + author = {Mihir Prabhudesai and Anirudh Goyal and Deepak Pathak and Katerina Fragkiadaki}, + year = 2024, + eprint = {arXiv:2310.03739} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="AlignProp", + trainer_citation=citation, + paper_title="Aligning Text-to-Image Diffusion Models with Reward Backpropagation", + paper_id="2310.03739", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/base.py b/testbed/huggingface__trl/trl/trainer/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f0314cb987fcf5a520ed1ab1ad0a7eb107f18acc --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/base.py @@ -0,0 +1,46 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from huggingface_hub import PyTorchModelHubMixin + + +class BaseTrainer(PyTorchModelHubMixin): + r""" + Base class for all trainers - this base class implements the basic functions that we + need for a trainer. + + The trainer needs to have the following functions: + - step: takes in a batch of data and performs a step of training + - loss: takes in a batch of data and returns the loss + - compute_rewards: takes in a batch of data and returns the rewards + - _build_models_and_tokenizer: builds the models and tokenizer + - _build_dataset: builds the dataset + Each user is expected to implement their own trainer class that inherits from this base + if they want to use a new training algorithm. + """ + + def __init__(self, config): + self.config = config + + def step(self, *args): + raise NotImplementedError("Not implemented") + + def loss(self, *args): + raise NotImplementedError("Not implemented") + + def compute_rewards(self, *args): + raise NotImplementedError("Not implemented") + + def _save_pretrained(self, save_directory): + raise NotImplementedError("Not implemented") diff --git a/testbed/huggingface__trl/trl/trainer/bco_config.py b/testbed/huggingface__trl/trl/trainer/bco_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7a3f7a0915d2a95a1cd7ada52867c01906cfb4 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/bco_config.py @@ -0,0 +1,88 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from transformers import TrainingArguments + + +@dataclass +class BCOConfig(TrainingArguments): + r""" + Configuration class for the [`BCOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + max_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_prompt_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the prompt. This argument is required if you want to use the default data collator. + max_completion_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. + label_pad_token_id (`int`, *optional*, defaults to `-100`): + Label pad token id. This argument is required if you want to use the default data collator. + padding_value (`Optional[int]`, *optional*, defaults to `None`): + Padding value to use. If `None`, the padding value of the tokenizer is used. + truncation_mode (`str`, *optional*, defaults to `"keep_end"`): + Truncation mode to use when the prompt is too long. Possible values are `"keep_end"` or `"keep_start"`. + This argument is required if you want to use the default data collator. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from both the model and the reference model to W&B during + evaluation. + is_encoder_decoder (`Optional[bool]`, *optional*, defaults to `None`): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute reference model log probabilities for training and evaluation datasets. This is + useful when training without the reference model to reduce the total GPU memory needed. + model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + ref_model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the reference model + from a string. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + prompt_sample_size (`int`, *optional*, defaults to `1024`): + Number of prompts that are fed to density ratio classifier. + min_density_ratio (`float`, *optional*, defaults to `0.5`): + Minimum value of the density ratio. The estimated density ratio is clamped to this value. + max_density_ratio (`float`, *optional*, defaults to `10.0`): + Maximum value of the density ratio. The estimated density ratio is clamped to this value. + """ + + max_length: Optional[int] = None + max_prompt_length: Optional[int] = None + max_completion_length: Optional[int] = None + beta: float = 0.1 + label_pad_token_id: int = -100 + padding_value: Optional[int] = None + truncation_mode: str = "keep_end" + generate_during_eval: bool = False + is_encoder_decoder: Optional[bool] = None + precompute_ref_log_probs: bool = False + model_init_kwargs: Optional[Dict[str, Any]] = None + ref_model_init_kwargs: Optional[Dict[str, Any]] = None + dataset_num_proc: Optional[int] = None + prompt_sample_size: int = 1024 + min_density_ratio: float = 0.5 + max_density_ratio: float = 10.0 diff --git a/testbed/huggingface__trl/trl/trainer/bco_trainer.py b/testbed/huggingface__trl/trl/trainer/bco_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..11fab36ef3bb3d46fa9e8f32a7df8da7e25bff78 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/bco_trainer.py @@ -0,0 +1,1526 @@ +# BCO Authors: Seungjae Jung, Gunsoo Han, Daniel Wontae Nam and Kyoung-Woon On +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +import os +import random +import textwrap +import warnings +from collections import defaultdict +from contextlib import contextmanager, nullcontext +from copy import deepcopy +from operator import itemgetter +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Tuple, Union + +import numpy as np +import torch +import torch.amp as amp +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from accelerate.utils import is_deepspeed_available, tqdm +from datasets import Dataset +from torch.utils.data import DataLoader, SequentialSampler +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainingArguments, + is_sklearn_available, + is_wandb_available, +) +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalLoopOutput, has_length +from transformers.utils import is_peft_available + +from ..data_utils import maybe_apply_chat_template +from ..models import PreTrainedModelWrapper, create_reference_model +from .bco_config import BCOConfig +from .utils import ( + DPODataCollatorWithPadding, + RunningMoments, + disable_dropout_in_model, + generate_model_card, + pad_to_length, + peft_module_casting_to_bf16, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training + +if is_wandb_available(): + import wandb + +if is_sklearn_available(): + from sklearn.linear_model import LogisticRegression + +if is_deepspeed_available(): + import deepspeed + +if TYPE_CHECKING: + from transformers import PreTrainedModel, PreTrainedTokenizer + +RUNNING_NAME = "running.json" +CLF_NAME = "clf.pt" + + +def _tokenize( + batch: Dict[str, List[Any]], + tokenizer: "PreTrainedTokenizer", + embedding_tokenizer: Optional["PreTrainedTokenizer"] = None, +) -> Dict[str, List[Any]]: + """Tokenize a batch from a BCO specific dataset.""" + prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False) + prompt_input_ids = prompt_tokenized["input_ids"] + prompt_attention_mask = prompt_tokenized["attention_mask"] + prompt_and_completion = [prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"])] + full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False) + full_input_ids = full_tokenized["input_ids"] + full_attention_mask = full_tokenized["attention_mask"] + + answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids)] + answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask)] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids)] + # Prepare input tokens for token by token comparison + full_input_ids = [np.array(f) for f in full_input_ids] + for full, concat in zip(full_input_ids, full_concat_input_ids): + if len(full) != len(concat): + raise ValueError( + "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length." + ) + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = [len(p) for p in prompt_input_ids] + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx)): + if not np.array_equal(p, f[:r]): + response_token_ids_start_idx[idx] -= 1 + + prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx)] + prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] + + for p, m in zip(prompt_input_ids, prompt_attention_mask): + if len(p) != len(m): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx)] + answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] + + output = dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + answer_input_ids=answer_input_ids, + answer_attention_mask=answer_attention_mask, + ) + + if embedding_tokenizer is not None: + embedding_tokenized = embedding_tokenizer(batch["prompt"], truncation=True, add_special_tokens=False) + + output.update( + { + "embedding_input_ids": embedding_tokenized["input_ids"], + "embedding_attention_mask": embedding_tokenized["attention_mask"], + } + ) + + return output + + +def _process_tokens(example: Dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> Dict: + """Process tokens of a BCO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation + in case the prompt + completion responses is/are too long. First + we truncate the prompt; if we're still too long, we truncate the completion. + + We also create the labels for the completion responses, which are of length equal to + the sum of the length of the prompt and the completion response, with + label_pad_token_id for the prompt tokens. + """ + prompt = example["prompt"] + completion = example["completion"] + + batch = { + f"{kwargs['prefix']}prompt": prompt, + f"{kwargs['prefix']}completion": completion, + f"{kwargs['prefix']}label": example["label"], + } + + if not kwargs["is_encoder_decoder"]: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + + if not isinstance(completion, str): + raise ValueError(f"completion should be an str but got {type(completion)}") + + # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer + all_tokens = { + "prompt_input_ids": example["prompt_input_ids"], + "prompt_attention_mask": example["prompt_attention_mask"], + "answer_input_ids": example["answer_input_ids"], + "answer_attention_mask": example["answer_attention_mask"], + } + + # calculate max length by checking if BOS/EOS is already there + max_length = kwargs["max_length"] + bos_token_id = kwargs["tokenizer"].bos_token_id + eos_token_id = kwargs["tokenizer"].eos_token_id + if bos_token_id != all_tokens["prompt_input_ids"][0]: + max_length -= 1 + if eos_token_id != all_tokens["answer_input_ids"][-1]: + max_length -= 1 + + # if combined sequence is too long (> max_length - 1 for BOS token - 1 for EOS), truncate the prompt + if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: + for k in ["prompt_input_ids", "prompt_attention_mask"]: + if kwargs["truncation_mode"] == "keep_start": + all_tokens[k] = all_tokens[k][: kwargs["max_prompt_length"]] + elif kwargs["truncation_mode"] == "keep_end": + all_tokens[k] = all_tokens[k][-kwargs["max_prompt_length"] :] + else: + raise ValueError(f"Unknown truncation mode: {kwargs['truncation_mode']}") + + # if that's still too long, truncate the response + if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: + for k in ["answer_input_ids", "answer_attention_mask"]: + all_tokens[k] = all_tokens[k][: max_length - kwargs["max_prompt_length"]] + + # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens + batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"] + batch[f"{kwargs['prefix']}completion_input_ids"] = ( + all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"] + ) + batch[f"{kwargs['prefix']}completion_attention_mask"] = ( + all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"] + ) + + # add BOS, which affects both prompt and the full completion + if bos_token_id is not None: + if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]: + batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}prompt_input_ids" + ] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}prompt_attention_mask" + ] + batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}completion_input_ids" + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + # add EOS, which affects only the full completion + if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]: + batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [ + eos_token_id + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + [1] + + batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:] + batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [ + kwargs["label_pad_token_id"] + ] * len(batch[f"{kwargs['prefix']}prompt_input_ids"]) + else: + completion_tokens = kwargs["tokenizer"]( + completion, truncation=True, max_length=kwargs["max_completion_length"], add_special_tokens=True + ) + prompt_tokens = kwargs["tokenizer"]( + prompt, truncation=True, max_length=kwargs["max_prompt_length"], add_special_tokens=True + ) + + batch[f"{kwargs['prefix']}prompt_input_ids"] = prompt_tokens["input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = prompt_tokens["attention_mask"] + + batch[f"{kwargs['prefix']}completion_labels"] = completion_tokens["input_ids"] + batch[f"{kwargs['prefix']}completion_attention_mask"] = completion_tokens["attention_mask"] + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch[f"{kwargs['prefix']}completion_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["completion_labels"]) + ) + + return batch + + +class BCOTrainer(Trainer): + r""" + Initialize BCOTrainer from [BCO](https://huggingface.co/papers/2404.04656) paper. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForSequenceClassification`. + ref_model (`PreTrainedModelWrapper`): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no + reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. + args (`BCOConfig`): + The arguments to use for training. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + data_collator (`transformers.DataCollator`, *optional*, defaults to `None`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Dict`, defaults to `None`): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. + disable_dropout (`bool`, defaults to `True`): + Whether or not to disable dropouts in `model` and `ref_model`. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + model_adapter_name (`str`, defaults to `None`): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`str`, defaults to `None`): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + """ + + _tag_names = ["trl", "bco"] + + def __init__( + self, + model: Union[PreTrainedModel, nn.Module, str] = None, + ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + args: BCOConfig = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + data_collator: Optional[DataCollator] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None, + model_adapter_name: Optional[str] = None, + ref_adapter_name: Optional[str] = None, + embedding_func: Optional[Callable] = None, + embedding_tokenizer: Optional[PreTrainedTokenizerBase] = None, + ): + if not is_sklearn_available(): + raise ImportError( + "BCOTrainer requires the scikit-learn library. Please install it with `pip install scikit-learn`." + ) + + if type(args) is TrainingArguments: + raise ValueError("Please use `BCOConfig` instead `TrainingArguments`.") + + if not isinstance(model, str) and ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must mass a copy of it, or `None` if you use peft." + ) + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the BCOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + torch_dtype = model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + model_init_kwargs["torch_dtype"] = torch_dtype + + if args.ref_model_init_kwargs is None: + ref_model_init_kwargs = {} + elif not isinstance(ref_model, str): + raise ValueError( + "You passed ref_model_kwargs to the BCOTrainer. But your ref_model is already instantiated." + ) + else: + ref_model_init_kwargs = args.ref_model_init_kwargs + torch_dtype = ref_model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + ref_model_init_kwargs["torch_dtype"] = torch_dtype + + if isinstance(model, str): + warnings.warn( + "You passed a model_id to the BCOTrainer. This will automatically create an " + "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you." + ) + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + if isinstance(ref_model, str): + warnings.warn( + "You passed a ref model_id to the BCOTrainer. This will automatically create an " + "`AutoModelForCausalLM`" + ) + ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs) + + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + + if not is_peft_available() and peft_config is not None: + raise ValueError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it with `pip install peft` to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + # if model is a peft model and we have a peft_config, we merge and unload it first + if isinstance(model, PeftModel): + model = model.merge_and_unload() + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not is_wandb_available(): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases to be installed." + " Please install with `pip install wandb` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + self.is_peft_model = is_peft_available() and isinstance(model, PeftModel) + self.model_adapter_name = model_adapter_name + self.ref_adapter_name = ref_adapter_name + + if ref_model: + self.ref_model = ref_model + elif self.is_peft_model or args.precompute_ref_log_probs: + # The `model` with adapters turned off will be used as the reference model + self.ref_model = None + else: + self.ref_model = create_reference_model(model) + + if processing_class is None: + raise ValueError( + "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding" + ) + if args.max_length is None: + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `max_length` in the `BCOConfig`. " + "It will be set to `512` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_length = 512 + if args.max_length is not None: + max_length = args.max_length + + if args.max_prompt_length is None: + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `max_prompt_length` in the `BCOConfig`. " + "It will be set to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_prompt_length = 128 + if args.max_prompt_length is not None: + max_prompt_length = args.max_prompt_length + + max_completion_length = None + if args.max_completion_length is None and self.is_encoder_decoder: + warnings.warn( + "When using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the BCOTrainer's init" + " it will be set to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_completion_length = 128 + if args.max_completion_length is not None and self.is_encoder_decoder: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + label_pad_token_id=args.label_pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your BCOConfig" + " we have set it for you, but you should do it yourself in the future.", + UserWarning, + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + # disable dropout in the model and reference model + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.label_pad_token_id = args.label_pad_token_id + self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id + self.max_prompt_length = max_prompt_length + self.truncation_mode = args.truncation_mode + self.max_completion_length = max_completion_length + self.precompute_ref_log_probs = args.precompute_ref_log_probs + + # Since ref_logs are precomputed on the first call to get_train/eval_dataloader + # keep track of first called to avoid computation of future calls + self._precomputed_train_ref_log_probs = False + self._precomputed_eval_ref_log_probs = False + + # metric + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # BCO parameter + self.beta = args.beta + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + warnings.warn( + "You set `output_router_logits` to True in the model config, but `router_aux_loss_coef` is set to 0.0," + " meaning the auxiliary loss will not be used." + ) + + # Underlying Distribution Matching argument + self.embedding_func = embedding_func + self.embedding_tokenizer = embedding_tokenizer + + with PartialState().local_main_process_first(): + # Apply the chat template if needed + train_dataset = train_dataset.map( + maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + ) + # Shuffle the datasets + train_dataset = train_dataset.shuffle(seed=args.data_seed) + if eval_dataset is not None: + eval_dataset = eval_dataset.shuffle(seed=args.data_seed) + # Tokenize and prepare the training datasets + train_dataset = train_dataset.map( + _tokenize, + batched=True, + fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, + num_proc=args.dataset_num_proc, + desc="Tokenizing train dataset", + ) + + # Prepare the datasets + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": processing_class, + "max_length": self.max_length, + "truncation_mode": self.truncation_mode, + "label_pad_token_id": self.label_pad_token_id, + "max_prompt_length": self.max_prompt_length, + "max_completion_length": self.max_completion_length, + } + train_dataset = train_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized train dataset", + ) + + if eval_dataset is not None: + # Tokenize + eval_dataset = eval_dataset.map( + _tokenize, + fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, + batched=True, + num_proc=args.dataset_num_proc, + desc="Tokenizing eval dataset", + ) + + # Process + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": processing_class, + "max_length": self.max_length, + "truncation_mode": self.truncation_mode, + "label_pad_token_id": self.label_pad_token_id, + "max_prompt_length": self.max_prompt_length, + "max_completion_length": self.max_completion_length, + } + eval_dataset = eval_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized eval dataset", + ) + + desirable = train_dataset.filter( + lambda x: x["label"], num_proc=args.dataset_num_proc, desc="Filtering desirable examples" + ) + undesirable = train_dataset.filter( + lambda x: not x["label"], num_proc=args.dataset_num_proc, desc="Filtering undesirable examples" + ) + + desirable = desirable.shuffle(seed=args.data_seed) + undesirable = undesirable.shuffle(seed=args.data_seed) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + # Deepspeed Zero-3 does not support precompute_ref_log_probs + if self.is_deepspeed_enabled: + if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." + ) + + if self.ref_model is None: + if not (self.is_peft_model or self.precompute_ref_log_probs): + raise ValueError( + "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" + ) + else: + if self.is_deepspeed_enabled: + self.ref_model = self._prepare_deepspeed(self.ref_model) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + self.running = RunningMoments(accelerator=self.accelerator) + + if self.embedding_func is None: + warnings.warn("You did not pass `embedding_func` underlying distribution matching feature is deactivated.") + return + + chosen_embeddings = self._get_sample_prompt_embeddings(desirable, sample_size=self.args.prompt_sample_size) + rejected_embeddings = self._get_sample_prompt_embeddings(undesirable, sample_size=self.args.prompt_sample_size) + + embeddings = torch.cat((chosen_embeddings, rejected_embeddings), dim=0) + labels = torch.cat( + (torch.ones_like(chosen_embeddings[:, 0]), torch.zeros_like(rejected_embeddings[:, 0])), dim=0 + ) + + self.clf = LogisticRegression(class_weight="balanced").fit( + embeddings.cpu().float().numpy(), labels.cpu().numpy() + ) + + @property + def match_underlying_distribution(self): + return self.embedding_func is not None and self.embedding_tokenizer is not None + + def _get_chosen_prob(self, prompt_embeddings: torch.FloatTensor) -> torch.FloatTensor: + """ + Calculates the probability if the given prompt embedding is from desirable dataset. + This function calculates the probability in the process and ensemble across processes. + """ + dtype = prompt_embeddings.dtype + device = prompt_embeddings.device + rank = self.accelerator.process_index + + padded_prompt_embeddings = self.accelerator.pad_across_processes( + prompt_embeddings, pad_index=self.embedding_tokenizer.pad_token_id + ) + sample_size = padded_prompt_embeddings.shape[0] + nonzero = padded_prompt_embeddings.mean(dim=1) != self.embedding_tokenizer.pad_token_id + prompt_embeddings = self.accelerator.gather(padded_prompt_embeddings) + + # cannot predict for all empty values + if prompt_embeddings.shape[0] == 0: + return torch.tensor([], device=device, dtype=dtype) + + prob = self.clf.predict_proba(prompt_embeddings.cpu().float().numpy())[:, 1] + prob = torch.as_tensor(prob, dtype=dtype, device=device) + prob = self.accelerator.reduce(prob, reduction="mean") + + prob = prob[sample_size * rank : sample_size * (rank + 1)] + prob = prob[nonzero] + + return prob + + def _vectorize_prompt(self, input_ids: torch.LongTensor, attention_mask: torch.LongTensor) -> torch.FloatTensor: + """ + Replaces processing_class.pad_token_id to embedding_tokenizer.pad_token_id + and applies self.embedding_func + """ + input_ids = torch.where( + input_ids == self.processing_class.pad_token_id, + self.embedding_tokenizer.pad_token_id, + input_ids, + ) + + with torch.no_grad(): + embeddings = self.embedding_func( + input_ids=input_ids, + attention_mask=attention_mask, + ) + + return embeddings + + def _get_prompt_embeddings( + self, batch: Dict[str, Union[List, torch.LongTensor]] + ) -> Tuple[torch.FloatTensor, torch.FloatTensor]: + """Extract embeddings from frozen embedding model""" + + if not self.match_underlying_distribution: + return None, None + + embeddings = self._vectorize_prompt( + input_ids=batch["embedding_input_ids"], + attention_mask=batch["embedding_attention_mask"], + ) + + chosen_idx = [i for i in range(len(batch["label"])) if batch["label"][i] is True] + rejected_idx = [i for i in range(len(batch["label"])) if batch["label"][i] is False] + + chosen_embeddings = embeddings[chosen_idx, ...] + rejected_embeddings = embeddings[rejected_idx, ...] + + return (chosen_embeddings, rejected_embeddings) + + def _get_sample_prompt_embeddings(self, dataset: Dataset, sample_size: int = 512) -> torch.FloatTensor: + """ + Sample instances from dataset and get prompt embeddings. + Used for density ratio classifier training. + """ + n_samples = min(len(dataset), sample_size) + rand_indices = np.random.choice(len(dataset), size=(n_samples,)) + + embedding_dataset = dataset.select(rand_indices) + + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(embedding_dataset, **dataloader_params)) + + with torch.no_grad(): + all_embeddings = torch.empty(0) + for padded_batch in tqdm(iterable=data_loader, desc="Building sample prompt embeddings"): + embeddings = self._vectorize_prompt( + input_ids=padded_batch["embedding_input_ids"], + attention_mask=padded_batch["embedding_attention_mask"], + ) + embeddings = self.accelerator.gather_for_metrics(embeddings) + all_embeddings = torch.cat((all_embeddings, embeddings.cpu())) + + return all_embeddings + + def _prepare_deepspeed(self, model: PreTrainedModelWrapper): + # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + + if model is not None: + if hasattr(model, "config"): + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0) + if config_kwargs["zero_optimization"]["stage"] != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + def _save_optimizer_and_scheduler(self, output_dir): + super()._save_optimizer_and_scheduler(output_dir) + + # When saving optimizer and scheduler to checkpoint, save also the running delta object. + output_dir = output_dir if output_dir is not None else self.args.output_dir + + self.running.save_to_json(os.path.join(output_dir, RUNNING_NAME)) + + if self.match_underlying_distribution: + torch.save(self.clf.get_params(), os.path.join(output_dir, CLF_NAME)) + + def _load_optimizer_and_scheduler(self, checkpoint): + super()._load_optimizer_and_scheduler(checkpoint) + + if checkpoint is None: + return + # when loading optimizer and scheduler from checkpoint, also load the running delta object. + running_file = os.path.join(checkpoint, RUNNING_NAME) + if not os.path.isfile(running_file): + warnings.warn(f"Missing file {running_file}. Will use a new running delta value for BCO loss calculation") + else: + self.running = RunningMoments.load_from_json(self.accelerator, running_file) + + if self.match_underlying_distribution: + clf_file = os.path.join(checkpoint, CLF_NAME) + if not os.path.isfile(running_file): + warnings.warn(f"Missing file {clf_file}. Will use a new UDM classifier for BCO loss calculation") + else: + self.clf.set_params(**torch.load(clf_file, weights_only=True, map_location="cpu")) + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with self.accelerator.unwrap_model( + self.model + ).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext(): + if self.ref_adapter_name: + self.model.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.set_adapter(self.model_adapter_name or "default") + + def get_train_dataloader(self) -> DataLoader: + """ + Returns the training [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. + """ + + if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) + reference_completion_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): + reference_completion_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + self.train_dataset = self.train_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + self._precomputed_train_ref_log_probs = True + + return super().get_train_dataloader() + + def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: + """ + Returns the evaluation [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. + + Args: + eval_dataset (`torch.utils.data.Dataset`, *optional*): + If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted + by the `model.forward()` method are automatically removed. It must implement `__len__`. + """ + if eval_dataset is None and self.eval_dataset is None: + raise ValueError("Trainer: evaluation requires an eval_dataset.") + eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset + + if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_eval_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) + + reference_completion_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): + reference_completion_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + eval_dataset = eval_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs + if self.eval_dataset is not None: + self.eval_dataset = eval_dataset + self._precomputed_eval_ref_log_probs = True + + return super().get_eval_dataloader(eval_dataset=eval_dataset) + + def compute_reference_log_probs(self, padded_batch: Dict) -> Dict: + """Computes log probabilities of the reference model for a single padded batch of a BCO specific dataset.""" + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + if self.is_encoder_decoder: + completion_logits = self.model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + else: + completion_logits = self.model( + padded_batch["completion_input_ids"], + attention_mask=padded_batch["completion_attention_mask"], + ).logits + + else: + if self.is_encoder_decoder: + completion_logits = self.ref_model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + else: + completion_logits = self.ref_model( + padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"] + ).logits + + completion_logps = self.get_batch_logps( + completion_logits, + padded_batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + + return completion_logps + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + label_pad_token_id: int = -100, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) + average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + else: + # Fixes end-dec RuntimeError + labels = labels.clone() + + loss_mask = labels != label_pad_token_id + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == label_pad_token_id] = 0 + + per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def forward( + self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]] + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + model_kwargs = ( + { + "labels": batch["completion_labels"], + "decoder_input_ids": batch.get("completion_decoder_input_ids"), + } + if self.is_encoder_decoder + else {} + ) + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + batch["completion_input_ids"], + attention_mask=batch["completion_attention_mask"], + **model_kwargs, + ) + completion_logits = outputs.logits + + completion_logps = self.get_batch_logps( + completion_logits, + batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + + if completion_logps.shape[0] != len(batch["label"]): + raise ValueError( + "There is a mismatch between the number of examples in this batch and the number of " + "examples for which an output sequence was predicted." + ) + + chosen_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is False] + + chosen_logps = completion_logps[chosen_idx, ...] + rejected_logps = completion_logps[rejected_idx, ...] + + chosen_logits = completion_logits[chosen_idx, ...] + rejected_logits = completion_logits[rejected_idx, ...] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, outputs.aux_loss) + else: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits) + + def _get_udm_weight(self, rejected_embeddings: torch.FloatTensor) -> torch.FloatTensor: + prob_desirable = self._get_chosen_prob(rejected_embeddings) + min_ratio = self.args.min_density_ratio + max_ratio = self.args.max_density_ratio + + weight = (prob_desirable / (1 - prob_desirable + 1e-8)).clamp(min=min_ratio, max=max_ratio) + + return weight + + def bco_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + reference_chosen_logps: torch.FloatTensor, + reference_rejected_logps: torch.FloatTensor, + chosen_embeddings: Optional[torch.FloatTensor], + rejected_embeddings: Optional[torch.FloatTensor], + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the BCO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,) + policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,) + reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,) + reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in batch_size,) + chosen_embeddings: embeddings of desirable prompts + rejected_embeddings: embeddings of undesirable prompts + + Returns: + A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, delta). + The losses tensor contains the BCO loss for each example in the batch. + The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. + The delta value contains the moving average of all implicit rewards. + """ + + if policy_chosen_logps.shape[0] != 0 or reference_chosen_logps.shape[0] != 0: + chosen_logratios = policy_chosen_logps - reference_chosen_logps + chosen_rewards = self.beta * chosen_logratios + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + chosen_losses = torch.Tensor([]).to(self.accelerator.device) + chosen_rewards = torch.Tensor([]).to(self.accelerator.device) + + if policy_rejected_logps.shape[0] != 0 or reference_rejected_logps.shape[0] != 0: + rejected_logratios = policy_rejected_logps - reference_rejected_logps + rejected_rewards = self.beta * rejected_logratios + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + rejected_losses = torch.Tensor([]).to(self.accelerator.device) + rejected_rewards = torch.Tensor([]).to(self.accelerator.device) + + rewards = torch.cat((chosen_rewards, rejected_rewards), 0).mean().detach() + self.running.update(rewards) + delta = self.running.mean + + if policy_chosen_logps.shape[0] != 0 or reference_chosen_logps.shape[0] != 0: + chosen_losses = -F.logsigmoid(chosen_rewards - delta) + + if policy_rejected_logps.shape[0] != 0 or reference_rejected_logps.shape[0] != 0: + rejected_losses = -F.logsigmoid(-(rejected_rewards - delta)) + + if self.match_underlying_distribution: + chosen_weight = torch.ones_like(chosen_losses) + rejected_weight = self._get_udm_weight(rejected_embeddings) + + losses = torch.cat((chosen_weight * chosen_losses, rejected_weight * rejected_losses), dim=0) + else: + losses = torch.cat((chosen_losses, rejected_losses), dim=0) + + return losses, chosen_rewards, rejected_rewards, torch.as_tensor(delta) + + def get_batch_loss_metrics( + self, + model, + batch: Dict[str, Union[List, torch.LongTensor]], + ): + """Compute the BCO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()} + + forward_output = self.forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + ) = forward_output[:4] + if self.aux_loss_enabled: + aux_loss = forward_output[4] + + # if reference_logps in batch use them, otherwise use the reference model + if "reference_logps" in batch: + chosen_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is False] + + reference_chosen_logps = batch["reference_logps"][chosen_idx, ...] + reference_rejected_logps = batch["reference_logps"][rejected_idx, ...] + else: + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + ) = self.forward(self.model, batch)[:4] + else: + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + ) = self.forward(self.ref_model, batch)[:4] + + chosen_embeddings, rejected_embeddings = self._get_prompt_embeddings(batch) + + losses, chosen_rewards, rejected_rewards, delta = self.bco_loss( + policy_chosen_logps, + policy_rejected_logps, + reference_chosen_logps, + reference_rejected_logps, + chosen_embeddings, + rejected_embeddings, + ) + metrics["delta"] = delta.item() + + num_chosen = torch.Tensor([len(chosen_rewards)]).to(self.accelerator.device) + num_rejected = torch.Tensor([len(rejected_rewards)]).to(self.accelerator.device) + + all_num_chosen = self.accelerator.gather(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather(num_rejected).sum().item() + + if all_num_chosen > 0: + metrics["rewards/chosen_sum"] = self.accelerator.gather(chosen_rewards.nansum()).nansum().item() + metrics["logps/chosen_sum"] = self.accelerator.gather(policy_chosen_logps.nansum()).nansum().item() + metrics["logits/chosen_sum"] = self.accelerator.gather(policy_chosen_logits.nansum()).nansum().item() + metrics["count/chosen"] = all_num_chosen + + if all_num_rejected > 0: + metrics["rewards/rejected_sum"] = self.accelerator.gather(rejected_rewards.nansum()).nansum().item() + metrics["logps/rejected_sum"] = self.accelerator.gather(policy_rejected_logps.nansum()).nansum().item() + metrics["logits/rejected_sum"] = self.accelerator.gather(policy_rejected_logits.nansum()).nansum().item() + metrics["count/rejected"] = all_num_rejected + + loss = losses.nanmean() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + return_outputs=False, + num_items_in_batch=None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: + if not self.use_dpo_data_collator: + warnings.warn( + "compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + compute_loss_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs) + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: + if self.train_dataset is None or not has_length(self.train_dataset): + return None + return SequentialSampler(self.train_dataset) + + def generate_from_model_and_ref(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch cuda amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + # if reference_output in batch use that otherwise use the reference model + if "reference_output" in batch: + reference_output = batch["reference_output"] + else: + if self.ref_model is None: + with self.null_ref_context(): + reference_output = self.model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + else: + reference_output = self.ref_model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id) + reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True) + + return policy_output_decoded, reference_output_decoded + + def prediction_step( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + prediction_loss_only: bool, + ignore_keys: Optional[List[str]] = None, + ): + if not self.use_dpo_data_collator: + warnings.warn( + "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs) + + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["logits/chosen"], + "eval_logits/rejected": metrics["logits/rejected"], + } + logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys) + logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: Optional[bool] = None, + ignore_keys: Optional[List[str]] = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. + Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + target_indicies = [i for i in range(len(random_batch["delta"])) if random_batch["delta"][i] is False] + target_batch = { + "prompt_input_ids": itemgetter(*target_indicies)(random_batch["prompt_input_ids"]), + "prompt_attention_mask": itemgetter(*target_indicies)(random_batch["prompt_attention_mask"]), + "prompt": itemgetter(*target_indicies)(random_batch["prompt"]), + } + policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch) + + self.log( + { + "game_log": wandb.Table( + columns=["Prompt", "Policy", "Ref Model"], + rows=[ + [prompt, pol[len(prompt) :], ref[len(prompt) :]] + for prompt, pol, ref in zip( + target_batch["prompt"], policy_output_decoded, ref_output_decoded + ) + ], + ) + } + ) + self.state.log_history.pop() + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: Dict[str, float]) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`Dict[str, float]`): + The values to log. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # train metrics should have no prefix, eval should have 'eval_' + prefix = "eval_" if train_eval == "eval" else "" + # accumulate average metrics from sums and lengths + for split in ["chosen", "rejected"]: + if f"count/{split}" in self._stored_metrics[train_eval]: + count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item() + for metric in ["rewards", "logps", "logits"]: + logs[f"{prefix}{metric}/{split}"] = ( + torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item() + / count_sum + ) + # delete obsolete metric + del self._stored_metrics[train_eval][f"{metric}/{split}_sum"] + del self._stored_metrics[train_eval][f"count/{split}"] + # calculate reward margin + if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs: + logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"] + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or None, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{jung2024binary, + title = {{Binary Classifier Optimization for Large Language Model Alignment}}, + author = {Seungjae Jung and Gunsoo Han and Daniel Wontae Nam and Kyoung{-}Woon On}, + year = 2024, + eprint = {arXiv:2404.04656} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="BCO", + trainer_citation=citation, + paper_title="Binary Classifier Optimization for Large Language Model Alignment", + paper_id="2404.04656", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/callbacks.py b/testbed/huggingface__trl/trl/trainer/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..068f3ebfe09b12de0f4cef9e7ba8854a5c759267 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/callbacks.py @@ -0,0 +1,453 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import List, Optional, Union + +import pandas as pd +import torch +from accelerate import Accelerator +from accelerate.state import AcceleratorState +from accelerate.utils import gather_object, is_deepspeed_available +from rich.console import Console, Group +from rich.live import Live +from rich.panel import Panel +from rich.progress import Progress +from transformers import ( + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + Trainer, + TrainerCallback, + TrainerControl, + TrainerState, + TrainingArguments, +) +from transformers.integrations import WandbCallback +from transformers.trainer_utils import has_length + +from ..data_utils import maybe_apply_chat_template +from ..models.utils import unwrap_model_for_generation +from .judges import BasePairwiseJudge + + +if is_deepspeed_available(): + import deepspeed + + +def _generate_completions( + prompts: List[str], + model: PreTrainedModel, + tokenizer: PreTrainedTokenizerBase, + accelerator: Accelerator, + generation_config: Optional[GenerationConfig], + batch_size: int = 1, +) -> List[str]: + """ + Generates completions for a list of pre-formatted prompts from the given model. + + Args: + prompts (List[str]): A list of input prompts for which completions are to be generated. + model (PreTrainedModel): The pre-trained model to be used for generation. + tokenizer (PreTrainedTokenizerBase): The tokenizer to be used for encoding and decoding. + accelerator (Accelerator): The accelerator to be used for model execution. + generation_config (GenerationConfig): Configuration for text generation. + batch_size (int, optional): The number of prompts to process in each batch. Default is 1. + + Returns: + List[str]: A list of generated text completions corresponding to the input prompts. + """ + completions = [] + with unwrap_model_for_generation(model, accelerator) as unwrapped_model: + for idx in range(0, len(prompts), batch_size): + batch = prompts[idx : idx + batch_size] + tokenized_batch = tokenizer(batch, return_tensors="pt", padding=True, truncation=True).to(model.device) + generations = unwrapped_model.generate( + **tokenized_batch, + generation_config=generation_config, + ) + for prompt, generation in zip(tokenized_batch.input_ids, generations): + # Remove prompt from generation + generation = generation[len(prompt) :] + completion = tokenizer.decode(generation, skip_special_tokens=True) + completions.append(completion) + return completions + + +class SyncRefModelCallback(TrainerCallback): + def __init__( + self, + ref_model: Union[PreTrainedModel, torch.nn.Module], + accelerator: Optional[Accelerator], + ): + self.accelerator = accelerator + self.ref_model = ref_model + + @staticmethod + def _sync_target_model(model, target_model, alpha): + for target_param, copy_param in zip(target_model.parameters(), model.parameters()): + target_param.data.mul_(1.0 - alpha).add_(copy_param.data, alpha=alpha) + + @staticmethod + def sync_target_model(model, target_model, alpha): + deepspeed_plugin = AcceleratorState().deepspeed_plugin + if deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3: + with deepspeed.zero.GatheredParameters( + list(model.parameters()) + list(target_model.parameters()), modifier_rank=0 + ): + if deepspeed.comm.get_rank() == 0: + SyncRefModelCallback._sync_target_model(model, target_model, alpha) + else: + SyncRefModelCallback._sync_target_model(model, target_model, alpha) + + def on_step_end(self, args, state, control, **kwargs): + model: PreTrainedModel = kwargs["model"] + + if self.ref_model is not None and state.global_step % args.ref_model_sync_steps == 0: + if self.accelerator: + model = self.accelerator.unwrap_model(model) + self.sync_target_model(model, self.ref_model, args.ref_model_mixup_alpha) + + +class RichProgressCallback(TrainerCallback): + """ + A [`TrainerCallback`] that displays the progress of training or evaluation using Rich. + """ + + def __init__(self): + self.training_bar = None + self.prediction_bar = None + + self.training_task_id = None + self.prediction_task_id = None + + self.rich_group = None + self.rich_console = None + + self.training_status = None + self.current_step = None + + def on_train_begin(self, args, state, control, **kwargs): + if state.is_world_process_zero: + self.training_bar = Progress() + self.prediction_bar = Progress() + + self.rich_console = Console() + + self.training_status = self.rich_console.status("Nothing to log yet ...") + + self.rich_group = Live(Panel(Group(self.training_bar, self.prediction_bar, self.training_status))) + self.rich_group.start() + + self.training_task_id = self.training_bar.add_task("[blue]Training the model", total=state.max_steps) + self.current_step = 0 + + def on_step_end(self, args, state, control, **kwargs): + if state.is_world_process_zero: + self.training_bar.update(self.training_task_id, advance=state.global_step - self.current_step, update=True) + self.current_step = state.global_step + + def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): + if state.is_world_process_zero and has_length(eval_dataloader): + if self.prediction_task_id is None: + self.prediction_task_id = self.prediction_bar.add_task( + "[blue]Predicting on the evaluation dataset", total=len(eval_dataloader) + ) + self.prediction_bar.update(self.prediction_task_id, advance=1, update=True) + + def on_evaluate(self, args, state, control, **kwargs): + if state.is_world_process_zero: + if self.prediction_task_id is not None: + self.prediction_bar.remove_task(self.prediction_task_id) + self.prediction_task_id = None + + def on_predict(self, args, state, control, **kwargs): + if state.is_world_process_zero: + if self.prediction_task_id is not None: + self.prediction_bar.remove_task(self.prediction_task_id) + self.prediction_task_id = None + + def on_log(self, args, state, control, logs=None, **kwargs): + if state.is_world_process_zero and self.training_bar is not None: + _ = logs.pop("total_flos", None) + self.training_status.update(f"[bold green]Status = {str(logs)}") + + def on_train_end(self, args, state, control, **kwargs): + if state.is_world_process_zero: + self.rich_group.stop() + + self.training_bar = None + self.prediction_bar = None + self.training_task_id = None + self.prediction_task_id = None + self.rich_group = None + self.rich_console = None + self.training_status = None + self.current_step = None + + +class WinRateCallback(TrainerCallback): + """ + A [`~transformers.TrainerCallback`] that computes the win rate of a model based on a reference. + + It generates completions using prompts from the evaluation dataset and compares the trained model's outputs against + a reference. The reference is either the initial version of the model (before training) or the reference model, if + available in the trainer. During each evaluation step, a judge determines how often the trained model's completions + win against the reference using a judge. The win rate is then logged in the trainer's logs under the key + `"eval_win_rate"`. + + Usage: + ```python + trainer = DPOTrainer(...) + judge = PairRMJudge() + win_rate_callback = WinRateCallback(judge=judge, trainer=trainer) + trainer.add_callback(win_rate_callback) + ``` + + Args: + judge (`BasePairwiseJudge`): + The judge to use for comparing completions. + trainer (`Trainer`): + Trainer to which the callback will be attached. The trainer's evaluation dataset must include a `"prompt"` + column containing the prompts for generating completions. If the `Trainer` has a reference model (via the + `ref_model` attribute), it will use this reference model for generating the reference completions; + otherwise, it defaults to using the initial model. + generation_config (`GenerationConfig`, *optional*): + The generation config to use for generating completions. + num_prompts (`int` or `None`, *optional*, defaults to `None`): + The number of prompts to generate completions for. If not provided, defaults to the number of examples + in the evaluation dataset. + shuffle_order (`bool`, *optional*, defaults to `True`): + Whether to shuffle the order of the completions before judging. + use_soft_judge (`bool`, *optional*, defaults to `False`): + Whether to use a soft judge that returns a win probability between 0 and 1 for the first completion vs the + second. + """ + + def __init__( + self, + judge: BasePairwiseJudge, + trainer: Trainer, + generation_config: Optional[GenerationConfig] = None, + num_prompts: Optional[int] = None, + shuffle_order: bool = True, + use_soft_judge: bool = False, + ): + self.judge = judge + self.trainer = trainer + self.shuffle_order = shuffle_order + self.generation_config = generation_config + self.ref_completions = [] + self.use_soft_judge = use_soft_judge + + if self.trainer.eval_dataset is None: + raise ValueError("Trainer must have an evaluation dataset to use the WinRateCallback.") + else: + self.eval_dataset = self.trainer.eval_dataset + + if num_prompts is not None: + self.eval_dataset = self.eval_dataset.select(range(num_prompts)) + + def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + # When the trainer is initialized, we generate completions for the reference model. + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + # Use the reference model if available, otherwise use the initial model + model = getattr(self.trainer, "ref_model", None) + # At this point, there are two cases where `ref_model` is None: + # 1. The method doesn't require a reference model. + # 2. The method uses a reference model, but `ref_model` is set to None. + # This occurs when using PEFT, where the reference model can be obtained by simply disabling the model's adapter. + # In theory, we should disable the adapter here, but since it's zero-initialized at the start of training, + # the model behaves identically with or without the adapter. + # Therefore, there's no need to explicitly disable it at this point. + if model is None: + model = self.trainer.model_wrapped + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + self.ref_completions = _generate_completions( + prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + # Compute initial win rate as a reference point + completions = list(zip(self.ref_completions, self.ref_completions)) + if self.use_soft_judge: + ref_win_probs = self.judge.judge(prompts, completions, self.shuffle_order, return_scores=True) + winner_indices = [0 if score > 0.5 else 1 for score in ref_win_probs] + ref_win_probs = gather_object(ref_win_probs) + else: + winner_indices = self.judge.judge(prompts, completions, self.shuffle_order) + prompts = gather_object(prompts) + completions = gather_object(completions) + winner_indices = gather_object(winner_indices) + + # Logging + if self.trainer.accelerator.is_main_process: + win_rate = sum(winner_idx == 1 for winner_idx in winner_indices) / len(winner_indices) + if self.use_soft_judge: + avg_win_prob = 1.0 - sum(ref_win_probs) / len(ref_win_probs) + self.trainer.log({"eval_avg_win_prob": avg_win_prob, "eval_win_rate": win_rate}) + else: + self.trainer.log({"eval_win_rate": win_rate}) + + if "wandb" in args.report_to: + import wandb + + if wandb.run is not None: + global_step = [str(state.global_step)] * len(prompts) + data = list(zip(global_step, prompts, completions, winner_indices)) + # Split completions from referenece model and policy + split_data = [(item[0], item[1], item[2][0], item[2][1], item[3]) for item in data] + df = pd.DataFrame( + split_data, columns=["step", "prompt", "reference_model", "policy", "winner_index"] + ) + wandb.log({"win_rate_completions": wandb.Table(dataframe=df)}) + + def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): + # At every evaluation step, we generate completions for the model and compare them with the reference + # completions that have been generated at the beginning of training. We then compute the win rate and log it to + # the trainer. + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + model = self.trainer.model_wrapped + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + completions = _generate_completions( + prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + + completions = list(zip(self.ref_completions, completions)) + + if self.use_soft_judge: + ref_win_probs = self.judge.judge(prompts, completions, self.shuffle_order, return_scores=True) + winner_indices = [0 if score > 0.5 else 1 for score in ref_win_probs] + ref_win_probs = gather_object(ref_win_probs) + else: + winner_indices = self.judge.judge(prompts, completions, self.shuffle_order) + prompts = gather_object(prompts) + completions = gather_object(completions) + winner_indices = gather_object(winner_indices) + + # Logging + if self.trainer.accelerator.is_main_process: + win_rate = sum(winner_idx == 1 for winner_idx in winner_indices) / len(winner_indices) + if self.use_soft_judge: + avg_win_prob = 1.0 - sum(ref_win_probs) / len(ref_win_probs) + self.trainer.log({"eval_avg_win_prob": avg_win_prob, "eval_win_rate": win_rate}) + else: + self.trainer.log({"eval_win_rate": win_rate}) + + if "wandb" in args.report_to: + import wandb + + if wandb.run is not None: + global_step = [str(state.global_step)] * len(prompts) + data = list(zip(global_step, prompts, completions, winner_indices)) + # Split completions from referenece model and policy + split_data = [(item[0], item[1], item[2][0], item[2][1], item[3]) for item in data] + df = pd.DataFrame( + split_data, columns=["step", "prompt", "reference_model", "policy", "winner_index"] + ) + wandb.log({"win_rate_completions": wandb.Table(dataframe=df)}) + + +class LogCompletionsCallback(WandbCallback): + r""" + A [`~transformers.TrainerCallback`] that logs completions to Weights & Biases. + + Usage: + ```python + trainer = DPOTrainer(...) + completions_callback = LogCompletionsCallback(trainer=trainer) + trainer.add_callback(completions_callback) + ``` + + Args: + trainer (`Trainer`): + Trainer to which the callback will be attached. The trainer's evaluation dataset must include a `"prompt"` + column containing the prompts for generating completions. + generation_config (`GenerationConfig`, *optional*): + The generation config to use for generating completions. + num_prompts (`int` or `None`, *optional*): + The number of prompts to generate completions for. If not provided, defaults to the number of examples in the evaluation dataset. + freq (`int` or `None`, *optional*): + The frequency at which to log completions. If not provided, defaults to the trainer's `eval_steps`. + """ + + def __init__( + self, + trainer: Trainer, + generation_config: Optional[GenerationConfig] = None, + num_prompts: Optional[int] = None, + freq: Optional[int] = None, + ): + super().__init__() + self.trainer = trainer + self.generation_config = generation_config + self.freq = freq + self.table = [] + self._last_logged_step = -1 + + if self.trainer.eval_dataset is None: + raise ValueError("Trainer must have an evaluation dataset to use the LogCompletionsCallback.") + else: + self.eval_dataset = self.trainer.eval_dataset + + if num_prompts is not None: + self.eval_dataset = self.eval_dataset.select(range(num_prompts)) + + def on_step_end(self, args, state, control, **kwargs): + # Only log once per step (this method may be called multiple times) + if state.global_step == self._last_logged_step: + return + + # Only log every `freq` steps (if no `freq` is provided, log every `eval_steps` steps) + freq = self.freq or state.eval_steps + if state.global_step % freq != 0: + return + + tokenizer = kwargs["processing_class"] + tokenizer.padding_side = "left" + accelerator = self.trainer.accelerator + model = self.trainer.model_wrapped + with accelerator.split_between_processes(self.eval_dataset["prompt"]) as prompts: + prompts = [maybe_apply_chat_template({"prompt": prompt}, tokenizer)["prompt"] for prompt in prompts] + completions = _generate_completions( + prompts, + model=model, + tokenizer=tokenizer, + accelerator=accelerator, + generation_config=self.generation_config, + batch_size=args.per_device_eval_batch_size, + ) + completions = gather_object(completions) + prompts = gather_object(prompts) + + # Build the data to log + if self.trainer.accelerator.is_main_process: + global_step = [str(state.global_step)] * len(prompts) + data = list(zip(global_step, prompts, completions)) + self.table.extend(data) + table = self._wandb.Table(columns=["step", "prompt", "completion"], data=self.table) + self._wandb.log({"completions": table}) + + # Save the last logged step, so we don't log the same completions multiple times + self._last_logged_step = state.global_step diff --git a/testbed/huggingface__trl/trl/trainer/cpo_config.py b/testbed/huggingface__trl/trl/trainer/cpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ac45b203e5c75182959e8c3146f2da091daee964 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/cpo_config.py @@ -0,0 +1,96 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Literal, Optional + +from transformers import TrainingArguments + + +@dataclass +class CPOConfig(TrainingArguments): + r""" + Configuration class for the [`CPOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + learning_rate (`float`, *optional*, defaults to `1e-6`): + Initial learning rate for [`AdamW`] optimizer. The default value replaces that of + [`~transformers.TrainingArguments`]. + max_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_prompt_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the prompt. This argument is required if you want to use the default data collator. + max_completion_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). + label_smoothing (`float`, *optional*, defaults to `0.0`): + Label smoothing factor. This argument is required if you want to use the default data collator. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"hinge"`: hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + - `"simpo"`: SimPO loss from the [SimPO](https://huggingface.co/papers/2405.14734) paper. + + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + cpo_alpha (`float`, *optional*, defaults to `1.0`): + Weight of the BC regularizer in CPO training. + simpo_gamma (`float`, *optional*, defaults to `0.5`): + Target reward margin for the SimPO loss, used only when the `loss_type="simpo"`. + label_pad_token_id (`int`, *optional*, defaults to `-100`): + Label pad token id. This argument is required if you want to use the default data collator. + padding_value (`Optional[int]`, *optional*, defaults to `None`): + Padding value to use. If `None`, the padding value of the tokenizer is used. + truncation_mode (`str`,*optional*, defaults to `"keep_end"`): + Truncation mode to use when the prompt is too long. Possible values are `"keep_end"` or `"keep_start"`. + This argument is required if you want to use the default data collator. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from the model to W&B during evaluation. + is_encoder_decoder (`Optional[bool]`, *optional*, defaults to `None`): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + """ + + learning_rate: float = 1e-6 + max_length: Optional[int] = None + max_prompt_length: Optional[int] = None + max_completion_length: Optional[int] = None + beta: float = 0.1 + label_smoothing: float = 0.0 + loss_type: Literal["sigmoid", "hinge", "ipo", "simpo"] = "sigmoid" + disable_dropout: bool = True + cpo_alpha: float = 1.0 + simpo_gamma: float = 0.5 + label_pad_token_id: int = -100 + padding_value: Optional[int] = None + truncation_mode: str = "keep_end" + generate_during_eval: bool = False + is_encoder_decoder: Optional[bool] = None + model_init_kwargs: Optional[Dict[str, Any]] = None + dataset_num_proc: Optional[int] = None diff --git a/testbed/huggingface__trl/trl/trainer/cpo_trainer.py b/testbed/huggingface__trl/trl/trainer/cpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e5fcef01db04e8b0fa2acc7ae26270259c3651e1 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/cpo_trainer.py @@ -0,0 +1,1059 @@ +# CPO Authors: Haoran Xu, Amr Sharaf, Yunmo Chen, Weiting Tan, Lingfeng Shen, Benjamin Van Durme, Kenton Murray, Young Jin Kim +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import os +import random +import textwrap +import warnings +from collections import defaultdict +from contextlib import nullcontext +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union + +import numpy as np +import torch +import torch.amp as amp +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + is_wandb_available, +) +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available, is_torch_fx_proxy +from transformers.utils.deprecation import deprecate_kwarg + +from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt +from .cpo_config import CPOConfig +from .utils import ( + DPODataCollatorWithPadding, + add_bos_token_if_needed, + add_eos_token_if_needed, + disable_dropout_in_model, + generate_model_card, + pad_to_length, + peft_module_casting_to_bf16, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + + +class CPOTrainer(Trainer): + r""" + Initialize CPOTrainer. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForSequenceClassification`. + args (`CPOConfig`): + The CPO config arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Dict`, defaults to `None`): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + """ + + _tag_names = ["trl", "cpo"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.14.0", raise_if_both_names=True) + def __init__( + self, + model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + args: Optional[CPOConfig] = None, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None, + ): + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the CPOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + torch_dtype = model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the CPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + model_init_kwargs["torch_dtype"] = torch_dtype + + if isinstance(model, str): + warnings.warn( + "You passed a model_id to the CPOTrainer. This will automatically create an " + "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you." + ) + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + + if not is_peft_available() and peft_config is not None: + raise ValueError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + # if model is a peft model and we have a peft_config, we merge and unload it first + if isinstance(model, PeftModel): + model = model.merge_and_unload() + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not is_wandb_available(): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases to be installed." + " Please install `wandb` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if self.is_encoder_decoder: + self.decoder_start_token_id = model.config.decoder_start_token_id + self.pad_token_id = model.config.pad_token_id + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a CPO dataset.") + if args.max_length is None: + warnings.warn( + "`max_length` is not set in the CPOConfig's init" + " it will default to `512` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_length = 512 + else: + max_length = args.max_length + if args.max_prompt_length is None: + warnings.warn( + "`max_prompt_length` is not set in the CPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_prompt_length = 128 + else: + max_prompt_length = args.max_prompt_length + + if args.max_completion_length is None and self.is_encoder_decoder: + warnings.warn( + "When using an encoder decoder architecture, you should set `max_completion_length` in the CPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_completion_length = 128 + else: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + label_pad_token_id=args.label_pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" + " we have set it for you, but you should do it yourself in the future.", + UserWarning, + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + if args.disable_dropout: + disable_dropout_in_model(model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.label_pad_token_id = args.label_pad_token_id + self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id + self.max_prompt_length = max_prompt_length + self.truncation_mode = args.truncation_mode + self.max_completion_length = max_completion_length + self.processing_class = processing_class + + if args.loss_type in ["hinge", "ipo"] and args.label_smoothing > 0: + warnings.warn( + "You are using a loss type that does not support label smoothing. Ignoring label_smoothing parameter." + ) + if args.loss_type == "kto_pair": + raise ValueError("Support for kto_pair has been removed in CPOTrainer. Please use KTOTrainer.") + + self.beta = args.beta + self.label_smoothing = args.label_smoothing + self.loss_type = args.loss_type + self.cpo_alpha = args.cpo_alpha + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + warnings.warn( + "You set `output_router_logits` to True in the model config, but `router_aux_loss_coef` is set to 0.0," + " meaning the auxiliary loss will not be used." + ) + + if args.loss_type == "simpo": + self.simpo_gamma = args.simpo_gamma + if self.cpo_alpha > 0: + warnings.warn( + "You are using CPO-SimPO method because you set a non-zero cpo_alpha. " + "This will result in the CPO-SimPO method " + "(https://github.com/fe1ixxu/CPO_SIMPO/tree/main). " + "If you want to use a pure SimPO method, please set cpo_alpha to 0." + ) + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().local_main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + train_dataset = train_dataset.map( + maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + ) + + # tokenize the dataset + train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + def build_tokenized_answer(self, prompt, answer): + """ + Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. + It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`. + Reference: + https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + """ + + full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) + prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] + + answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] + answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) + + # Prepare input tokens for token by token comparison + full_input_ids = np.array(full_tokenized["input_ids"]) + + if len(full_input_ids) != len(full_concat_input_ids): + raise ValueError("Prompt input ids and answer input ids should have the same length.") + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = len(prompt_input_ids) + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: + response_token_ids_start_idx -= 1 + + prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] + prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] + + if len(prompt_input_ids) != len(prompt_attention_mask): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] + answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] + + return dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + input_ids=answer_input_ids, + attention_mask=answer_attention_mask, + ) + + def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> Dict: + """Tokenize a single row from a CPO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation + in case the prompt + chosen or prompt + rejected responses is/are too long. First + we truncate the prompt; if we're still too long, we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to + the sum of the length of the prompt and the chosen/rejected response, with + label_pad_token_id for the prompt tokens. + """ + batch = {} + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + + if not self.is_encoder_decoder: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + prompt_tokens = self.processing_class(prompt, add_special_tokens=False) + prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} + + if not isinstance(chosen, str): + raise ValueError(f"chosen should be an str but got {type(chosen)}") + chosen_tokens = self.build_tokenized_answer(prompt, chosen) + + if not isinstance(rejected, str): + raise ValueError(f"rejected should be an str but got {type(rejected)}") + rejected_tokens = self.build_tokenized_answer(prompt, rejected) + + # Last prompt token might get merged by tokenizer and + # it should not be included for generation if that happens + prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) + + chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) + rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) + prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) + + for k, v in prompt_tokens.items(): + prompt_tokens[k] = v[:prompt_len_input_ids] + + # Make sure prompts only have one different token at most an + # and length only differs by 1 at most + num_diff_tokens = sum( + [a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])] + ) + num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) + if num_diff_tokens > 1 or num_diff_len > 1: + raise ValueError( + "Chosen and rejected prompt_input_ids might only differ on the " + "last token due to tokenizer merge ops." + ) + + # add BOS token to head of prompt. Avoid adding if it's already there + prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( + self.processing_class.bos_token_id, + prompt_len_input_ids, + prompt_tokens, + chosen_prompt_len_input_ids, + chosen_tokens, + rejected_prompt_len_input_ids, + rejected_tokens, + ) + + # add EOS token to end of answer. Avoid adding if it's already there + chosen_tokens, rejected_tokens = add_eos_token_if_needed( + self.processing_class.eos_token_id, chosen_tokens, rejected_tokens + ) + + longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) + + # if combined sequence is too long, truncate the prompt + for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + if self.truncation_mode == "keep_start": + for k in ["prompt_input_ids", "prompt_attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_prompt_length] + elif self.truncation_mode == "keep_end": + for k in ["prompt_input_ids", "prompt_attention_mask"]: + answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :] + else: + raise ValueError(f"Unknown truncation mode: {self.truncation_mode}") + + # if that's still too long, truncate the response + for answer_tokens in [chosen_tokens, rejected_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + for k in ["input_ids", "attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length] + + # Create labels + chosen_sequence_tokens = { + k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] + } + rejected_sequence_tokens = { + k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] + } + chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] + chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [ + self.label_pad_token_id + ] * len(chosen_tokens["prompt_input_ids"]) + rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] + rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [ + self.label_pad_token_id + ] * len(rejected_tokens["prompt_input_ids"]) + + for k, toks in { + "chosen_": chosen_sequence_tokens, + "rejected_": rejected_sequence_tokens, + "": prompt_tokens, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}{type_key}"] = tokens + + else: + chosen_tokens = self.processing_class( + chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + rejected_tokens = self.processing_class( + rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + prompt_tokens = self.processing_class( + prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True + ) + + batch["chosen_labels"] = chosen_tokens["input_ids"] + batch["rejected_labels"] = rejected_tokens["input_ids"] + batch["prompt_input_ids"] = prompt_tokens["input_ids"] + batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] + + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["rejected_labels"]) + ) + batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["chosen_labels"]) + ) + + return batch + + @staticmethod + def concatenated_inputs( + batch: Dict[str, Union[List, torch.LongTensor]], + is_encoder_decoder: bool = False, + label_pad_token_id: int = -100, + padding_value: int = 0, + device: Optional[torch.device] = None, + ) -> Dict[str, torch.LongTensor]: + """Concatenate the chosen and rejected inputs into a single tensor. + + Args: + batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). + is_encoder_decoder: Whether the model is an encoder-decoder model. + label_pad_token_id: The label pad token id. + padding_value: The padding value to use for the concatenated inputs_ids. + device: The device for the concatenated inputs. + + Returns: + A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. + """ + concatenated_batch = {} + + if is_encoder_decoder: + max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) + else: + max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + + for k in batch: + if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = label_pad_token_id + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("chosen", "concatenated") + concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) + for k in batch: + if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = label_pad_token_id + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("rejected", "concatenated") + concatenated_batch[concatenated_key] = torch.cat( + ( + concatenated_batch[concatenated_key], + pad_to_length(batch[k], max_length, pad_value=pad_value), + ), + dim=0, + ).to(device=device) + + if is_encoder_decoder: + concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) + concatenated_batch["concatenated_attention_mask"] = ( + batch["prompt_attention_mask"].repeat(2, 1).to(device=device) + ) + + return concatenated_batch + + def cpo_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the CPO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) + policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) + + Returns: + A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). + The losses tensor contains the CPO loss for each example in the batch. + The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. + """ + logits = (policy_chosen_logps - policy_rejected_logps).to(self.accelerator.device) + + # The beta is a temperature parameter for the CPO loss, typically something in the range of 0.1 to 0.5. + # We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and + # calculates a conservative CPO loss. + + if self.loss_type == "simpo": + gamma_logratios = self.simpo_gamma / self.beta + logits = logits - gamma_logratios + # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + elif self.loss_type == "sigmoid": + # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + elif self.loss_type == "hinge": + losses = torch.relu(1 - self.beta * logits) + elif self.loss_type == "ipo": + # eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper. + losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise ValueError( + f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'simpo']" + ) + + chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() + rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() + + return losses, chosen_rewards, rejected_rewards + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + label_pad_token_id: int = -100, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) + average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. + label_pad_token_id: The label pad token id. + is_encoder_decoder: Whether the model is an encoder-decoder model. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + loss_mask = labels != label_pad_token_id + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == label_pad_token_id] = 0 + + per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def concatenated_forward( + self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]] + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + concatenated_batch = self.concatenated_inputs( + batch, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + padding_value=self.padding_value, + device=self.accelerator.device, + ) + len_chosen = batch["chosen_labels"].shape[0] + + model_kwargs = ( + { + "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), + } + if self.is_encoder_decoder + else {} + ) + + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + concatenated_batch["concatenated_input_ids"], + attention_mask=concatenated_batch["concatenated_attention_mask"], + use_cache=False, + **model_kwargs, + ) + all_logits = outputs.logits + + def cross_entropy_loss(logits, labels): + if not self.is_encoder_decoder: + # Shift so that tokens < n predict n + logits = logits[..., :-1, :].contiguous() + labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + logits = logits.view(-1, logits.shape[-1]) + labels = labels.view(-1) + # Enable model parallelism + labels = labels.to(logits.device) + loss = loss_fct(logits, labels) + return loss + + labels = concatenated_batch["concatenated_labels"].clone() + + if self.cpo_alpha == 0: + nll_loss = torch.tensor(0.0).to(self.accelerator.device) + else: + nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) + + all_logps = self.get_batch_logps( + all_logits, + concatenated_batch["concatenated_labels"], + average_log_prob=self.loss_type in ["ipo", "simpo"], + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + + chosen_logps = all_logps[:len_chosen] + rejected_logps = all_logps[len_chosen:] + + chosen_logits = all_logits[:len_chosen] + rejected_logits = all_logits[len_chosen:] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss, outputs.aux_loss) + + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss) + + def get_batch_loss_metrics( + self, + model, + batch: Dict[str, Union[List, torch.LongTensor]], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the CPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + forward_output = self.concatenated_forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_nll_loss, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + losses, chosen_rewards, rejected_rewards = self.cpo_loss( + policy_chosen_logps, + policy_rejected_logps, + ) + + loss = losses.mean() + self.cpo_alpha * policy_nll_loss + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean().cpu() + metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean().cpu() + metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean().cpu() + metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean().cpu() + metrics[f"{prefix}logps/rejected"] = policy_rejected_logps.detach().mean().cpu() + metrics[f"{prefix}logps/chosen"] = policy_chosen_logps.detach().mean().cpu() + metrics[f"{prefix}logits/rejected"] = policy_rejected_logits.detach().mean().cpu() + metrics[f"{prefix}logits/chosen"] = policy_chosen_logits.detach().mean().cpu() + metrics[f"{prefix}nll_loss"] = policy_nll_loss.detach().mean().cpu() + + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + return_outputs=False, + num_items_in_batch=None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: + if not self.use_dpo_data_collator: + warnings.warn( + "compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + + compute_loss_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def generate_from_model(self, model, batch: Dict[str, torch.LongTensor]) -> str: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch cuda amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + return policy_output_decoded + + def prediction_step( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + prediction_loss_only: bool, + ignore_keys: Optional[List[str]] = None, + ): + if not self.use_dpo_data_collator: + warnings.warn( + "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys) + logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: Optional[bool] = None, + ignore_keys: Optional[List[str]] = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. + Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded = self.generate_from_model(self.model, random_batch) + + self.log( + { + "game_log": wandb.Table( + columns=["Prompt", "Policy"], + rows=[ + [prompt, pol[len(prompt) :]] + for prompt, pol in zip(random_batch["prompt"], policy_output_decoded) + ], + ) + } + ) + self.state.log_history.pop() + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: Dict[str, float]) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`Dict[str, float]`): + The values to log. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs) + + def _shift_right(self, input_ids): + if self.decoder_start_token_id is None: + raise ValueError( + "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." + ) + + # shift inputs to the right + if is_torch_fx_proxy(input_ids): + # Item assignment is not supported natively for proxies. + shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) + shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) + else: + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() + shifted_input_ids[..., 0] = self.decoder_start_token_id + + if self.pad_token_id is None: + raise ValueError("model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) + + return shifted_input_ids + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @inproceedings{xu2024contrastive, + title = {{Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation}}, + author = {Haoran Xu and Amr Sharaf and Yunmo Chen and Weiting Tan and Lingfeng Shen and Benjamin Van Durme and Kenton Murray and Young Jin Kim}, + year = 2024, + booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=51iwkioZpn} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="CPO", + trainer_citation=citation, + paper_title="Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation", + paper_id="2401.08417", + ) + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/ddpo_config.py b/testbed/huggingface__trl/trl/trainer/ddpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff42312a663a14dee36a1ff838d05b863d0ec45 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/ddpo_config.py @@ -0,0 +1,182 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional + +from transformers import is_bitsandbytes_available, is_torchvision_available + +from ..core import flatten_dict + + +@dataclass +class DDPOConfig: + r""" + Configuration class for the [`DDPOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + exp_name (`str`, *optional*, defaults to `os.path.basename(sys.argv[0])[: -len(".py")]`): + Name of this experiment (by default is the file name without the extension name). + run_name (`str`, *optional*, defaults to `""`): + Name of this run. + seed (`int`, *optional*, defaults to `0`): + Random seed. + log_with (`Optional[Literal["wandb", "tensorboard"]]`, *optional*, defaults to `None`): + Log with either 'wandb' or 'tensorboard', check + https://huggingface.co/docs/accelerate/usage_guides/tracking for more details. + tracker_kwargs (`Dict`, *optional*, defaults to `{}`): + Keyword arguments for the tracker (e.g. wandb_project). + accelerator_kwargs (`Dict`, *optional*, defaults to `{}`): + Keyword arguments for the accelerator. + project_kwargs (`Dict`, *optional*, defaults to `{}`): + Keyword arguments for the accelerator project config (e.g. `logging_dir`). + tracker_project_name (`str`, *optional*, defaults to `"trl"`): + Name of project to use for tracking. + logdir (`str`, *optional*, defaults to `"logs"`): + Top-level logging directory for checkpoint saving. + num_epochs (`int`, *optional*, defaults to `100`): + Number of epochs to train. + save_freq (`int`, *optional*, defaults to `1`): + Number of epochs between saving model checkpoints. + num_checkpoint_limit (`int`, *optional*, defaults to `5`): + Number of checkpoints to keep before overwriting old ones. + mixed_precision (`str`, *optional*, defaults to `"fp16"`): + Mixed precision training. + allow_tf32 (`bool`, *optional*, defaults to `True`): + Allow `tf32` on Ampere GPUs. + resume_from (`str`, *optional*, defaults to `""`): + Resume training from a checkpoint. + sample_num_steps (`int`, *optional*, defaults to `50`): + Number of sampler inference steps. + sample_eta (`float`, *optional*, defaults to `1.0`): + Eta parameter for the DDIM sampler. + sample_guidance_scale (`float`, *optional*, defaults to `5.0`): + Classifier-free guidance weight. + sample_batch_size (`int`, *optional*, defaults to `1`): + Batch size (per GPU) to use for sampling. + sample_num_batches_per_epoch (`int`, *optional*, defaults to `2`): + Number of batches to sample per epoch. + train_batch_size (`int`, *optional*, defaults to `1`): + Batch size (per GPU) to use for training. + train_use_8bit_adam (`bool`, *optional*, defaults to `False`): + Use 8bit Adam optimizer from bitsandbytes. + train_learning_rate (`float`, *optional*, defaults to `3e-4`): + Learning rate. + train_adam_beta1 (`float`, *optional*, defaults to `0.9`): + Adam beta1. + train_adam_beta2 (`float`, *optional*, defaults to `0.999`): + Adam beta2. + train_adam_weight_decay (`float`, *optional*, defaults to `1e-4`): + Adam weight decay. + train_adam_epsilon (`float`, *optional*, defaults to `1e-8`): + Adam epsilon. + train_gradient_accumulation_steps (`int`, *optional*, defaults to `1`): + Number of gradient accumulation steps. + train_max_grad_norm (`float`, *optional*, defaults to `1.0`): + Maximum gradient norm for gradient clipping. + train_num_inner_epochs (`int`, *optional*, defaults to `1`): + Number of inner epochs per outer epoch. + train_cfg (`bool`, *optional*, defaults to `True`): + Whether or not to use classifier-free guidance during training. + train_adv_clip_max (`float`, *optional*, defaults to `5.0`): + Clip advantages to the range. + train_clip_range (`float`, *optional*, defaults to `1e-4`): + PPO clip range. + train_timestep_fraction (`float`, *optional*, defaults to `1.0`): + Fraction of timesteps to train on. + per_prompt_stat_tracking (`bool`, *optional*, defaults to `False`): + Whether to track statistics for each prompt separately. + per_prompt_stat_tracking_buffer_size (`int`, *optional*, defaults to `16`): + Number of reward values to store in the buffer for each prompt. + per_prompt_stat_tracking_min_count (`int`, *optional*, defaults to `16`): + Minimum number of reward values to store in the buffer. + async_reward_computation (`bool`, *optional*, defaults to `False`): + Whether to compute rewards asynchronously. + max_workers (`int`, *optional*, defaults to `2`): + Maximum number of workers to use for async reward computation. + negative_prompts (`Optional[str]`, *optional*, defaults to `""`): + Comma-separated list of prompts to use as negative examples. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the final model checkpoint to the Hub. + """ + + exp_name: str = os.path.basename(sys.argv[0])[: -len(".py")] + run_name: str = "" + seed: int = 0 + log_with: Optional[Literal["wandb", "tensorboard"]] = None + tracker_kwargs: dict = field(default_factory=dict) + accelerator_kwargs: dict = field(default_factory=dict) + project_kwargs: dict = field(default_factory=dict) + tracker_project_name: str = "trl" + logdir: str = "logs" + num_epochs: int = 100 + save_freq: int = 1 + num_checkpoint_limit: int = 5 + mixed_precision: str = "fp16" + allow_tf32: bool = True + resume_from: str = "" + sample_num_steps: int = 50 + sample_eta: float = 1.0 + sample_guidance_scale: float = 5.0 + sample_batch_size: int = 1 + sample_num_batches_per_epoch: int = 2 + train_batch_size: int = 1 + train_use_8bit_adam: bool = False + train_learning_rate: float = 3e-4 + train_adam_beta1: float = 0.9 + train_adam_beta2: float = 0.999 + train_adam_weight_decay: float = 1e-4 + train_adam_epsilon: float = 1e-8 + train_gradient_accumulation_steps: int = 1 + train_max_grad_norm: float = 1.0 + train_num_inner_epochs: int = 1 + train_cfg: bool = True + train_adv_clip_max: float = 5.0 + train_clip_range: float = 1e-4 + train_timestep_fraction: float = 1.0 + per_prompt_stat_tracking: bool = False + per_prompt_stat_tracking_buffer_size: int = 16 + per_prompt_stat_tracking_min_count: int = 16 + async_reward_computation: bool = False + max_workers: int = 2 + negative_prompts: str = "" + push_to_hub: bool = False + + def to_dict(self): + output_dict = {} + for key, value in self.__dict__.items(): + output_dict[key] = value + return flatten_dict(output_dict) + + def __post_init__(self): + if self.log_with not in ["wandb", "tensorboard"]: + warnings.warn( + "Accelerator tracking only supports image logging if `log_with` is set to 'wandb' or 'tensorboard'." + ) + + if self.log_with == "wandb" and not is_torchvision_available(): + warnings.warn("Wandb image logging requires torchvision to be installed") + + if self.train_use_8bit_adam and not is_bitsandbytes_available(): + raise ImportError( + "You need to install bitsandbytes to use 8bit Adam. " + "You can install it with `pip install bitsandbytes`." + ) diff --git a/testbed/huggingface__trl/trl/trainer/ddpo_trainer.py b/testbed/huggingface__trl/trl/trainer/ddpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..412a461a30f350dc82b197219db076c2bdfa7077 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/ddpo_trainer.py @@ -0,0 +1,650 @@ +# Copyright 2023 DDPO-pytorch authors (Kevin Black), metric-space, The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import textwrap +from collections import defaultdict +from concurrent import futures +from typing import Any, Callable, List, Optional, Tuple, Union +from warnings import warn + +import torch +from accelerate import Accelerator +from accelerate.logging import get_logger +from accelerate.utils import ProjectConfiguration, set_seed +from transformers import is_wandb_available + +from ..models import DDPOStableDiffusionPipeline +from . import BaseTrainer, DDPOConfig +from .utils import PerPromptStatTracker, generate_model_card + + +if is_wandb_available(): + import wandb + + +logger = get_logger(__name__) + + +class DDPOTrainer(BaseTrainer): + """ + The DDPOTrainer uses Deep Diffusion Policy Optimization to optimise diffusion models. + Note, this trainer is heavily inspired by the work here: https://github.com/kvablack/ddpo-pytorch + As of now only Stable Diffusion based pipelines are supported + + Attributes: + **config** (`DDPOConfig`) -- Configuration object for DDPOTrainer. Check the documentation of `PPOConfig` for more + details. + **reward_function** (Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor]) -- Reward function to be used + **prompt_function** (Callable[[], Tuple[str, Any]]) -- Function to generate prompts to guide model + **sd_pipeline** (`DDPOStableDiffusionPipeline`) -- Stable Diffusion pipeline to be used for training. + **image_samples_hook** (Optional[Callable[[Any, Any, Any], Any]]) -- Hook to be called to log images + """ + + _tag_names = ["trl", "ddpo"] + + def __init__( + self, + config: DDPOConfig, + reward_function: Callable[[torch.Tensor, Tuple[str], Tuple[Any]], torch.Tensor], + prompt_function: Callable[[], Tuple[str, Any]], + sd_pipeline: DDPOStableDiffusionPipeline, + image_samples_hook: Optional[Callable[[Any, Any, Any], Any]] = None, + ): + if image_samples_hook is None: + warn("No image_samples_hook provided; no images will be logged") + + self.prompt_fn = prompt_function + self.reward_fn = reward_function + self.config = config + self.image_samples_callback = image_samples_hook + + accelerator_project_config = ProjectConfiguration(**self.config.project_kwargs) + + if self.config.resume_from: + self.config.resume_from = os.path.normpath(os.path.expanduser(self.config.resume_from)) + if "checkpoint_" not in os.path.basename(self.config.resume_from): + # get the most recent checkpoint in this directory + checkpoints = list( + filter( + lambda x: "checkpoint_" in x, + os.listdir(self.config.resume_from), + ) + ) + if len(checkpoints) == 0: + raise ValueError(f"No checkpoints found in {self.config.resume_from}") + checkpoint_numbers = sorted([int(x.split("_")[-1]) for x in checkpoints]) + self.config.resume_from = os.path.join( + self.config.resume_from, + f"checkpoint_{checkpoint_numbers[-1]}", + ) + + accelerator_project_config.iteration = checkpoint_numbers[-1] + 1 + + # number of timesteps within each trajectory to train on + self.num_train_timesteps = int(self.config.sample_num_steps * self.config.train_timestep_fraction) + + self.accelerator = Accelerator( + log_with=self.config.log_with, + mixed_precision=self.config.mixed_precision, + project_config=accelerator_project_config, + # we always accumulate gradients across timesteps; we want config.train.gradient_accumulation_steps to be the + # number of *samples* we accumulate across, so we need to multiply by the number of training timesteps to get + # the total number of optimizer steps to accumulate across. + gradient_accumulation_steps=self.config.train_gradient_accumulation_steps * self.num_train_timesteps, + **self.config.accelerator_kwargs, + ) + + is_okay, message = self._config_check() + if not is_okay: + raise ValueError(message) + + is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard" + + if self.accelerator.is_main_process: + self.accelerator.init_trackers( + self.config.tracker_project_name, + config=dict(ddpo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(), + init_kwargs=self.config.tracker_kwargs, + ) + + logger.info(f"\n{config}") + + set_seed(self.config.seed, device_specific=True) + + self.sd_pipeline = sd_pipeline + + self.sd_pipeline.set_progress_bar_config( + position=1, + disable=not self.accelerator.is_local_main_process, + leave=False, + desc="Timestep", + dynamic_ncols=True, + ) + + # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision + # as these weights are only used for inference, keeping weights in full precision is not required. + if self.accelerator.mixed_precision == "fp16": + inference_dtype = torch.float16 + elif self.accelerator.mixed_precision == "bf16": + inference_dtype = torch.bfloat16 + else: + inference_dtype = torch.float32 + + self.sd_pipeline.vae.to(self.accelerator.device, dtype=inference_dtype) + self.sd_pipeline.text_encoder.to(self.accelerator.device, dtype=inference_dtype) + self.sd_pipeline.unet.to(self.accelerator.device, dtype=inference_dtype) + + trainable_layers = self.sd_pipeline.get_trainable_layers() + + self.accelerator.register_save_state_pre_hook(self._save_model_hook) + self.accelerator.register_load_state_pre_hook(self._load_model_hook) + + # Enable TF32 for faster training on Ampere GPUs, + # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices + if self.config.allow_tf32: + torch.backends.cuda.matmul.allow_tf32 = True + + self.optimizer = self._setup_optimizer( + trainable_layers.parameters() if not isinstance(trainable_layers, list) else trainable_layers + ) + + self.neg_prompt_embed = self.sd_pipeline.text_encoder( + self.sd_pipeline.tokenizer( + [""] if self.config.negative_prompts is None else self.config.negative_prompts, + return_tensors="pt", + padding="max_length", + truncation=True, + max_length=self.sd_pipeline.tokenizer.model_max_length, + ).input_ids.to(self.accelerator.device) + )[0] + + if config.per_prompt_stat_tracking: + self.stat_tracker = PerPromptStatTracker( + config.per_prompt_stat_tracking_buffer_size, + config.per_prompt_stat_tracking_min_count, + ) + + # NOTE: for some reason, autocast is necessary for non-lora training but for lora training it isn't necessary and it uses + # more memory + self.autocast = self.sd_pipeline.autocast or self.accelerator.autocast + + if hasattr(self.sd_pipeline, "use_lora") and self.sd_pipeline.use_lora: + unet, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer) + self.trainable_layers = list(filter(lambda p: p.requires_grad, unet.parameters())) + else: + self.trainable_layers, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer) + + if self.config.async_reward_computation: + self.executor = futures.ThreadPoolExecutor(max_workers=config.max_workers) + + if config.resume_from: + logger.info(f"Resuming from {config.resume_from}") + self.accelerator.load_state(config.resume_from) + self.first_epoch = int(config.resume_from.split("_")[-1]) + 1 + else: + self.first_epoch = 0 + + def compute_rewards(self, prompt_image_pairs, is_async=False): + if not is_async: + rewards = [] + for images, prompts, prompt_metadata in prompt_image_pairs: + reward, reward_metadata = self.reward_fn(images, prompts, prompt_metadata) + rewards.append( + ( + torch.as_tensor(reward, device=self.accelerator.device), + reward_metadata, + ) + ) + else: + rewards = self.executor.map(lambda x: self.reward_fn(*x), prompt_image_pairs) + rewards = [ + (torch.as_tensor(reward.result(), device=self.accelerator.device), reward_metadata.result()) + for reward, reward_metadata in rewards + ] + + return zip(*rewards) + + def step(self, epoch: int, global_step: int): + """ + Perform a single step of training. + + Args: + epoch (int): The current epoch. + global_step (int): The current global step. + + Side Effects: + - Model weights are updated + - Logs the statistics to the accelerator trackers. + - If `self.image_samples_callback` is not None, it will be called with the prompt_image_pairs, global_step, and the accelerator tracker. + + Returns: + global_step (int): The updated global step. + + """ + samples, prompt_image_data = self._generate_samples( + iterations=self.config.sample_num_batches_per_epoch, + batch_size=self.config.sample_batch_size, + ) + + # collate samples into dict where each entry has shape (num_batches_per_epoch * sample.batch_size, ...) + samples = {k: torch.cat([s[k] for s in samples]) for k in samples[0].keys()} + rewards, rewards_metadata = self.compute_rewards( + prompt_image_data, is_async=self.config.async_reward_computation + ) + + for i, image_data in enumerate(prompt_image_data): + image_data.extend([rewards[i], rewards_metadata[i]]) + + if self.image_samples_callback is not None: + self.image_samples_callback(prompt_image_data, global_step, self.accelerator.trackers[0]) + + rewards = torch.cat(rewards) + rewards = self.accelerator.gather(rewards).cpu().numpy() + + self.accelerator.log( + { + "reward": rewards, + "epoch": epoch, + "reward_mean": rewards.mean(), + "reward_std": rewards.std(), + }, + step=global_step, + ) + + if self.config.per_prompt_stat_tracking: + # gather the prompts across processes + prompt_ids = self.accelerator.gather(samples["prompt_ids"]).cpu().numpy() + prompts = self.sd_pipeline.tokenizer.batch_decode(prompt_ids, skip_special_tokens=True) + advantages = self.stat_tracker.update(prompts, rewards) + else: + advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8) + + # ungather advantages; keep the entries corresponding to the samples on this process + samples["advantages"] = ( + torch.as_tensor(advantages) + .reshape(self.accelerator.num_processes, -1)[self.accelerator.process_index] + .to(self.accelerator.device) + ) + + del samples["prompt_ids"] + + total_batch_size, num_timesteps = samples["timesteps"].shape + + for inner_epoch in range(self.config.train_num_inner_epochs): + # shuffle samples along batch dimension + perm = torch.randperm(total_batch_size, device=self.accelerator.device) + samples = {k: v[perm] for k, v in samples.items()} + + # shuffle along time dimension independently for each sample + # still trying to understand the code below + perms = torch.stack( + [torch.randperm(num_timesteps, device=self.accelerator.device) for _ in range(total_batch_size)] + ) + + for key in ["timesteps", "latents", "next_latents", "log_probs"]: + samples[key] = samples[key][ + torch.arange(total_batch_size, device=self.accelerator.device)[:, None], + perms, + ] + + original_keys = samples.keys() + original_values = samples.values() + # rebatch them as user defined train_batch_size is different from sample_batch_size + reshaped_values = [v.reshape(-1, self.config.train_batch_size, *v.shape[1:]) for v in original_values] + + # Transpose the list of original values + transposed_values = zip(*reshaped_values) + # Create new dictionaries for each row of transposed values + samples_batched = [dict(zip(original_keys, row_values)) for row_values in transposed_values] + + self.sd_pipeline.unet.train() + global_step = self._train_batched_samples(inner_epoch, epoch, global_step, samples_batched) + # ensure optimization step at the end of the inner epoch + if not self.accelerator.sync_gradients: + raise ValueError( + "Optimization step should have been performed by this point. Please check calculated gradient accumulation settings." + ) + + if epoch != 0 and epoch % self.config.save_freq == 0 and self.accelerator.is_main_process: + self.accelerator.save_state() + + return global_step + + def calculate_loss(self, latents, timesteps, next_latents, log_probs, advantages, embeds): + """ + Calculate the loss for a batch of an unpacked sample + + Args: + latents (torch.Tensor): + The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width] + timesteps (torch.Tensor): + The timesteps sampled from the diffusion model, shape: [batch_size] + next_latents (torch.Tensor): + The next latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width] + log_probs (torch.Tensor): + The log probabilities of the latents, shape: [batch_size] + advantages (torch.Tensor): + The advantages of the latents, shape: [batch_size] + embeds (torch.Tensor): + The embeddings of the prompts, shape: [2*batch_size or batch_size, ...] + Note: the "or" is because if train_cfg is True, the expectation is that negative prompts are concatenated to the embeds + + Returns: + loss (torch.Tensor), approx_kl (torch.Tensor), clipfrac (torch.Tensor) + (all of these are of shape (1,)) + """ + with self.autocast(): + if self.config.train_cfg: + noise_pred = self.sd_pipeline.unet( + torch.cat([latents] * 2), + torch.cat([timesteps] * 2), + embeds, + ).sample + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.config.sample_guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + else: + noise_pred = self.sd_pipeline.unet( + latents, + timesteps, + embeds, + ).sample + # compute the log prob of next_latents given latents under the current model + + scheduler_step_output = self.sd_pipeline.scheduler_step( + noise_pred, + timesteps, + latents, + eta=self.config.sample_eta, + prev_sample=next_latents, + ) + + log_prob = scheduler_step_output.log_probs + + advantages = torch.clamp( + advantages, + -self.config.train_adv_clip_max, + self.config.train_adv_clip_max, + ) + + ratio = torch.exp(log_prob - log_probs) + + loss = self.loss(advantages, self.config.train_clip_range, ratio) + + approx_kl = 0.5 * torch.mean((log_prob - log_probs) ** 2) + + clipfrac = torch.mean((torch.abs(ratio - 1.0) > self.config.train_clip_range).float()) + + return loss, approx_kl, clipfrac + + def loss( + self, + advantages: torch.Tensor, + clip_range: float, + ratio: torch.Tensor, + ): + unclipped_loss = -advantages * ratio + clipped_loss = -advantages * torch.clamp( + ratio, + 1.0 - clip_range, + 1.0 + clip_range, + ) + return torch.mean(torch.maximum(unclipped_loss, clipped_loss)) + + def _setup_optimizer(self, trainable_layers_parameters): + if self.config.train_use_8bit_adam: + import bitsandbytes + + optimizer_cls = bitsandbytes.optim.AdamW8bit + else: + optimizer_cls = torch.optim.AdamW + + return optimizer_cls( + trainable_layers_parameters, + lr=self.config.train_learning_rate, + betas=(self.config.train_adam_beta1, self.config.train_adam_beta2), + weight_decay=self.config.train_adam_weight_decay, + eps=self.config.train_adam_epsilon, + ) + + def _save_model_hook(self, models, weights, output_dir): + self.sd_pipeline.save_checkpoint(models, weights, output_dir) + weights.pop() # ensures that accelerate doesn't try to handle saving of the model + + def _load_model_hook(self, models, input_dir): + self.sd_pipeline.load_checkpoint(models, input_dir) + models.pop() # ensures that accelerate doesn't try to handle loading of the model + + def _generate_samples(self, iterations, batch_size): + """ + Generate samples from the model + + Args: + iterations (int): Number of iterations to generate samples for + batch_size (int): Batch size to use for sampling + + Returns: + samples (List[Dict[str, torch.Tensor]]), prompt_image_pairs (List[List[Any]]) + """ + samples = [] + prompt_image_pairs = [] + self.sd_pipeline.unet.eval() + + sample_neg_prompt_embeds = self.neg_prompt_embed.repeat(batch_size, 1, 1) + + for _ in range(iterations): + prompts, prompt_metadata = zip(*[self.prompt_fn() for _ in range(batch_size)]) + + prompt_ids = self.sd_pipeline.tokenizer( + prompts, + return_tensors="pt", + padding="max_length", + truncation=True, + max_length=self.sd_pipeline.tokenizer.model_max_length, + ).input_ids.to(self.accelerator.device) + prompt_embeds = self.sd_pipeline.text_encoder(prompt_ids)[0] + + with self.autocast(): + sd_output = self.sd_pipeline( + prompt_embeds=prompt_embeds, + negative_prompt_embeds=sample_neg_prompt_embeds, + num_inference_steps=self.config.sample_num_steps, + guidance_scale=self.config.sample_guidance_scale, + eta=self.config.sample_eta, + output_type="pt", + ) + + images = sd_output.images + latents = sd_output.latents + log_probs = sd_output.log_probs + + latents = torch.stack(latents, dim=1) # (batch_size, num_steps + 1, ...) + log_probs = torch.stack(log_probs, dim=1) # (batch_size, num_steps, 1) + timesteps = self.sd_pipeline.scheduler.timesteps.repeat(batch_size, 1) # (batch_size, num_steps) + + samples.append( + { + "prompt_ids": prompt_ids, + "prompt_embeds": prompt_embeds, + "timesteps": timesteps, + "latents": latents[:, :-1], # each entry is the latent before timestep t + "next_latents": latents[:, 1:], # each entry is the latent after timestep t + "log_probs": log_probs, + "negative_prompt_embeds": sample_neg_prompt_embeds, + } + ) + prompt_image_pairs.append([images, prompts, prompt_metadata]) + + return samples, prompt_image_pairs + + def _train_batched_samples(self, inner_epoch, epoch, global_step, batched_samples): + """ + Train on a batch of samples. Main training segment + + Args: + inner_epoch (int): The current inner epoch + epoch (int): The current epoch + global_step (int): The current global step + batched_samples (List[Dict[str, torch.Tensor]]): The batched samples to train on + + Side Effects: + - Model weights are updated + - Logs the statistics to the accelerator trackers. + + Returns: + global_step (int): The updated global step + """ + info = defaultdict(list) + for _i, sample in enumerate(batched_samples): + if self.config.train_cfg: + # concat negative prompts to sample prompts to avoid two forward passes + embeds = torch.cat([sample["negative_prompt_embeds"], sample["prompt_embeds"]]) + else: + embeds = sample["prompt_embeds"] + + for j in range(self.num_train_timesteps): + with self.accelerator.accumulate(self.sd_pipeline.unet): + loss, approx_kl, clipfrac = self.calculate_loss( + sample["latents"][:, j], + sample["timesteps"][:, j], + sample["next_latents"][:, j], + sample["log_probs"][:, j], + sample["advantages"], + embeds, + ) + info["approx_kl"].append(approx_kl) + info["clipfrac"].append(clipfrac) + info["loss"].append(loss) + + self.accelerator.backward(loss) + if self.accelerator.sync_gradients: + self.accelerator.clip_grad_norm_( + self.trainable_layers.parameters() + if not isinstance(self.trainable_layers, list) + else self.trainable_layers, + self.config.train_max_grad_norm, + ) + self.optimizer.step() + self.optimizer.zero_grad() + + # Checks if the accelerator has performed an optimization step behind the scenes + if self.accelerator.sync_gradients: + # log training-related stuff + info = {k: torch.mean(torch.stack(v)) for k, v in info.items()} + info = self.accelerator.reduce(info, reduction="mean") + info.update({"epoch": epoch, "inner_epoch": inner_epoch}) + self.accelerator.log(info, step=global_step) + global_step += 1 + info = defaultdict(list) + return global_step + + def _config_check(self) -> Tuple[bool, str]: + samples_per_epoch = ( + self.config.sample_batch_size * self.accelerator.num_processes * self.config.sample_num_batches_per_epoch + ) + total_train_batch_size = ( + self.config.train_batch_size + * self.accelerator.num_processes + * self.config.train_gradient_accumulation_steps + ) + + if not self.config.sample_batch_size >= self.config.train_batch_size: + return ( + False, + f"Sample batch size ({self.config.sample_batch_size}) must be greater than or equal to the train batch size ({self.config.train_batch_size})", + ) + if not self.config.sample_batch_size % self.config.train_batch_size == 0: + return ( + False, + f"Sample batch size ({self.config.sample_batch_size}) must be divisible by the train batch size ({self.config.train_batch_size})", + ) + if not samples_per_epoch % total_train_batch_size == 0: + return ( + False, + f"Number of samples per epoch ({samples_per_epoch}) must be divisible by the total train batch size ({total_train_batch_size})", + ) + return True, "" + + def train(self, epochs: Optional[int] = None): + """ + Train the model for a given number of epochs + """ + global_step = 0 + if epochs is None: + epochs = self.config.num_epochs + for epoch in range(self.first_epoch, epochs): + global_step = self.step(epoch, global_step) + + def _save_pretrained(self, save_directory): + self.sd_pipeline.save_pretrained(save_directory) + self.create_model_card() + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @inproceedings{black2024training, + title = {{Training Diffusion Models with Reinforcement Learning}}, + author = {Kevin Black and Michael Janner and Yilun Du and Ilya Kostrikov and Sergey Levine}, + year = 2024, + booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=YCWjhGrJFD}, + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="DDPO", + trainer_citation=citation, + paper_title="Training Diffusion Models with Reinforcement Learning", + paper_id="2305.13301", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/dpo_config.py b/testbed/huggingface__trl/trl/trainer/dpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..964b29bbe753b739df698e59df0891c98bc14bba --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/dpo_config.py @@ -0,0 +1,201 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import warnings +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict, Literal, Optional + +from transformers import TrainingArguments + + +class FDivergenceType(Enum): + REVERSE_KL = "reverse_kl" + JS_DIVERGENCE = "js_divergence" + ALPHA_DIVERGENCE = "alpha_divergence" + + +class FDivergenceConstants: + ALPHA_DIVERGENCE_COEF_KEY = "alpha_divergence_coef" + ALPHA_DIVERGENCE_COEF_DEFAULT = 1.0 + + +@dataclass +class DPOConfig(TrainingArguments): + r""" + Configuration class for the [`DPOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + learning_rate (`float`, *optional*, defaults to `1e-6`): + Initial learning rate for [`AdamW`] optimizer. The default value replaces that of + [`~transformers.TrainingArguments`]. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). + label_smoothing (`float`, *optional*, defaults to `0.0`): + Robust DPO label smoothing parameter from the [cDPO](https://ericmitchell.ai/cdpo.pdf) report and + [Robust DPO](https://huggingface.co/papers/2403.00409) paper that should be between `0.0` and `0.5`. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"hinge"`: hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + - `"exo_pair"`: pairwise EXO loss from the [EXO](https://huggingface.co/papers/2402.00856) paper. + - `"nca_pair"`: pairwise NCA loss from the [NCA](https://huggingface.co/papers/2402.05369) paper. + - `"robust"`: unbiased estimate of the DPO loss that is robust to preference noise from the [Robust DPO](https://huggingface.co/papers/2403.00409) paper. + - `"bco_pair"`: pairwise BCO loss from the [BCO](https://huggingface.co/papers/2404.04656) paper. + - `"sppo_hard"`: SPPO loss with hard label from the [SPPO](https://huggingface.co/papers/2405.00675) paper. + - `"aot"`: AOT loss for paired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper. + - `"aot_pair"`: AOT loss for unpaired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper. + - `"discopop"`: DiscoPOP (a.k.a Log-Ratio Modulated Loss, LRML) loss from the [DiscoPOP](https://huggingface.co/papers/2406.08414) paper. + - `"apo_zero"`: APO-zero loss from the [APO](https://huggingface.co/papers/2408.06266) paper. + - `"apo_down"`: APO-down loss from the [APO](https://huggingface.co/papers/2408.06266) paper. + use_weighting (`bool`, *optional*, defaults to `False`): + Whether or not to weight the loss as done in the [WPO](https://huggingface.co/papers/2406.11827) paper. + label_pad_token_id (`int`, *optional*, defaults to `-100`): + Label pad token id. This argument is required if you want to use the default data collator. + padding_value (`Optional[int]`, *optional*, defaults to `None`): + Padding value to use. If `None`, the padding value of the tokenizer is used. + truncation_mode (`str`, *optional*, defaults to `"keep_end"`): + Truncation mode to use, either `keep_end` or `keep_start`. This argument is required if you want to use the + default data collator. + max_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_prompt_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the prompt. This argument is required if you want to use the default data collator. + max_completion_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the target. This argument is required if you want to use the default data collator and + your model is an encoder-decoder. + is_encoder_decoder(`Optional[int]`, *optional*, defaults to `None`): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model and reference model. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from both the model and the reference model to W&B during + evaluation. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute reference model log probabilities for training and evaluation datasets. This is + useful when training without the reference model to reduce the total GPU memory needed. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + ref_model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the reference model + from a string. + model_adapter_name (`Optional[str]`, *optional*, defaults to `None`): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`Optional[str]`, *optional*, defaults to `None`): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + reference_free (`bool`, *optional*, defaults to `False`): + If `True`, we ignore the _provided_ reference model and implicitly use a reference model that assigns equal + probability to all responses. + force_use_ref_model (`bool`, *optional*, defaults to `False`): + In case one passes a PEFT model for the active model and you want to use a different model for the + ref_model, set this flag to `True`. + f_divergence_type (`str`, *optional*, defaults to `FDivergenceType.REVERSE_KL`): + Type of f-divergence regularization function to compute divergence between policy and reference model. + f_alpha_divergence_coef (`float`, *optional*, defaults to `1.0`): + α coefficient in the α-divergence u^-α regularization function for DPO loss. + sync_ref_model (`bool`, *optional*, defaults to `False`): + When set to `True`, the reference model is synchronized with the active model every `ref_model_sync_steps` + steps, using the `ref_model_mixup_alpha` parameter. This synchronization originites from the + [TR-DPO](https://huggingface.co/papers/2404.09656) paper. + ref_model_mixup_alpha (`float`, *optional*, defaults to `0.9`): + α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix + between the current policy and the previous reference policy during updates. The reference policy is + updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev` + To use this parameter, you must set `sync_ref_model=True`. + ref_model_sync_steps (`int`, *optional*, defaults to `64`): + τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how + frequently the current policy is synchronized with the reference policy. To use this parameter, you must + set `sync_ref_model=True`. + rpo_alpha (`float`, *optional*, defaults to `None`): + α parameter from the [RPO](https://huggingface.co/papers/2404.19733) paper (v3), which controls the + weighting of the NLL term in the loss. If `None`, no weighting is applied and the loss is the same as the + DPO loss. The paper recommends `rpo_alpha=1.0`. + discopop_tau (`float`, *optional*, defaults to `0.05`): + τ/temperature parameter from the [DiscoPOP](https://huggingface.co/papers/2406.08414) paper, which controls + the shape of log ratio modulated loss. The paper recommends the default value `discopop_tau=0.05`. + use_num_logits_to_keep (`bool`, *optional*, defaults to `False`): + If `True`, only a specified number of logits are computed in the forward pass of CausalLM. This can be useful + for saving memory and speeding up training by not computing the logits for all tokens, especially in scenarios + when working with very long prompts where labels are -ignored (-100). + [Read more](https://huggingface.co/docs/transformers/main/model_doc/llama#transformers.LlamaForCausalLM) + """ + + learning_rate: float = 1e-6 + beta: float = 0.1 + label_smoothing: float = 0.0 + loss_type: Literal[ + "sigmoid", + "hinge", + "ipo", + "exo_pair", + "nca_pair", + "robust", + "bco_pair", + "sppo_hard", + "aot", + "aot_pair", + "discopop", + "apo_zero", + "apo_down", + ] = "sigmoid" + use_weighting: bool = False + label_pad_token_id: int = -100 + padding_value: Optional[int] = None + truncation_mode: str = "keep_end" + max_length: Optional[int] = None + max_prompt_length: Optional[int] = None + max_target_length: Optional[int] = None # deprecated in favor of max_completion_length + max_completion_length: Optional[int] = None + is_encoder_decoder: Optional[bool] = None + disable_dropout: bool = True + generate_during_eval: bool = False + precompute_ref_log_probs: bool = False + dataset_num_proc: Optional[int] = None + model_init_kwargs: Optional[Dict[str, Any]] = None + ref_model_init_kwargs: Optional[Dict[str, Any]] = None + model_adapter_name: Optional[str] = None + ref_adapter_name: Optional[str] = None + reference_free: bool = False + force_use_ref_model: bool = False + f_divergence_type: FDivergenceType = FDivergenceType.REVERSE_KL + f_alpha_divergence_coef: float = 1.0 + sync_ref_model: bool = False + ref_model_mixup_alpha: float = 0.9 + ref_model_sync_steps: int = 64 + rpo_alpha: Optional[float] = None + discopop_tau: float = 0.05 + use_num_logits_to_keep: bool = False + + def __post_init__(self): + if self.max_target_length is not None: + warnings.warn( + "The `max_target_length` argument is deprecated in favor of `max_completion_length` and will be removed in a future version.", + FutureWarning, + ) + if self.max_completion_length is None: + self.max_completion_length = self.max_target_length + + return super().__post_init__() diff --git a/testbed/huggingface__trl/trl/trainer/dpo_trainer.py b/testbed/huggingface__trl/trl/trainer/dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c699bce2eeb03fed512cc3f33673c102eb8f381b --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/dpo_trainer.py @@ -0,0 +1,1466 @@ +# DPO Authors: Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn 2023 +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import os +import random +import textwrap +import warnings +from collections import defaultdict +from contextlib import contextmanager, nullcontext +from copy import deepcopy +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union + +import torch +import torch.amp as amp +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from accelerate.utils import is_deepspeed_available, tqdm +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + is_wandb_available, +) +from transformers.data.data_collator import DataCollatorMixin +from transformers.models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available +from transformers.utils.deprecation import deprecate_kwarg + +from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt +from ..models import PreTrainedModelWrapper, create_reference_model +from .callbacks import SyncRefModelCallback +from .dpo_config import DPOConfig, FDivergenceConstants, FDivergenceType +from .utils import ( + RunningMoments, + cap_exp, + disable_dropout_in_model, + generate_model_card, + pad, + pad_to_length, + peft_module_casting_to_bf16, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + +if is_deepspeed_available(): + import deepspeed + + +@dataclass +class PreferenceCollator(DataCollatorMixin): + """ + Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch if they + are not all of the same length. + + Args: + pad_token_id (`int`): + Token ID to use for padding. + return_tensors (`str`, *optional*, defaults to `"pt"`): + Type of Tensor to return. Only `"pt"` is currently supported. + + Examples: + ```python + >>> from trl import PreferenceCollator + >>> collator = PreferenceCollator(pad_token_id=0) + >>> examples = [ + ... {"prompt_input_ids": [1, 2, 3], "chosen_input_ids": [4, 5], "rejected_input_ids": [6]}, + ... {"prompt_input_ids": [7, 8], "chosen_input_ids": [9, 10], "rejected_input_ids": [11, 12, 13]} + ... ] + >>> collator(examples) + {'prompt_input_ids': tensor([[1, 2, 3], + [0, 7, 8]]), + 'prompt_attention_mask': tensor([[1, 1, 1], + [0, 1, 1]]), + 'chosen_input_ids': tensor([[ 4, 5], + [ 9, 10]]), + 'chosen_attention_mask': tensor([[1, 1], + [1, 1]]), + 'rejected_input_ids': tensor([[ 6, 0, 0], + [11, 12, 13]]), + 'rejected_attention_mask': tensor([[1, 0, 0], + [1, 1, 1]]) + } + ``` + """ + + pad_token_id: int + return_tensors: str = "pt" + + def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]: + # Convert to tensor + prompt_input_ids = [torch.tensor(example["prompt_input_ids"]) for example in examples] + prompt_attention_mask = [torch.ones_like(input_ids) for input_ids in prompt_input_ids] + chosen_input_ids = [torch.tensor(example["chosen_input_ids"]) for example in examples] + chosen_attention_mask = [torch.ones_like(input_ids) for input_ids in chosen_input_ids] + rejected_input_ids = [torch.tensor(example["rejected_input_ids"]) for example in examples] + rejected_attention_mask = [torch.ones_like(input_ids) for input_ids in rejected_input_ids] + if "pixel_values" in examples[0]: + pixel_values = [torch.tensor(example["pixel_values"]) for example in examples] + if "pixel_attention_mask" in examples[0]: + pixel_attention_mask = [torch.tensor(example["pixel_attention_mask"]) for example in examples] + + # Pad + output = {} + output["prompt_input_ids"] = pad(prompt_input_ids, padding_value=self.pad_token_id, padding_side="left") + output["prompt_attention_mask"] = pad(prompt_attention_mask, padding_value=0, padding_side="left") + output["chosen_input_ids"] = pad(chosen_input_ids, padding_value=self.pad_token_id) + output["chosen_attention_mask"] = pad(chosen_attention_mask, padding_value=0) + output["rejected_input_ids"] = pad(rejected_input_ids, padding_value=self.pad_token_id) + output["rejected_attention_mask"] = pad(rejected_attention_mask, padding_value=0) + if "pixel_values" in examples[0]: + output["pixel_values"] = pad(pixel_values, padding_value=0.0) + if "pixel_attention_mask" in examples[0]: + output["pixel_attention_mask"] = pad(pixel_attention_mask, padding_value=0) + + return output + + +class DPOTrainer(Trainer): + r""" + Initialize DPOTrainer. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForSequenceClassification`. + ref_model (`PreTrainedModelWrapper`): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no + reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. + args (`DPOConfig`): + The DPO config arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + This supercedes the `tokenizer` argument, which is now deprecated. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Dict`, defaults to `None`): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. + """ + + _tag_names = ["trl", "dpo"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.16.0", raise_if_both_names=True) + def __init__( + self, + model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + args: Optional[DPOConfig] = None, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional[Dict] = None, + ): + if not isinstance(model, str) and ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must mass a copy of it, or `None` if you use peft." + ) + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError( + "You passed model_init_kwargs to the DPOTrainer/DPOConfig, but your model is already instantiated." + ) + else: + model_init_kwargs = args.model_init_kwargs + torch_dtype = model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the DPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + model_init_kwargs["torch_dtype"] = torch_dtype + + if args.ref_model_init_kwargs is None: + ref_model_init_kwargs = {} + elif not isinstance(ref_model, str): + raise ValueError( + "You passed ref_model_init_kwargs to the DPOTrainer/DPOConfig, but your ref_model is already instantiated." + ) + else: + ref_model_init_kwargs = args.ref_model_init_kwargs + torch_dtype = ref_model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the DPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + ref_model_init_kwargs["torch_dtype"] = torch_dtype + + if isinstance(model, str): + warnings.warn( + "You passed a model_id to the DPOTrainer. This will automatically create an " + "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you." + ) + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + if isinstance(ref_model, str): + warnings.warn( + "You passed a ref model_id to the DPOTrainer. This will automatically create an " + "`AutoModelForCausalLM`" + ) + ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs) + + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + + if not is_peft_available() and peft_config is not None: + raise ValueError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + # if model is a peft model and we have a peft_config, we merge and unload it first + if isinstance(model, PeftModel): + model = model.merge_and_unload() + + if ref_model is not None and not args.force_use_ref_model: + raise ValueError( + "You passed both a ref_model and a peft_config. For training PEFT adapters with DPO there is no need to pass a reference" + " model. Please pass `ref_model=None` in case you want to train PEFT adapters, or pass a ref_model with `force_use_ref_model=True` in DPOTrainer's init." + " if you want to use a different ref_model." + ) + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not is_wandb_available(): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases to be installed." + " Please install `wandb` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError( + "When no model is provided, you need to pass the parameter is_encoder_decoder to the DPOTrainer/DPOConfig." + ) + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if model is not None: + self.is_vision_model = model.config.model_type in MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.keys() + else: + warnings.warn( + "No model provided, cannot determine if it is a vision model. Setting is_vision_model to False." + ) + self.is_vision_model = False + + self.is_peft_model = is_peft_available() and isinstance(model, PeftModel) + self.model_adapter_name = args.model_adapter_name + self.ref_adapter_name = args.ref_adapter_name + self.reference_free = args.reference_free + + if ref_model: + self.ref_model = ref_model + elif self.is_peft_model or args.precompute_ref_log_probs: + # The `model` with adapters turned off will be used as the reference model + self.ref_model = None + else: + self.ref_model = create_reference_model(model) + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a DPO dataset.") + + if args.padding_value is not None: + self.padding_value = args.padding_value + else: + if hasattr(processing_class, "pad_token_id") and processing_class.pad_token_id is not None: + self.padding_value = processing_class.pad_token_id + elif hasattr(processing_class, "tokenizer") and processing_class.tokenizer.pad_token_id is not None: + self.padding_value = processing_class.tokenizer.pad_token_id + else: + raise ValueError( + "Can't find `pad_token_id` in the `processing_class`. " + "Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`) " + "before instantiating the trainer." + ) + + if data_collator is None: + data_collator = PreferenceCollator(pad_token_id=self.padding_value) + + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + self.max_length = args.max_length + self.generate_during_eval = args.generate_during_eval + self.label_pad_token_id = args.label_pad_token_id + self.max_prompt_length = args.max_prompt_length + self.truncation_mode = args.truncation_mode + self.max_completion_length = args.max_completion_length + self.precompute_ref_log_probs = args.precompute_ref_log_probs + self.use_num_logits_to_keep = args.use_num_logits_to_keep + + # Since ref_logs are precomputed on the first call to get_train/eval_dataloader + # keep track of first called to avoid computation of future calls + self._precomputed_train_ref_log_probs = False + self._precomputed_eval_ref_log_probs = False + + if ( + args.loss_type in ["hinge", "ipo", "bco_pair", "sppo_hard", "nca_pair", "apo_zero", "apo_down"] + and args.label_smoothing > 0 + ): + warnings.warn( + "You are using a loss type that does not support label smoothing. Ignoring label_smoothing parameter." + ) + if args.loss_type == "kto_pair": + raise ValueError("Support for kto_pair has been removed in DPOTrainer. Please use KTOTrainer.") + + self.beta = args.beta + self.label_smoothing = args.label_smoothing + self.loss_type = args.loss_type + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.use_weighting = args.use_weighting + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + warnings.warn( + "You set `output_router_logits` to True in the model config, but `router_aux_loss_coef` is set to 0.0," + " meaning the auxiliary loss will not be used." + ) + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + self.f_divergence_type = args.f_divergence_type + self.f_divergence_params = {FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY: args.f_alpha_divergence_coef} + self.dataset_num_proc = args.dataset_num_proc + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().local_main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset" + ) + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + desc="Applying chat template to train dataset", + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset" + ) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + desc="Applying chat template to eval dataset", + ) + + # tokenize the dataset, lower writer batch size to avoid OOM (frequent in vision models) + fn_kwargs = { + "processing_class": processing_class, + "max_prompt_length": args.max_prompt_length, + "max_completion_length": args.max_completion_length, + # for enc-dec, we add the special tokens ([bos_token] + prompt + [eos_token]; completion + [eos_token]) + "add_special_tokens": self.is_encoder_decoder, + } + train_dataset = train_dataset.map( + self.tokenize_row if not self.is_vision_model else self.process_row, + fn_kwargs=fn_kwargs, + num_proc=self.dataset_num_proc, + writer_batch_size=10, + desc="Tokenizing train dataset", + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + self.tokenize_row if not self.is_vision_model else self.process_row, + fn_kwargs=fn_kwargs, + num_proc=self.dataset_num_proc, + writer_batch_size=10, + desc="Tokenizing eval dataset", + ) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + # Deepspeed Zero-3 does not support precompute_ref_log_probs + if self.is_deepspeed_enabled: + if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." + ) + + if self.ref_model is None: + if not (self.is_peft_model or self.precompute_ref_log_probs): + raise ValueError( + "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" + ) + if args.sync_ref_model: + raise ValueError( + "You currently cannot use `ref_model=None` with TR-DPO method. Please provide `ref_model`." + ) + else: + if self.is_deepspeed_enabled: + self.ref_model = self._prepare_deepspeed(self.ref_model) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + if args.sync_ref_model: + if self.precompute_ref_log_probs: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with TR-DPO method. Please set `precompute_ref_log_probs=False`." + ) + + self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) + + if self.loss_type == "bco_pair": + self.running = RunningMoments(self.accelerator) + + @staticmethod + def tokenize_row(features, processing_class, max_prompt_length, max_completion_length, add_special_tokens): + """ + Tokenize a row of the dataset. + + Args: + features (`Dict[str, str]`): + Row of the dataset, should contain the keys `"prompt"`, `"chosen"`, and `"rejected"`. + processing_class (`PreTrainedTokenizerBase`): + Processing class used to process the data. + max_prompt_length (`int` or `None`): + Maximum length of the prompt sequence. If `None`, the prompt sequence is not truncated. + max_completion_length (`int` or `None`): + Maximum length of the completion sequences. If `None`, the completion sequences are not truncated. + add_special_tokens (`bool`): + Whether to add special tokens to the sequences. Typically used for encoder-decoder models. If `True`, + the prompt sequence will have a bos token prepended and an eos token appended. In any case, the + completion sequences will have an eos token appended. + + Returns: + `Dict[str, List[int]]`: + Tokenized sequences with the keys `"prompt_input_ids"`, `"chosen_input_ids"`, and + `"rejected_input_ids". + + Example: + ```python + >>> from transformers import GPT2Tokenizer + >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2") + >>> features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"} + >>> DPOTrainer.tokenize_row(features, tokenizer, max_prompt_length=3, max_completion_length=3, add_special_tokens=False) + {'prompt_input_ids': [464, 6766, 318], 'chosen_input_ids': [4171, 50256], 'rejected_input_ids': [4077, 50256]} + ``` + """ + tokenizer = processing_class # the processing class is a tokenizer + prompt_input_ids = tokenizer(features["prompt"], add_special_tokens=False)["input_ids"] + chosen_input_ids = tokenizer(features["chosen"], add_special_tokens=False)["input_ids"] + rejected_input_ids = tokenizer(features["rejected"], add_special_tokens=False)["input_ids"] + + # Add special tokens (typically for encoder-decoder models) + if add_special_tokens: + if tokenizer.bos_token_id is not None: + prompt_input_ids = [tokenizer.bos_token_id] + prompt_input_ids + if tokenizer.eos_token_id is not None: + prompt_input_ids = prompt_input_ids + [tokenizer.eos_token_id] + chosen_input_ids = chosen_input_ids + [tokenizer.eos_token_id] + rejected_input_ids = rejected_input_ids + [tokenizer.eos_token_id] + + # Truncate prompt and completion sequences + if max_prompt_length is not None: + prompt_input_ids = prompt_input_ids[-max_prompt_length:] + if max_completion_length is not None: + chosen_input_ids = chosen_input_ids[:max_completion_length] + rejected_input_ids = rejected_input_ids[:max_completion_length] + + return { + "prompt_input_ids": prompt_input_ids, + "chosen_input_ids": chosen_input_ids, + "rejected_input_ids": rejected_input_ids, + } + + @staticmethod + def process_row(features, processing_class, max_prompt_length, max_completion_length, add_special_tokens): + """ + Same as `tokenize_row` but for vision models. Please refer to `tokenize_row` for more information. + """ + processor, tokenizer = processing_class, processing_class.tokenizer # the processing class is a processor + processed_features = processor(images=features["images"], text=features["prompt"], add_special_tokens=False) + + prompt_input_ids = processed_features["input_ids"][0] + pixel_values = processed_features["pixel_values"][0] + chosen_input_ids = tokenizer(features["chosen"], add_special_tokens=False)["input_ids"] + rejected_input_ids = tokenizer(features["rejected"], add_special_tokens=False)["input_ids"] + + # Add special tokens (typically for encoder-decoder models) + if add_special_tokens: + if tokenizer.bos_token_id is not None: + prompt_input_ids = [tokenizer.bos_token_id] + prompt_input_ids + if tokenizer.eos_token_id is not None: + prompt_input_ids = prompt_input_ids + [tokenizer.eos_token_id] + chosen_input_ids = chosen_input_ids + [tokenizer.eos_token_id] + rejected_input_ids = rejected_input_ids + [tokenizer.eos_token_id] + + # Truncate prompt and completion sequences + if max_prompt_length is not None: + prompt_input_ids = prompt_input_ids[-max_prompt_length:] + if max_completion_length is not None: + chosen_input_ids = chosen_input_ids[:max_completion_length] + rejected_input_ids = rejected_input_ids[:max_completion_length] + + output = { + "prompt_input_ids": prompt_input_ids, + "pixel_values": pixel_values, + "chosen_input_ids": chosen_input_ids, + "rejected_input_ids": rejected_input_ids, + } + + if "pixel_attention_mask" in processed_features: + output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0] + + return output + + def _prepare_deepspeed(self, model: PreTrainedModelWrapper): + # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + + if model is not None: + if hasattr(model, "config"): + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0) + if config_kwargs["zero_optimization"]["stage"] != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + def _set_signature_columns_if_needed(self): + # If `self.args.remove_unused_columns` is True, non-signature columns are removed. + # By default, this method sets `self._signature_columns` to the model's expected inputs. + # In DPOTrainer, we preprocess data, so using the model's signature columns doesn't work. + # Instead, we set them to the columns expected by `DPODataCollatorWithPadding`, hence the override. + if self._signature_columns is None: + self._signature_columns = ["prompt_input_ids", "chosen_input_ids", "rejected_input_ids"] + + def get_train_dataloader(self) -> DataLoader: + """ + Returns the training [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. + """ + + if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) + + ref_chosen_logps = [] + ref_rejected_logps = [] + for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): + ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch) + ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics( + (ref_chosen_logp, ref_rejected_logp) + ) + ref_chosen_logps.append(ref_chosen_logp.cpu()) + ref_rejected_logps.append(ref_rejected_logp.cpu()) + + # Unnecessary cache clearing to avoid OOM + torch.cuda.empty_cache() + self.accelerator.free_memory() + + all_ref_chosen_logps = torch.cat(ref_chosen_logps).float().numpy() + all_ref_rejected_logps = torch.cat(ref_rejected_logps).float().numpy() + + self.train_dataset = self.train_dataset.add_column(name="ref_chosen_logps", column=all_ref_chosen_logps) + self.train_dataset = self.train_dataset.add_column( + name="ref_rejected_logps", column=all_ref_rejected_logps + ) + + self._precomputed_train_ref_log_probs = True + + return super().get_train_dataloader() + + def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: + """ + Returns the evaluation [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. + + Args: + eval_dataset (`torch.utils.data.Dataset`, *optional*): + If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted + by the `model.forward()` method are automatically removed. It must implement `__len__`. + """ + if eval_dataset is None and self.eval_dataset is None: + raise ValueError("Trainer: evaluation requires an eval_dataset.") + eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset + + if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_eval_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) + + ref_chosen_logps = [] + ref_rejected_logps = [] + for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): + ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch) + ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics( + (ref_chosen_logp, ref_rejected_logp) + ) + ref_chosen_logps.append(ref_chosen_logp.cpu()) + ref_rejected_logps.append(ref_rejected_logp.cpu()) + + all_ref_chosen_logps = torch.cat(ref_chosen_logps).float().numpy() + all_ref_rejected_logps = torch.cat(ref_rejected_logps).float().numpy() + + eval_dataset = eval_dataset.add_column(name="ref_chosen_logps", column=all_ref_chosen_logps) + eval_dataset = eval_dataset.add_column(name="ref_rejected_logps", column=all_ref_rejected_logps) + + # Save calculated ref_chosen_logps and ref_rejected_logps to the eval_dataset for subsequent runs + if self.eval_dataset is not None: + self.eval_dataset = eval_dataset + self._precomputed_eval_ref_log_probs = True + + return super().get_eval_dataloader(eval_dataset=eval_dataset) + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with self.accelerator.unwrap_model( + self.model + ).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext(): + if self.ref_adapter_name: + self.model.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.set_adapter(self.model_adapter_name or "default") + + def compute_ref_log_probs(self, batch: Dict[str, torch.LongTensor]) -> Dict: + """Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset.""" + compte_ref_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + with torch.no_grad(), compte_ref_context_manager: + if self.ref_model is None: + with self.null_ref_context(): + ref_model_output = self.concatenated_forward(self.model, batch) + else: + ref_model_output = self.concatenated_forward(self.ref_model, batch) + return ref_model_output["chosen_logps"], ref_model_output["rejected_logps"] + + @staticmethod + def concatenated_inputs( + batch: Dict[str, Union[List, torch.LongTensor]], padding_value: int + ) -> Dict[str, torch.LongTensor]: + """ + Concatenate the `chosen` and `rejected` inputs from the batch into a single tensor for both the prompt + and completion sequences. + + Args: + batch (`Dict[str, Union[List, torch.LongTensor]]`): + A batch of input data. The batch must contain the following keys: + + - `"prompt_input_ids"`: Tensor of shape `(batch_size, prompt_length)` representing the prompt input IDs. + - `"chosen_input_ids"`: Tensor of shape `(batch_size, chosen_length)` representing the chosen completion input IDs. + - `"rejected_input_ids"`: Tensor of shape `(batch_size, rejected_length)` representing the rejected completion input IDs. + - `"prompt_pixel_values"` (optional): Tensor for pixel values, if available. + - `"prompt_pixel_attention_mask"` (optional): Tensor for pixel attention masks, if available. + + padding_value (`int`): + The padding value to use for the concatenated completion sequences (`chosen_input_ids` and + `rejected_input_ids`). + + Returns: + `Dict[str, torch.LongTensor]`: A dictionary containing: + + - `"prompt_input_ids"`: Concatenated prompt input IDs of shape `(2 * batch_size, prompt_length)`. + - `"completion_input_ids"`: Concatenated chosen and rejected completion input IDs of shape `(2 * batch_size, max_completion_length)`. + - `"prompt_attention_mask"`: Concatenated prompt attention masks of shape `(2 * batch_size, prompt_length)`. + - `"completion_attention_mask"`: Concatenated chosen and rejected attention masks of shape `(2 * batch_size, max_completion_length)`. + - `"pixel_values"` (optional): Concatenated pixel values if `"prompt_pixel_values"` are present. + - `"pixel_attention_mask"` (optional): Concatenated pixel attention masks if `"prompt_pixel_attention_mask"` are present. + + Notes: + The completion input IDs and attention masks are padded to the maximum completion length of the chosen + or rejected sequences. + """ + output = {} + + # For the prompt, the input_ids are the same for both the chosen and rejected responses + output["prompt_input_ids"] = torch.cat([batch["prompt_input_ids"], batch["prompt_input_ids"]], dim=0) + output["prompt_attention_mask"] = torch.cat( + [batch["prompt_attention_mask"], batch["prompt_attention_mask"]], dim=0 + ) + if "pixel_values" in batch: + output["pixel_values"] = torch.cat([batch["pixel_values"], batch["pixel_values"]], dim=0) + + if "pixel_attention_mask" in batch: + output["pixel_attention_mask"] = torch.cat( + [batch["pixel_attention_mask"], batch["pixel_attention_mask"]], dim=0 + ) + + # Concatenate the chosen and rejected completions + max_completion_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + output["completion_input_ids"] = torch.cat( + ( + pad_to_length(batch["chosen_input_ids"], max_completion_length, pad_value=padding_value), + pad_to_length(batch["rejected_input_ids"], max_completion_length, pad_value=padding_value), + ), + ) + output["completion_attention_mask"] = torch.cat( + ( + pad_to_length(batch["chosen_attention_mask"], max_completion_length, pad_value=0), + pad_to_length(batch["rejected_attention_mask"], max_completion_length, pad_value=0), + ), + ) + + return output + + def dpo_loss( + self, + chosen_logps: torch.FloatTensor, + rejected_logps: torch.FloatTensor, + ref_chosen_logps: torch.FloatTensor, + ref_rejected_logps: torch.FloatTensor, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """ + Compute the DPO loss for a batch of policy and reference model log probabilities. + + Args: + chosen_logps (`torch.FloatTensor`): + Log probabilities of the model for the chosen responses. Shape: `(batch_size,)`. + rejected_logps (`torch.FloatTensor`): + Log probabilities of the model for the rejected responses. Shape: `(batch_size,)`. + ref_chosen_logps (`torch.FloatTensor`): + Log probabilities of the reference model for the chosen responses. Shape: `(batch_size,)`. + ref_rejected_logps (`torch.FloatTensor`): + Log probabilities of the reference model for the rejected responses. Shape: `(batch_size,)`. + + Returns: + A tuple of three tensors: `(losses, chosen_rewards, rejected_rewards)`. + The losses tensor contains the DPO loss for each example in the batch. + The `chosen_rewards` and `rejected_rewards` tensors contain the rewards for the chosen and rejected + responses, respectively. + """ + device = self.accelerator.device + + # Get the log ratios for the chosen and rejected responses + chosen_logratios = chosen_logps.to(device) - (not self.reference_free) * ref_chosen_logps.to(device) + rejected_logratios = rejected_logps.to(device) - (not self.reference_free) * ref_rejected_logps.to(device) + + if self.f_divergence_type == FDivergenceType.ALPHA_DIVERGENCE.value: + # The alpha-divergence formula: (1 - u^-alpha) / alpha + # The divergence difference between the chosen and rejected sample is: + # (1 - u[w]^-alpha) / alpha - (1 - u[l]^-alpha) / alpha + # = (u[l]^-alpha - u[w]^-alpha) / alpha + # where u[w] and u[l] are the policy/reference probability ratios + # for the chosen and rejected samples, respectively. + alpha_coef = FDivergenceConstants.ALPHA_DIVERGENCE_COEF_DEFAULT + if self.f_divergence_params and FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY in self.f_divergence_params: + alpha_coef = float(self.f_divergence_params[FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY]) + logits = (cap_exp(rejected_logratios * -alpha_coef) - cap_exp(chosen_logratios * -alpha_coef)) / alpha_coef + else: + logratios = chosen_logps - rejected_logps + if self.reference_free: + ref_logratios = torch.tensor([0], dtype=logratios.dtype, device=logratios.device) + else: + ref_logratios = ref_chosen_logps - ref_rejected_logps + + logratios = logratios.to(self.accelerator.device) + ref_logratios = ref_logratios.to(self.accelerator.device) + logits = logratios - ref_logratios + + if self.f_divergence_type == FDivergenceType.JS_DIVERGENCE.value: + # The js-divergence formula: log(2 * u / (1 + u)) + # The divergence difference between the chosen and rejected sample is: + # log(2 * u[w] / (1 + u[w])) - log(2 * u[l] / (1 + u[l])) + # = log(u[w]) - log(u[l]) - (log(1 + u[w]) - log(1 + u[l])) + # where u[w] and u[l] are the policy/reference probability ratios + # for the chosen and rejected samples, respectively. + logits -= F.softplus(chosen_logratios) - F.softplus(rejected_logratios) + + # The beta is a temperature parameter for the DPO loss, typically something in the range of 0.1 to 0.5. + # We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the + # labels and calculates a conservative DPO loss. + if self.loss_type == "sigmoid": + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) + + elif self.loss_type == "robust": + losses = ( + -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) + + F.logsigmoid(-self.beta * logits) * self.label_smoothing + ) / (1 - 2 * self.label_smoothing) + + elif self.loss_type == "exo_pair": + # eqn (16) of the EXO paper: https://huggingface.co/papers/2402.00856 + import math + + if self.label_smoothing == 0: + self.label_smoothing = 1e-3 + losses = (self.beta * logits).sigmoid() * ( + F.logsigmoid(self.beta * logits) - math.log(1 - self.label_smoothing) + ) + (-self.beta * logits).sigmoid() * (F.logsigmoid(-self.beta * logits) - math.log(self.label_smoothing)) + + elif self.loss_type == "hinge": + losses = torch.relu(1 - self.beta * logits) + + elif self.loss_type == "ipo": + # eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper. + losses = (logits - 1 / (2 * self.beta)) ** 2 + + elif self.loss_type == "bco_pair": + chosen_logratios = chosen_logps - ref_chosen_logps + rejected_logratios = rejected_logps - ref_rejected_logps + chosen_rewards = self.beta * chosen_logratios + rejected_rewards = self.beta * rejected_logratios + rewards = torch.cat((chosen_rewards, rejected_rewards), 0).mean().detach() + self.running.update(rewards) + delta = self.running.mean + losses = -F.logsigmoid((self.beta * chosen_logratios) - delta) - F.logsigmoid( + -(self.beta * rejected_logratios - delta) + ) + + elif self.loss_type == "sppo_hard": + # In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach, + # estimated using the PairRM score. The probability calculation is conducted outside of the trainer class. + # The version described here is the hard probability version, where P in Equation (4.7) of Algorithm 1 is + # set to 1 for the winner and 0 for the loser. + a = chosen_logps - ref_chosen_logps + b = rejected_logps - ref_rejected_logps + losses = (a - 0.5 / self.beta) ** 2 + (b + 0.5 / self.beta) ** 2 + + elif self.loss_type == "nca_pair": + chosen_rewards = (chosen_logps - ref_chosen_logps) * self.beta + rejected_rewards = (rejected_logps - ref_rejected_logps) * self.beta + losses = ( + -F.logsigmoid(chosen_rewards) + - 0.5 * F.logsigmoid(-chosen_rewards) + - 0.5 * F.logsigmoid(-rejected_rewards) + ) + + elif self.loss_type == "aot_pair": + chosen_logratios = chosen_logps - ref_chosen_logps + rejected_logratios = rejected_logps - ref_rejected_logps + chosen_logratios_sorted, _ = torch.sort(chosen_logratios, dim=0) + rejected_logratios_sorted, _ = torch.sort(rejected_logratios, dim=0) + delta = chosen_logratios_sorted - rejected_logratios_sorted + losses = ( + -F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta) * self.label_smoothing + ) + + elif self.loss_type == "aot": + logratios = chosen_logps - rejected_logps + ref_logratios = ref_chosen_logps - ref_rejected_logps + logratios_sorted, _ = torch.sort(logratios, dim=0) + ref_logratios_sorted, _ = torch.sort(ref_logratios, dim=0) + delta = logratios_sorted - ref_logratios_sorted + losses = ( + -F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing) + - F.logsigmoid(-self.beta * delta) * self.label_smoothing + ) + + elif self.loss_type == "apo_zero": + # Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are better than your model's default output + losses_chosen = 1 - F.sigmoid(self.beta * chosen_logratios) # Increase chosen likelihood + losses_rejected = F.sigmoid(self.beta * rejected_logratios) # Decrease rejected likelihood + losses = losses_chosen + losses_rejected + + elif self.loss_type == "apo_down": + # Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are worse than your model's default output. + # Decrease chosen likelihood and decrease rejected likelihood more + losses_chosen = F.sigmoid(self.beta * chosen_logratios) + losses_rejected = 1 - F.sigmoid(self.beta * (chosen_logratios - rejected_logratios)) + losses = losses_chosen + losses_rejected + + elif self.loss_type == "discopop": + # Eqn (5) of the DiscoPOP paper (https://huggingface.co/papers/2406.08414) + # This loss was discovered with LLM discovery + logratios = chosen_logps - rejected_logps + ref_logratios = ref_chosen_logps - ref_rejected_logps + logits = logratios - ref_logratios + logits = logits * self.beta + # Modulate the mixing coefficient based on the log ratio magnitudes + log_ratio_modulation = torch.sigmoid(logits / self.args.discopop_tau) + logistic_component = -F.logsigmoid(logits) + exp_component = torch.exp(-logits) + # Blend between logistic and exponential component based on log ratio modulation + losses = logistic_component * (1 - log_ratio_modulation) + exp_component * log_ratio_modulation + + else: + raise ValueError( + f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'exo_pair', " + "'nca_pair', 'robust', 'bco_pair', 'sppo_hard', 'aot', 'aot_pair', 'discopop', 'apo_zero', 'apo_down']" + ) + + chosen_rewards = self.beta * (chosen_logps.to(device) - ref_chosen_logps.to(device)).detach() + rejected_rewards = self.beta * (rejected_logps.to(device) - ref_rejected_logps.to(device)).detach() + + return losses, chosen_rewards, rejected_rewards + + def concatenated_forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]): + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + num_examples = batch["prompt_input_ids"].shape[0] + + concatenated_batch = self.concatenated_inputs(batch, padding_value=self.padding_value) + + model_kwargs = {} + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + # Add the pixel values and attention masks for vision models + if "pixel_values" in concatenated_batch: + model_kwargs["pixel_values"] = concatenated_batch["pixel_values"] + if "pixel_attention_mask" in concatenated_batch: + model_kwargs["pixel_attention_mask"] = concatenated_batch["pixel_attention_mask"] + + prompt_input_ids = concatenated_batch["prompt_input_ids"] + prompt_attention_mask = concatenated_batch["prompt_attention_mask"] + completion_input_ids = concatenated_batch["completion_input_ids"] + completion_attention_mask = concatenated_batch["completion_attention_mask"] + if self.is_encoder_decoder: + labels = completion_input_ids + labels[completion_attention_mask == 0] = self.label_pad_token_id + outputs = model( + input_ids=prompt_input_ids, + attention_mask=prompt_attention_mask, + labels=labels, # we need the labels for the logits to be returned + **model_kwargs, + ) + logits = outputs.logits + loss_mask = completion_attention_mask.bool() + else: + # Concatenate the prompt and completion inputs + input_ids = torch.cat((prompt_input_ids, completion_input_ids), dim=1) + attention_mask = torch.cat((prompt_attention_mask, completion_attention_mask), dim=1) + # Mask the prompt but not the completion for the loss + loss_mask = torch.cat( + (torch.zeros_like(prompt_attention_mask), completion_attention_mask), + dim=1, + ) + + # Flush left to reduce the memory usage + # [[0, 0, x, x, x, x], -> [[x, x, x, x], + # [0, x, x, x, 0, 0]] [x, x, x, 0]] + for i in range(attention_mask.size(0)): + first_one_idx = torch.nonzero(attention_mask[i])[0].item() + input_ids[i] = torch.roll(input_ids[i], shifts=-first_one_idx) + attention_mask[i] = torch.roll(attention_mask[i], shifts=-first_one_idx) + loss_mask[i] = torch.roll(loss_mask[i], shifts=-first_one_idx) + + # Get the first column idx that is all zeros and remove every column after that + empty_cols = torch.sum(attention_mask, dim=0) == 0 + first_empty_col = torch.nonzero(empty_cols)[0].item() if empty_cols.any() else attention_mask.size(1) + input_ids = input_ids[:, :first_empty_col] + attention_mask = attention_mask[:, :first_empty_col] + loss_mask = loss_mask[:, :first_empty_col] + + # Truncate right + if self.args.max_length is not None: + input_ids = input_ids[:, : self.args.max_length] + attention_mask = attention_mask[:, : self.args.max_length] + loss_mask = loss_mask[:, : self.args.max_length] + + if self.use_num_logits_to_keep: + # Compute num_logits_to_keep based on loss_mask pattern: + # [[0, 0, 0, x, x, x, x], + # [0, 0, 0, x, x, x, 0]] + # ^ start computing logits from here ([:, -(7-3+1):]) + first_compute_index = loss_mask.nonzero(as_tuple=True)[1].min() + num_logits_to_keep = loss_mask.shape[1] - first_compute_index + model_kwargs["num_logits_to_keep"] = num_logits_to_keep.item() + 1 # +1 for the first label + + outputs = model(input_ids=input_ids, attention_mask=attention_mask, **model_kwargs) + + # Offset the logits by one to align with the labels + logits = outputs.logits[:, :-1, :] + labels = input_ids[:, 1:].clone() + loss_mask = loss_mask[:, 1:].bool() + + if self.use_num_logits_to_keep: + # Align labels with logits + # logits: -, -, [x2, x3, x4, x5, x6] + # ^ --------- ^ after logits[:, :-1, :] + # labels: [y0, y1, y2, y3, y4, y5, y6] + # ^ --------- ^ with num_logits_to_keep=4, [:, -4:] + # loss_mask: [0, 0, 0, 1, 1, 1, 1] + labels = labels[:, -num_logits_to_keep:] + loss_mask = loss_mask[:, -num_logits_to_keep:] + + if logits.shape[:2] != labels.shape[:2]: + # for llava, the returned logits include the image tokens (placed before the text tokens) + seq_len = labels.shape[1] + logits = logits[:, -seq_len:] + + # Compute the log probabilities of the labels + labels[~loss_mask] = 0 # dummy token; we'll ignore the losses on these tokens later + per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2) + per_token_logps[~loss_mask] = 0 + all_logps = per_token_logps.sum(-1) + + output = {} + + if self.use_weighting: + with torch.no_grad(): + # Eq (2) of the WPO paper: https://huggingface.co/papers/2406.11827 + logprobs = F.log_softmax(logits, dim=-1) + weights_adjustment_factor = torch.logsumexp(2 * logprobs, dim=-1) # same as sum(probs**2) in log space + per_token_logps_adjusted = per_token_logps - weights_adjustment_factor + all_weights = (per_token_logps_adjusted * loss_mask).sum(-1) / loss_mask.sum(-1) + chosen_weights = all_weights[:num_examples] + rejected_weights = all_weights[num_examples:] + output["policy_weights"] = torch.clamp(torch.exp(chosen_weights + rejected_weights), max=1) + + if self.args.rpo_alpha is not None: + # Only use the chosen logits for the RPO loss + chosen_logits = logits[:num_examples] + chosen_labels = labels[:num_examples] + + # Compute the log probabilities of the labels + output["nll_loss"] = F.cross_entropy( + torch.flatten(chosen_logits, end_dim=1), torch.flatten(chosen_labels, end_dim=1), ignore_index=0 + ) + + if self.loss_type == "ipo": + all_logps = all_logps / loss_mask.sum(-1) + + output["chosen_logps"] = all_logps[:num_examples] + output["rejected_logps"] = all_logps[num_examples:] + output["mean_chosen_logits"] = logits[:num_examples][loss_mask[:num_examples]].mean() + output["mean_rejected_logits"] = logits[num_examples:][loss_mask[num_examples:]].mean() + + if self.aux_loss_enabled: + output["aux_loss"] = outputs.aux_loss + + return output + + def get_batch_loss_metrics( + self, + model, + batch: Dict[str, Union[List, torch.LongTensor]], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the DPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + model_output = self.concatenated_forward(model, batch) + + # if ref_chosen_logps and ref_rejected_logps in batch use them, otherwise use the reference model + if "ref_chosen_logps" in batch and "ref_rejected_logps" in batch: + ref_chosen_logps = batch["ref_chosen_logps"] + ref_rejected_logps = batch["ref_rejected_logps"] + else: + ref_chosen_logps, ref_rejected_logps = self.compute_ref_log_probs(batch) + + losses, chosen_rewards, rejected_rewards = self.dpo_loss( + model_output["chosen_logps"], model_output["rejected_logps"], ref_chosen_logps, ref_rejected_logps + ) + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + if self.args.rpo_alpha is not None: + losses = losses + self.args.rpo_alpha * model_output["nll_loss"] # RPO loss from V3 of the paper + + if self.use_weighting: + losses = losses * model_output["policy_weights"] + + if self.aux_loss_enabled: + losses = losses + self.aux_loss_coef * model_output["aux_loss"] + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean().cpu() + metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean().cpu() + metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean().cpu() + metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean().cpu() + metrics[f"{prefix}logps/chosen"] = model_output["chosen_logps"].detach().mean().cpu() + metrics[f"{prefix}logps/rejected"] = model_output["rejected_logps"].detach().mean().cpu() + metrics[f"{prefix}logits/chosen"] = model_output["mean_chosen_logits"].detach().cpu() + metrics[f"{prefix}logits/rejected"] = model_output["mean_rejected_logits"].detach().cpu() + if self.args.rpo_alpha is not None: + metrics[f"{prefix}nll_loss"] = model_output["nll_loss"].detach().mean().cpu() + if self.aux_loss_enabled: + metrics[f"{prefix}aux_loss"] = model_output["aux_loss"].detach().cpu() + + return losses.mean(), metrics + + def compute_loss( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + return_outputs=False, + num_items_in_batch=None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: + compute_loss_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return loss, metrics + + return loss + + def generate_from_model_and_ref(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch cuda amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + # if ref_output in batch use that otherwise use the reference model + if "ref_output" in batch: + ref_output = batch["ref_output"] + else: + if self.ref_model is None: + with self.null_ref_context(): + ref_output = self.model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + else: + ref_output = self.ref_model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + ref_output = pad_to_length(ref_output, self.max_length, self.processing_class.pad_token_id) + ref_output_decoded = self.processing_class.batch_decode(ref_output, skip_special_tokens=True) + + return policy_output_decoded, ref_output_decoded + + def prediction_step( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + prediction_loss_only: bool, + ignore_keys: Optional[List[str]] = None, + ): + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return loss.detach(), None, None + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys) + logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: Optional[bool] = None, + ignore_keys: Optional[List[str]] = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. + Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, random_batch) + + self.log( + { + "game_log": wandb.Table( + columns=["Prompt", "Policy", "Ref Model"], + rows=[ + [prompt, pol[len(prompt) :], ref[len(prompt) :]] + for prompt, pol, ref in zip( + random_batch["prompt"], policy_output_decoded, ref_output_decoded + ) + ], + ) + } + ) + self.state.log_history.pop() + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: Dict[str, float]) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`Dict[str, float]`): + The values to log. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent( + """\ + @inproceedings{rafailov2023direct, + title = {{Direct Preference Optimization: Your Language Model is Secretly a Reward Model}}, + author = {Rafael Rafailov and Archit Sharma and Eric Mitchell and Christopher D. Manning and Stefano Ermon and Chelsea Finn}, + year = 2023, + booktitle = {Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023}, + url = {http://papers.nips.cc/paper_files/paper/2023/hash/a85b405ed65c6477a4fe8302b5e06ce7-Abstract-Conference.html}, + editor = {Alice Oh and Tristan Naumann and Amir Globerson and Kate Saenko and Moritz Hardt and Sergey Levine}, + }""" + ) + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="DPO", + trainer_citation=citation, + paper_title="Direct Preference Optimization: Your Language Model is Secretly a Reward Model", + paper_id="2305.18290", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/gkd_config.py b/testbed/huggingface__trl/trl/trainer/gkd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7230b296404e6c3d472418c5faa4847165b82890 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/gkd_config.py @@ -0,0 +1,64 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from .sft_config import SFTConfig + + +@dataclass +class GKDConfig(SFTConfig): + """ + Configuration class for GKDTrainer. + + Args: + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + lmbda (`float`, *optional*, defaults to `0.5`): + Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy + student-generated outputs). + beta (`float`, *optional*, defaults to `0.5`): + Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When + beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence. + max_new_tokens (`int`, *optional*, defaults to `128`): + Maximum number of tokens to generate per completion. + teacher_model_name_or_path (`Optional[str]`, *optional*, defaults to `None`): + Model name or path of the teacher model. If `None`, the teacher model will be the same as the model + being trained. + teacher_model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model + from a string. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether or not to disable dropouts in `model`. + seq_kd (`bool`, *optional*, defaults to `False`): + Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT + on teacher-generated output). + """ + + temperature: float = 0.9 + lmbda: float = 0.5 + beta: float = 0.5 + max_new_tokens: int = 128 + teacher_model_name_or_path: Optional[str] = None + teacher_model_init_kwargs: Optional[Dict[str, Any]] = None + disable_dropout: bool = True + seq_kd: bool = False + + def __post_init__(self): + super().__post_init__() + # check lmbda and beta are in the range [0, 1] + if self.lmbda < 0.0 or self.lmbda > 1.0: + raise ValueError("lmbda must be in the range [0.0, 1.0].") + if self.beta < 0.0 or self.beta > 1.0: + raise ValueError("beta must be in the range [0.0, 1.0].") diff --git a/testbed/huggingface__trl/trl/trainer/gkd_trainer.py b/testbed/huggingface__trl/trl/trainer/gkd_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f44335d197fb14145cccd00c411a2946d805afe2 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/gkd_trainer.py @@ -0,0 +1,391 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import random +import textwrap +import warnings +from copy import deepcopy +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from accelerate.utils import is_deepspeed_available +from datasets import Dataset +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + is_wandb_available, +) +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_liger_kernel_available, is_peft_available + +from ..models import PreTrainedModelWrapper +from ..models.utils import unwrap_model_for_generation +from .gkd_config import GKDConfig +from .sft_trainer import SFTTrainer +from .utils import DataCollatorForChatML, disable_dropout_in_model, empty_cache, generate_model_card + + +if is_deepspeed_available(): + import deepspeed + +if is_liger_kernel_available(): + from liger_kernel.transformers import AutoLigerKernelForCausalLM + +if is_peft_available(): + from peft import PeftConfig + +if is_wandb_available(): + import wandb + + +class GKDTrainer(SFTTrainer): + _tag_names = ["trl", "gkd"] + + def __init__( + self, + model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + teacher_model: Union[PreTrainedModel, nn.Module, str] = None, + args: Optional[GKDConfig] = None, + data_collator: Optional[DataCollator] = None, # type: ignore + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional["PeftConfig"] = None, + formatting_func: Optional[Callable] = None, + ): + # add remove_unused_columns=False to the the dataclass args + args.remove_unused_columns = False + data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_seq_length) + + super().__init__( + model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + peft_config=peft_config, + formatting_func=formatting_func, + ) + + if args.teacher_model_init_kwargs is None: + teacher_model_init_kwargs = {} + elif not isinstance(teacher_model, str): + raise ValueError( + "You passed teacher_model_init_kwargs to the GKDConfig, but your teacher_model is already instantiated." + ) + else: + teacher_model_init_kwargs = args.teacher_model_init_kwargs + teacher_model_init_kwargs["torch_dtype"] = ( + teacher_model_init_kwargs["torch_dtype"] + if teacher_model_init_kwargs["torch_dtype"] in ["auto", None] + else getattr(torch, teacher_model_init_kwargs["torch_dtype"]) + ) + + if isinstance(teacher_model, str): + warnings.warn( + "You passed a teacher model_id to the GKDTrainer. This will automatically create an " + "`AutoModelForCausalLM`" + ) + if args.use_liger: + teacher_model = AutoLigerKernelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs) + else: + teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs) + + if args.disable_dropout: + disable_dropout_in_model(self.model) + + if self.is_deepspeed_enabled: + self.teacher_model = self._prepare_deepspeed(teacher_model) + else: + self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True) + + self.lmbda = args.lmbda + self.beta = args.beta + self.temperature = args.temperature + self.seq_kd = args.seq_kd + + self.generation_config = GenerationConfig( + max_new_tokens=args.max_new_tokens, + temperature=args.temperature, + do_sample=True, + top_k=0, + use_cache=False if args.gradient_checkpointing else True, + pad_token_id=self.processing_class.pad_token_id, + ) + # Set custom EOS tokens if they are specified by the model's generation + # config. This is important for models with the Llama 3 chat template, + # which use special tokens <|eot_id|> and <|eom_id|> to mark the end of + # turns or messages. + if ( + hasattr(self.model.generation_config, "eos_token_id") + and self.model.generation_config.eos_token_id is not None + ): + self.generation_config.eos_token_id = self.model.generation_config.eos_token_id + + @staticmethod + def generalized_jsd_loss( + student_logits, teacher_logits, labels=None, beta=0.5, temperature=1.0, reduction="batchmean" + ): + """ + Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1) + of https://huggingface.co/papers/2306.13649 for the definition. + + Args: + student_logits: Tensor of shape (batch_size, sequence_length, vocab_size) + teacher_logits: Tensor of shape (batch_size, sequence_length, vocab_size) + labels: Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing loss + beta: Interpolation coefficient between 0 and 1 (default: 0.5) + temperature: Softmax temperature (default: 1.0) + reduction: Specifies the reduction to apply to the output (default: 'batchmean') + + Returns: + loss: Scalar tensor with the generalized JSD loss + """ + + # Apply temperature scaling + student_logits = student_logits / temperature + teacher_logits = teacher_logits / temperature + + # Compute log probabilities for student and probabilities for teacher + student_log_probs = F.log_softmax(student_logits, dim=-1) + teacher_log_probs = F.log_softmax(teacher_logits, dim=-1) + + # Compute the log of the mixture distribution + # log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture + beta = torch.tensor(beta, dtype=student_log_probs.dtype) + mixture_log_probs = torch.logsumexp( + torch.stack([student_log_probs + torch.log(beta), teacher_log_probs + torch.log(1 - beta)]), + dim=0, + ) + + # Compute KL divergences using F.kl_div + # PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper. + kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True) + kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True) + + # Compute the Generalized Jensen-Shannon Divergence + jsd = beta * kl_teacher + (1 - beta) * kl_student + + # Masking + if labels is not None: + mask = labels != -100 + jsd = jsd[mask] + + # Apply reduction + if reduction == "batchmean": + return jsd.sum() / mask.sum() if labels is not None else jsd.sum() / (jsd.size(0) * jsd.size(1)) + elif reduction == "sum": + return jsd.sum() + elif reduction == "mean": + return jsd.mean() + else: + return jsd + + def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): + # compute student output + outputs_student = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # compute teacher output in eval mode + self.teacher_model.eval() + with torch.no_grad(): + outputs_teacher = self.teacher_model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + ) + + # slice the logits for the generated tokens using the inputs["prompts"] lengths + prompt_lengths = inputs["prompts"].shape[1] + shifted_student_logits = outputs_student.logits[:, prompt_lengths - 1 : -1, :] + shifted_teacher_logits = outputs_teacher.logits[:, prompt_lengths - 1 : -1, :] + shifted_labels = inputs["labels"][:, prompt_lengths:] + + # compute loss + loss = self.generalized_jsd_loss( + student_logits=shifted_student_logits, + teacher_logits=shifted_teacher_logits, + labels=shifted_labels, + beta=self.beta, + ) + + # empty cache + empty_cache() + + # Return loss + return (loss, outputs_student) if return_outputs else loss + + @staticmethod + def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None): + # Generate output with respect to the prompt only + generated_outputs = model.generate( + input_ids=inputs["prompts"], + attention_mask=inputs.get("prompt_attention_mask", None), + generation_config=generation_config, + return_dict_in_generate=True, + ) + + # Get the generated token IDs + generated_tokens = generated_outputs.sequences + # Calculate new attention mask + new_attention_mask = torch.ones_like(generated_tokens) + new_labels = generated_tokens.clone() + + # If there's pad_token_id, set attention mask to 0 for padding tokens + if pad_token_id is not None: + new_labels[new_labels == pad_token_id] = -100 + new_attention_mask[generated_tokens == pad_token_id] = 0 + + return generated_tokens, new_attention_mask, new_labels + + def training_step( + self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None + ) -> torch.Tensor: + """ + Perform a training step for the Generalized Knowledge Distillation (GKD) model. + + This method implements the on-policy learning approach described in the GKD paper. + With probability `self.lmbda`, it generates new responses using the student model, + which are then used for training instead of the original inputs. + """ + if self.seq_kd: + with unwrap_model_for_generation(self.teacher_model, self.accelerator) as unwrapped_model: + new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs( + unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id + ) + inputs["input_ids"] = new_input_ids + inputs["attention_mask"] = new_attention_mask + inputs["labels"] = new_labels + if random.random() <= self.lmbda: + with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model: + new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs( + unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id + ) + inputs["input_ids"] = new_input_ids + inputs["attention_mask"] = new_attention_mask + inputs["labels"] = new_labels + + loss = super().training_step(model, inputs, num_items_in_batch) + return loss + + def _prepare_deepspeed(self, model: PreTrainedModelWrapper): + # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + + if model is not None: + if hasattr(model, "config"): + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0) + if config_kwargs["zero_optimization"]["stage"] != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @inproceedings{agarwal2024on-policy, + title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}}, + author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem}, + year = 2024, + booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=3zKtaqxLhW}, + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="GKD", + trainer_citation=citation, + paper_title="On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes", + paper_id="2306.13649", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/iterative_sft_trainer.py b/testbed/huggingface__trl/trl/trainer/iterative_sft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..6e81a3586fe125aa4d3fffa1f8dc322312e9cb7c --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/iterative_sft_trainer.py @@ -0,0 +1,443 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import warnings +from typing import Callable, Dict, List, Optional, Tuple, Union + +import torch +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import ( + BaseImageProcessor, + DataCollator, + DataCollatorForLanguageModeling, + DataCollatorForSeq2Seq, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainingArguments, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available + +from ..core import PPODecorators +from .utils import generate_model_card + + +if is_peft_available(): + from peft import PeftModel + + +if is_wandb_available(): + import wandb + + +class IterativeSFTTrainer(Trainer): + """ + The IterativeSFTTrainer can be used to finetune models with methods that requires some steps between optimization. + + Args: + model (`PreTrainedModel`): + Model to be optimized, either an 'AutoModelForCausalLM' or an 'AutoModelForSeq2SeqLM'. + Check the documentation of `PreTrainedModel` for more details. + args (`transformers.TrainingArguments`): + The arguments to use for training. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + data_collator (Union[DataCollatorForLanguageModeling, DataCollatorForSeq2Seq], *optional*): + Data collator to be used for training and passed along the dataloader. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + max_length (`int`, defaults to `None`): + The maximum length of the input. + truncation_mode (`str`, defaults to `keep_end`): + The truncation mode to use, either `keep_end` or `keep_start`. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values. + optimize_device_cache (`bool`, *optional*, defaults to `False`): + Optimize CUDA cache for slightly more memory-efficient training. + """ + + _tag_names = ["trl", "iterative-sft"] + + def __init__( + self, + model: Optional[PreTrainedModel] = None, + args: Optional[TrainingArguments] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = ( + None, + None, + ), + data_collator: Optional[DataCollator] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + max_length: Optional[int] = None, + truncation_mode: Optional[str] = "keep_end", + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None, + optimize_device_cache: Optional[bool] = False, + ): + # Step 0: check positional arguments validity + if not isinstance(processing_class, (PreTrainedTokenizerBase)): + raise ValueError( + f"processing_class must be a PreTrainedTokenizerBase like a PreTrainedTokenizer or a PreTrainedTokenizerFast, got {type(processing_class)}" + ) + if not isinstance(model, PreTrainedModel): + raise ValueError(f"model must be a PreTrainedModel, got {type(model)}") + if not model.can_generate(): + warnings.warn( + f"The current model class {type(model)} is not compatible with `.generate()`" + "Please make sure that this is intended." + ) + if optimizers[1] is None and args.max_steps == -1: + raise ValueError( + "When no scheduler is provided, you need to set the total number of training steps to perform `max_steps`" + ) + + self.is_encoder_decoder = getattr(model.config, "is_encoder_decoder", False) + self.is_peft_model = is_peft_available() and isinstance(model, PeftModel) + + self.processing_class = processing_class + + if data_collator is None: + if self.is_encoder_decoder: + warnings.warn( + "No data collator is provided. Using 'DataCollatorForSeq2Seq' with" + "'labels_pad_token_id' set to '-100' and 'pad_to_multiple_of' set to 8." + ) + self.data_collator = DataCollatorForSeq2Seq( + processing_class, label_pad_token_id=-100, pad_to_multiple_of=8 + ) + else: + warnings.warn("No data collator is provided. Using 'DataCollatorForLanguageModeling'") + self.data_collator = DataCollatorForLanguageModeling(self.processing_class, mlm=False) + else: + self.data_collator = data_collator + + self.max_length = max_length + self.truncation_mode = truncation_mode + self.optimize_device_cache = optimize_device_cache + + super().__init__( + model=model, + args=args, + data_collator=self.data_collator, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self.create_optimizer_and_scheduler(self.args.max_steps) + + # prepare model, optimizer and lr_scheduler + self.model, self.optimizer, self.lr_scheduler = self.accelerator.prepare( + self.model, self.optimizer, self.lr_scheduler + ) + + self.processing_class.truncation_side = "left" if self.truncation_mode == "keep_end" else "right" + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + PPODecorators.optimize_device_cache = self.optimize_device_cache + + def prepare_model_inputs(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, labels: torch.Tensor): + if attention_mask is None: + attention_mask = [torch.ones_like(ids) for ids in input_ids] + + if self.is_encoder_decoder: + input_data = self.data_collator( + [ + {"input_ids": ids, "attention_mask": att, "labels": lab} + for ids, att, lab in zip(input_ids, attention_mask, labels) + ] + ).to(self.model.device) + + input_data.pop("decoder_input_ids", None) # This is directly computed inside the model + + input_data["labels"][input_data["labels"] == self.processing_class.pad_token_id] = -100 + + else: + input_data = self.data_collator( + [{"input_ids": ids, "attention_mask": att} for ids, att in zip(input_ids, attention_mask)] + ).to(self.model.device) + + # truncate in case the user has provided input_ids, attention_mask and labels + if self.max_length is not None: + if self.truncation_mode == "keep_start": + input_data = {k: v[: self.max_length] for k, v in input_data.items()} + elif self.truncation_mode == "keep_end": + input_data = {k: v[-self.max_length :] for k, v in input_data.items()} + else: + raise ValueError(f"Unknown truncation mode: {self.truncation_mode}") + + return input_data + + @staticmethod + def _step_safety_checker( + input_ids: List[torch.LongTensor], + attention_mask: List[torch.LongTensor], + labels: List[torch.LongTensor], + texts: List[str], + texts_labels: List[str], + ): + """ + Check if the input data is valid for training. + + Args: + input_ids (List[`torch.LongTensor`]): + List of tensors containing the input_ids + attention_mask (List[`torch.LongTensor`]): + List of tensors containing the attention_mask + labels (List[`torch.FloatTensor`]): + List of tensors containing the labels + texts (List[`str`]): + List of string containing the text input. + texts_labels (List[`str`]): + List of string containing the text labels. + + Returns: + `tuple`: The input data. + """ + if texts is None: + if attention_mask is None: + for name, tensor_list in zip(["input_ids", "labels"], [input_ids, labels]): + if not isinstance(tensor_list, list): + raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}") + if not isinstance(tensor_list[0], torch.Tensor): + raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}") + else: + for name, tensor_list in zip( + ["input_ids", "attention_mask", "labels"], [input_ids, attention_mask, labels] + ): + if not isinstance(tensor_list, list): + raise ValueError(f"{name} must be a list of tensors - got {type(tensor_list)}") + if not isinstance(tensor_list[0], torch.Tensor): + raise ValueError(f"Elements in {name} must be tensors - got {type(tensor_list[0])}") + else: + if not isinstance(texts, list): + raise ValueError(f"'text' must be a list of strings - got {type(texts)}") + if not isinstance(texts[0], str): + raise ValueError(f"Elements in 'text' must be strings - got {type(texts[0])}") + if texts_labels is not None: + if not isinstance(texts_labels, list): + raise ValueError(f"'text_labels' must be a list of strings - got {type(texts_labels)}") + if not isinstance(texts_labels[0], str): + raise ValueError(f"Elements in 'text_labels' must be strings - got {type(texts_labels[0])}") + + return input_ids, attention_mask, labels, texts, texts_labels + + @PPODecorators.empty_device_cache() + def step( + self, + input_ids: Optional[List[torch.LongTensor]] = None, + attention_mask: Optional[List[torch.LongTensor]] = None, + labels: Optional[List[torch.LongTensor]] = None, + texts: Optional[List[str]] = None, + texts_labels: Optional[List[str]] = None, + ): + """ + Run an optimisation step given a list of input_ids, attention_mask, and labels or a list of text and text_labels. + Args: + input_ids (List[`torch.LongTensor`]): + List of tensors containing the input_ids (if not provided, text will be used) + attention_mask (List[`torch.LongTensor`], , *optional*): + List of tensors containing the attention_mask + labels (List[`torch.FloatTensor`], *optional*): + List of tensors containing the labels (if set to None, will default to input_ids) + texts (List[`str`], *optional*): + List of strings containing the text input (if not provided, input_ids will directly be used) + texts_labels (List[`str`], *optional*): + List of strings containing the text labels (if set to None, will default to text) + + Returns: + `dict[str, Any]`: A summary of the training statistics + """ + self.model.train() + + if self.state.global_step == 0: + self.tr_loss = torch.tensor(0.0).to(self.args.device) + self._globalstep_last_logged = self.state.global_step + + if input_ids is None and texts is None: + raise ValueError("Step should include `input_ids` or `texts` as keyword arguments.") + elif input_ids is not None and texts is not None: + warnings.warn( + "Both 'input_ids' and 'texts' are provided. 'input_ids' will be overwritten using inputs provided by the 'texts' keyword argument." + ) + + if labels is None and texts_labels is None and self.is_encoder_decoder: + raise ValueError( + "No 'labels' or 'text_labels' are provided. When using an encoder-decoder architecture, 'labels' or 'text_labels' must be passed." + ) + + input_ids, attention_mask, labels, texts, texts_labels = self._step_safety_checker( + input_ids, attention_mask, labels, texts, texts_labels + ) + + if texts is not None: + model_inputs = self.processing_class( + texts, max_length=self.max_length, truncation=True, padding=True, return_tensors="pt" + ) + + input_ids, attention_mask = model_inputs["input_ids"], model_inputs["attention_mask"] + + if texts_labels is not None: + labels = self.processing_class( + texts, max_length=self.max_length, truncation=True, padding=True, return_tensors="pt" + )["input_ids"] + + if labels is None: + warnings.warn("No labels are provided. Setting labels to input_ids") + labels = input_ids + + model_inputs = self.prepare_model_inputs(input_ids, attention_mask, labels) + + model_inputs_names = list(model_inputs.keys()) + + batch_dict = {} + batch_dict.update(model_inputs) + + def collator(data): + return_dict = dict() + for key in data[0]: + if key in ["input_ids", "attention_mask", "labels"]: + return_dict[key] = torch.stack([d[key] for d in data]).to(self.model.device) + return return_dict + + batch_data = Dataset.from_dict(batch_dict) + batch_data.set_format("torch") + + step_dataloader = DataLoader( + batch_data, + batch_size=self.args.per_device_train_batch_size, + shuffle=True, + collate_fn=collator, + ) + + for _, batch in enumerate(step_dataloader): + with self.accelerator.accumulate(self.model): + model_inputs = {k: batch[k] for k in model_inputs_names} + loss = self.compute_loss(self.model, model_inputs) + + if self.args.n_gpu > 1: + loss = loss.mean() + + tr_loss_step = loss.detach() + + self.accelerator.backward(loss) + + if self.accelerator.sync_gradients and self.args.max_grad_norm is not None: + self.accelerator.clip_grad_norm_( + self.model.parameters(), + self.args.max_grad_norm, + ) + + self.optimizer.step() + self.optimizer.zero_grad() + if self.lr_scheduler is not None: + self.lr_scheduler.step() + + self.state.global_step += 1 + + # update stats etc + self.tr_loss += tr_loss_step + + self._maybe_log_save_evaluate() + + def _maybe_log_save_evaluate(self): + # check if eval is required + if self.args.eval_steps is not None: + if self.state.global_step % self.args.eval_steps == 0 and self.state.global_step != 0: + self.evaluate(self.eval_dataset) + + # check if logging is required + if self.args.logging_steps is not None: + if self.state.global_step % self.args.logging_steps == 0 and self.state.global_step != 0: + logs: Dict[str, float] = {} + + tr_loss_scalar = self._nested_gather(self.tr_loss).mean().item() + + # reset tr_loss to zero + self.tr_loss -= self.tr_loss + + logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) + logs["learning_rate"] = self._get_learning_rate() + + self._globalstep_last_logged = self.state.global_step + + self.log(logs) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="Iterative SFT", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/judges.py b/testbed/huggingface__trl/trl/trainer/judges.py new file mode 100644 index 0000000000000000000000000000000000000000..7822a24d3a76b8bfbe641e381003509e8363d4fa --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/judges.py @@ -0,0 +1,457 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import concurrent.futures +import logging +from abc import ABC, abstractmethod +from typing import List, Optional, Union + +import numpy as np +from accelerate import Accelerator +from huggingface_hub import InferenceClient +from transformers.utils import is_openai_available + +from ..import_utils import is_llm_blender_available + + +if is_llm_blender_available(): + import llm_blender + +if is_openai_available(): + from openai import OpenAI + + +DEFAULT_PAIRWISE_SYSTEM_PROMPT = '''I require a leaderboard for various large language models. I'll provide you with prompts given to these models and their corresponding outputs. Your task is to assess these responses, and select the model that produces the best output from a human perspective. + +## Instruction + +{{ + "instruction": """{prompt}""", +}} + +## Model Outputs + +Here are the unordered outputs from the models. Each output is associated with a specific model, identified by a unique model identifier. + +{{ + {{ + "model_identifier": "0", + "output": """{response0}""" + }}, + {{ + "model_identifier": "1", + "output": """{response1}""" + }} +}} + +## Task + +Evaluate the models on the basis of the quality and relevance of their results, and select the model that generated the best result. Reply with the identifier of the best model. Our evaluation will only take into account the first character of your answer, so make sure it contains only one of the identifiers and nothing else (no quotation marks, no spaces, no new lines, ...). +''' + + +class BaseJudge(ABC): + """ + Base class for judges. The subclasses of this class should implement the `judge` method. + """ + + @abstractmethod + def judge(self, prompts: List[str], completions: List[str], shuffle_order: bool = True) -> List: + raise NotImplementedError("Judge subclasses must implement the `judge` method.") + + +class BaseRankJudge(ABC): + """ + Base class for LLM ranking judges. + + **Example**: + ```python + class MyRankJudge(BaseRankJudge): + def judge(self, prompts, completions, shuffle_order=True): + return ... # Your ranking logic here + + judge = MyRankJudge() + judge.judge( + prompts=["The capital of France is", "The capital of Germany is"], + completions=[[" Paris", " Marseille", "Lyon"], [" Munich", " Berlin"]] + ) # [[0, 1, 2], [1, 0]] + ``` + """ + + @abstractmethod + def judge(self, prompts: List[str], completions: List[List[str]], shuffle_order: bool = True) -> List[List[int]]: + """ + Judge the completion for the given prompts and return the ranks of each completion. + + Args: + prompts (`List[str]`): + List of prompts. + completions (`List[List[str]]`): + List of completions list, where each element is a list of completions for the corresponding prompt. + shuffle_order (`bool`, *optional*, defaults to `True`): + Whether to shuffle the order of the completions to avoid positional bias. + + Returns: + `List[List[int]]`: + List of lists of idxs, where each list contains the ranks of the completions for the corresponding + prompt. E.g., `[1, 2, 0]` means that the second completion (`idx=1`) is the best, followed by the + third, and then the first. + """ + raise NotImplementedError("Judge subclasses must implement the `judge` method.") + + +class BasePairwiseJudge(BaseJudge): + """ + Base class for pairwise judges. + """ + + @abstractmethod + def judge(self, prompts: List[str], completions: List[List[str]], shuffle_order: bool = True) -> List[int]: + """ + Judge the completion pairs for the given prompts. + + Args: + prompts (`List[str]`): + List of prompts. + completions (`List[List[str]]`): + List of completions pairs, where each element is a pair of completions for the corresponding prompt. + shuffle_order (`bool`, *optional*, defaults to `True`): + Whether to shuffle the order of the completions to avoid positional bias. + + Returns: + `List[int]`: + List of idxs, where each idx is the rank of the best completion for the corresponding prompt. + E.g., `1` means that the second completion (`idx=1`) is the best. + + Note: + If the judge returns `-1` for any prompt, it indicates that the inner process used to compute the + preference has failed. For instance, this could occur if the underlying language model returned an invalid + answer. In such cases, the caller should handle these invalid indices appropriately, possibly by + implementing fallback logic or error handling. + """ + raise NotImplementedError("Judge subclasses must implement the `judge` method.") + + +class BaseBinaryJudge(BaseJudge): + """ + Base class for binary judges. + """ + + @abstractmethod + def judge( + self, + prompts: List[str], + completions: List[str], + gold_completions: Optional[List[str]] = None, + shuffle_order: bool = True, + ) -> List[int]: + """ + Judge the completion for a given prompt. Used to assess if a completion satisfies a constraint. + + This base class should be used to implement binary evaluations as done in section 4.1.4 of the + [CGPO paper](https://huggingface.co/papers/2409.20370). + It is relevant for assessing whether or not a prompt completion pair satisfies a specific contraint. + + Args: + prompts (`List[str]`): List of prompts. + completions (`List[str]`): List of completions. + gold_completions (`List[str]`, `optional`): List of gold completions if it exists. + shuffle_order (`bool`): Whether to shuffle the order of the completions to avoid positional bias. + + Returns: + List[int]: A list of binary labels: + - 1 indicates that the completion satisfies the evaluated constraint. + - 0 indicates that the completion does not satisfy the evaluated constraint. + + Note: + If the judge returns -1 for any prompt, it indicates that the inner process used to compute the preference has failed. + For instance, this could occur if the underlying language model or rule based contraint returned an invalid answer. + In such cases, the caller should handle these invalid indices appropriately, possibly by implementing fallback logic or error handling. + """ + raise NotImplementedError("Judge subclasses must implement the `judge` method.") + + +class PairRMJudge(BasePairwiseJudge): + """ + LLM judge based on the PairRM model from AllenAI. + + This judge uses the PairRM model to rank pairs of completions for given prompts. It's designed for pairwise + comparison of language model outputs. The PairRM model is loaded using the llm-blender library and runs on the + default Accelerator device. + + **Attributes**: + + blender (`llm_blender.Blender`): + An instance of the Blender class from llm-blender. + + **Example**: + ```python + >>> pairrm_judge = PairRMJudge() + >>> prompts = ["Translate 'hello' to French", "What's the capital of Japan?"] + >>> completions = [["Bonjour", "Salut"], ["Kyoto", "Tokyo"]] + >>> results = pairrm_judge.judge(prompts, completions) + >>> print(results) # [0, 1] (indicating the first completion is preferred for the first prompt and the second) + ``` + + + + This class requires the llm-blender library to be installed. Install it with: `pip install llm-blender`. + + + """ + + def __init__(self): + if not is_llm_blender_available(): + raise ValueError("llm-blender is not installed. Please install it with `pip install llm-blender`.") + self.blender = llm_blender.Blender() + self.blender.loadranker("llm-blender/PairRM", device=Accelerator().device) + + def judge( + self, + prompts: List[str], + completions: List[List[str]], + shuffle_order: bool = True, + return_scores: bool = False, + temperature: float = 1.0, + ) -> List[Union[int, float]]: + """ + Judge the completion pairs for the given prompts using the PairRM model. + + Args: + prompts (`List[str]`): + List of prompts to judge. + completions (`List[List[str]]`): + List of completion pairs for each prompt. + shuffle_order (`bool`, *optional*, defaults to `True`): + Whether to shuffle the order of the completions to avoid positional bias. + return_scores (`bool`, *optional*, defaults to `False`): + If `True`, return probability scores of the first completion instead of ranks (i.e. a *soft-judge*). + temperature (`float`, *optional*, defaults to `1.0`): + Temperature for scaling logits if `return_scores` is True. + + Returns: + `Union[List[int, float]]`: + If `return_scores` is `False`, returns a list of ranks (`0` or `1`) for each prompt, indicating which + completion is preferred. + If `return_scores` is `True`, returns softmax probabilities for the first completion. + + Raises: + `ValueError`: + If the number of completions per prompt is not exactly 2. + + Note: + Unlike llm-blender, ranks are 0-indexed (`0` means the first completion is preferred). + """ + + if len(completions[0]) != 2: + raise ValueError("PairRM judge requires exactly 2 completions per prompt.") + + # Shuffle the order of the completions to avoid positional bias + if shuffle_order: + flip_mask = np.random.choice([True, False], size=len(prompts)) + completions = [pair[::-1] if flip else pair for flip, pair in zip(flip_mask, completions)] + + # Rank the completions + ranks = self.blender.rank(prompts, completions, return_scores=return_scores, disable_tqdm=True) + if not return_scores: + ranks -= 1 # PairRM rank is 1-indexed, so we subtract 1 to make it 0-indexed + else: + # scale the logits by temperature + ranks /= temperature + + # Flip back the ranks or scores to the original order if needed + if shuffle_order: + ranks[flip_mask] = ranks[flip_mask][:, ::-1] + + # Return the ranks or score probability + if return_scores: + logit_max = np.amax(ranks, axis=-1, keepdims=True) + exp_logit_shifted = np.exp(ranks - logit_max) + probs = exp_logit_shifted / np.sum(exp_logit_shifted, axis=-1, keepdims=True) + return probs[:, 0].tolist() + else: + return ranks[:, 0].tolist() + + +class HfPairwiseJudge(BasePairwiseJudge): + """ + Pairwise judge based on the Hugging Face API with chat completion. + + This judge is relevant for assessing the quality chat models, where the completion is a response to a given prompt. + + Args: + model (`str`, *optional*, defaults to `"meta-llama/Meta-Llama-3-70B-Instruct"`): + Model to use for the judge. + token (`str`, *optional*): + Hugging Face API token to use for the [`huggingface_hub.InferenceClient`]. + system_prompt (`str` or `None`, *optional*, defaults to `None`): + The system prompt to be used for the judge. If not provided, a default prompt is used. Note that the system + prompt should contain the following placeholders: `{prompt}`, `{response0}`, and `{response1}`. Also, the + inference is called with `max_tokens=1`, consequently the system prompt should ask for a single token + response. + """ + + def __init__( + self, + model="meta-llama/Meta-Llama-3-70B-Instruct", + token: Optional[str] = None, + system_prompt: Optional[str] = None, + ): + self.client = InferenceClient(model=model, token=token) + self.system_prompt = system_prompt or DEFAULT_PAIRWISE_SYSTEM_PROMPT + + def judge(self, prompts: List[str], completions: List[List[str]], shuffle_order: bool = True) -> List[int]: + # Shuffle the order of the completions to avoid positional bias + if shuffle_order: + flip_mask = np.random.choice([True, False], size=len(prompts)) + completions = [pair[::-1] if flip else pair for flip, pair in zip(flip_mask, completions)] + + # Define a function to get the rank for a single prompt, will be called concurrently + def get_rank(prompt, candidates): + content = self.system_prompt.format(prompt=prompt, response0=candidates[0], response1=candidates[1]) + completion = self.client.chat_completion(messages=[{"role": "user", "content": content}], max_tokens=1) + response = completion.choices[0].message.content + if response in ["0", "1"]: + return int(response) + else: + logging.debug(f"Invalid response from the judge model: '{response}'. Returning -1.") + return -1 + + # Call the completions concurrently + with concurrent.futures.ThreadPoolExecutor() as executor: + ranks = list(executor.map(get_rank, prompts, completions)) + + # Flip back the ranks to the original order if needed + if shuffle_order: + ranks = [ranks[i] if not flip else 1 - ranks[i] for i, flip in enumerate(flip_mask)] + + # Return the ranks + return ranks + + +class OpenAIPairwiseJudge(BasePairwiseJudge): + """ + Judge based on the OpenAI API. + + This judge is relevant for assessing the quality chat models, where the completion is a response to a given prompt. + + Args: + model (`str`, *optional*, defaults to `"gpt-4-turbo-preview"`): + Model to use for the judge. + system_prompt (`str` or `None`, *optional*, defaults to `None`): + System prompt to be used for the judge. If not provided, a default prompt is used. Note that the system + prompt should contain the following placeholders: `{prompt}`, `{response0}`, and `{response1}`. Also, the + inference is called with `max_tokens=1`, consequently the system prompt should ask for a single token + response. + max_requests (`int` or `None`, *optional*, defaults to `1000`): + Maximum number of requests to make to the OpenAI API. If set to `None`, there is no limit. + """ + + def __init__( + self, model="gpt-4-turbo-preview", system_prompt: Optional[str] = None, max_requests: Union[int, None] = 1_000 + ): + if not is_openai_available(): + raise ValueError("OpenAI client is not installed. Please install it with 'pip install openai'.") + self.client = OpenAI() + self.model = model + self.system_prompt = system_prompt or DEFAULT_PAIRWISE_SYSTEM_PROMPT + self.max_requests = max_requests + self.num_requests = 0 + self._warned = False + + def judge(self, prompts: List[str], completions: List[List[str]], shuffle_order: bool = True) -> List[int]: + # Check if the limit of requests is reached, if so, use random choice instead + if self.max_requests is not None and self.num_requests >= self.max_requests: + if not self._warned: # Print the warning only once + logging.warning( + f"Reached the maximum number of requests ({self.max_requests}). From now on, returning -1 instead. " + " To increase the limit, set `max_requests` to a higher value, or to `None` for no limit." + ) + self._warned = True + return [-1] * len(prompts) + + # Shuffle the order of the completions to avoid positional bias + if shuffle_order: + flip_mask = np.random.choice([True, False], size=len(prompts)) + completions = [pair[::-1] if flip else pair for flip, pair in zip(flip_mask, completions)] + + # Define a function to get the rank for a single prompt, will be called concurrently + def get_rank(prompt, candidates): + content = self.system_prompt.format(prompt=prompt, response0=candidates[0], response1=candidates[1]) + messages = [{"role": "user", "content": content}] + completion = self.client.chat.completions.create(model=self.model, messages=messages, max_tokens=1) + response = completion.choices[0].message.content + if response in ["0", "1"]: + return int(response) + else: + logging.debug(f"Invalid response from the judge model: '{response}'. Returning -1.") + return -1 + + # Call the completions concurrently + with concurrent.futures.ThreadPoolExecutor() as executor: + ranks = list(executor.map(get_rank, prompts, completions)) + + # Flip back the ranks to the original order if needed + if shuffle_order: + ranks = [ranks[i] if not flip else 1 - ranks[i] for i, flip in enumerate(flip_mask)] + + # Update the number of requests + self.num_requests += len(prompts) + + # Return the ranks + return ranks + + +class AllTrueJudge(BaseBinaryJudge): + """ + Unify the decision of multiple [`BaseBinaryJudge`] instances. + + Returns `1` only if all inner binary judges return `1`. If any judge returns `0`, it returns `0`. + If any judge returns `-1`, indicating a failure in its process, this judge will also return `-1`. + + Implements the Mixture of Judges as described in the [CGPO paper](https://huggingface.co/papers/2409.20370). + + Args: + judges (`List[BaseBinaryJudge]`): A list of [`BaseBinaryJudge`] instances whose decisions will be unified. + """ + + def __init__(self, judges: List[BaseBinaryJudge]): + self.judges = judges + + def judge( + self, + prompts: List[str], + completions: List[str], + gold_completions: Optional[List[str]] = None, + shuffle_order: bool = True, + ) -> List[int]: + all_binary_judgments = [ + judge.judge(prompts, completions, gold_completions, shuffle_order) for judge in self.judges + ] + output = [] + for binary_judgments in zip(*all_binary_judgments): + # Check that all values are in {0, 1, -1} + if any(binary_judgment not in {0, 1, -1} for binary_judgment in binary_judgments): + raise ValueError( + f"Invalid binary judgment: {binary_judgments}, expected list of values in {{0, 1, -1}}." + ) + + # Unify the decision + if -1 in binary_judgments: + output.append(-1) + elif all(binary_judgment == 1 for binary_judgment in binary_judgments): + output.append(1) + else: + output.append(0) + return output diff --git a/testbed/huggingface__trl/trl/trainer/kto_config.py b/testbed/huggingface__trl/trl/trainer/kto_config.py new file mode 100644 index 0000000000000000000000000000000000000000..3acca53bdeee6d82e8150ca61fa7525c88ca44a0 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/kto_config.py @@ -0,0 +1,99 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Literal, Optional + +from transformers import TrainingArguments + + +@dataclass +class KTOConfig(TrainingArguments): + r""" + Configuration class for the [`KTOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + learning_rate (`float`, *optional*, defaults to `5e-7`): + Initial learning rate for [`AdamW`] optimizer. The default value replaces that of + [`~transformers.TrainingArguments`]. + max_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_prompt_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the prompt. This argument is required if you want to use the default data collator. + max_completion_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. + loss_type (`str`, *optional*, defaults to `"kto"`): + Type of loss to use. Possible values are: + + - `"kto"`: KTO loss from the [KTO](https://huggingface.co/papers/2402.01306) paper. + - `"apo_zero_unpaired"`: Unpaired variant of APO-zero loss from the [APO](https://huggingface.co/papers/2408.06266) paper. + + desirable_weight (`float`, *optional*, defaults to `1.0`): + Desirable losses are weighed by this factor to counter unequal number of desirable and undesirable paris. + undesirable_weight (`float`, *optional*, defaults to `1.0`): + Undesirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs. + label_pad_token_id (`int`, *optional*, defaults to `-100`): + Label pad token id. This argument is required if you want to use the default data collator. + padding_value (`Optional[int]`, *optional*, defaults to `None`): + Padding value to use. If `None`, the padding value of the tokenizer is used. + truncation_mode (`str`, *optional*, defaults to `"keep_end"`): + Truncation mode to use when the prompt is too long. Possible values are `"keep_end"` or `"keep_start"`. + This argument is required if you want to use the default data collator. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from both the model and the reference model to W&B during + evaluation. + is_encoder_decoder (`Optional[bool]`, *optional*, defaults to `None`): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): + Whether to precompute reference model log probabilities for training and evaluation datasets. This is + useful when training without the reference model to reduce the total GPU memory needed. + model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + ref_model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the reference model + from a string. + dataset_num_proc: (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + """ + + learning_rate: float = 1e-6 + max_length: Optional[int] = None + max_prompt_length: Optional[int] = None + max_completion_length: Optional[int] = None + beta: float = 0.1 + loss_type: Literal["kto", "apo_zero_unpaired"] = "kto" + desirable_weight: float = 1.0 + undesirable_weight: float = 1.0 + label_pad_token_id: int = -100 + padding_value: Optional[int] = None + truncation_mode: str = "keep_end" + generate_during_eval: bool = False + is_encoder_decoder: Optional[bool] = None + disable_dropout: bool = True + precompute_ref_log_probs: bool = False + model_init_kwargs: Optional[Dict[str, Any]] = None + ref_model_init_kwargs: Optional[Dict[str, Any]] = None + dataset_num_proc: Optional[int] = None diff --git a/testbed/huggingface__trl/trl/trainer/kto_trainer.py b/testbed/huggingface__trl/trl/trainer/kto_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..17ad779a5a92850bde82430a540edc0e02a26790 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/kto_trainer.py @@ -0,0 +1,1531 @@ +# KTO Authors: Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, and Douwe Kiela +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +import os +import random +import textwrap +import warnings +from collections import defaultdict +from contextlib import contextmanager, nullcontext +from copy import deepcopy +from operator import itemgetter +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Tuple, Union + +import numpy as np +import torch +import torch.amp as amp +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from accelerate.utils import is_deepspeed_available, tqdm +from datasets import Dataset, concatenate_datasets +from torch.utils.data import DataLoader, SequentialSampler +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainerCallback, + TrainingArguments, + is_wandb_available, +) +from transformers.trainer_utils import EvalLoopOutput, has_length +from transformers.utils import is_peft_available +from transformers.utils.deprecation import deprecate_kwarg + +from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt, maybe_unpair_preference_dataset +from ..models import PreTrainedModelWrapper, create_reference_model +from .kto_config import KTOConfig +from .utils import ( + DPODataCollatorWithPadding, + disable_dropout_in_model, + generate_model_card, + pad_to_length, + peft_module_casting_to_bf16, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + +if is_deepspeed_available(): + import deepspeed + +if TYPE_CHECKING: + from transformers import PreTrainedModel, PreTrainedTokenizer + +RUNNING_NAME = "running.pt" + + +def _get_kl_dataset(batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]: + """ + Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of completions. + For best results, the mismatched outputs y' used to estimate the KL term for a batch should be the same set as the matched + outputs y used to estimate the rewards in that batch, just paired with different x. + """ + batch["answer_input_ids"] = [batch["answer_input_ids"][-1]] + batch["answer_input_ids"][:-1] + batch["answer_attention_mask"] = [batch["answer_attention_mask"][-1]] + batch["answer_attention_mask"][:-1] + return batch + + +def _tokenize( + batch: Dict[str, List[Any]], + tokenizer: "PreTrainedTokenizer", +) -> Dict[str, List[Any]]: + """Tokenize a batch from a KTO specific dataset.""" + prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False) + prompt_input_ids = prompt_tokenized["input_ids"] + prompt_attention_mask = prompt_tokenized["attention_mask"] + prompt_and_completion = [prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"])] + full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False) + full_input_ids = full_tokenized["input_ids"] + full_attention_mask = full_tokenized["attention_mask"] + + answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids)] + answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask)] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids)] + # Prepare input tokens for token by token comparison + full_input_ids = [np.array(f) for f in full_input_ids] + for full, concat in zip(full_input_ids, full_concat_input_ids): + if len(full) != len(concat): + raise ValueError( + "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length." + ) + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = [len(p) for p in prompt_input_ids] + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx)): + if not np.array_equal(p, f[:r]): + response_token_ids_start_idx[idx] -= 1 + + prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx)] + prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] + + for p, m in zip(prompt_input_ids, prompt_attention_mask): + if len(p) != len(m): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx)] + answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] + + output = dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + answer_input_ids=answer_input_ids, + answer_attention_mask=answer_attention_mask, + ) + + return output + + +def _process_tokens(example: Dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> Dict: + """Process tokens of a KTO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation + in case the prompt + completion responses is/are too long. First + we truncate the prompt; if we're still too long, we truncate the completion. + + We also create the labels for the completion responses, which are of length equal to + the sum of the length of the prompt and the completion response, with + label_pad_token_id for the prompt tokens. + """ + prompt = example["prompt"] + completion = example["completion"] + + batch = { + f"{kwargs['prefix']}prompt": prompt, + f"{kwargs['prefix']}completion": completion, + f"{kwargs['prefix']}label": example["label"], + } + + if not kwargs["is_encoder_decoder"]: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + + if not isinstance(completion, str): + raise ValueError(f"completion should be an str but got {type(completion)}") + + # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer + all_tokens = { + "prompt_input_ids": example["prompt_input_ids"], + "prompt_attention_mask": example["prompt_attention_mask"], + "answer_input_ids": example["answer_input_ids"], + "answer_attention_mask": example["answer_attention_mask"], + } + + # calculate max length by checking if BOS/EOS is already there + max_length = kwargs["max_length"] + bos_token_id = kwargs["tokenizer"].bos_token_id + eos_token_id = kwargs["tokenizer"].eos_token_id + if len(all_tokens["prompt_input_ids"]) > 0 and bos_token_id != all_tokens["prompt_input_ids"][0]: + max_length -= 1 + if len(all_tokens["answer_input_ids"]) > 0 and eos_token_id != all_tokens["answer_input_ids"][-1]: + max_length -= 1 + + # if combined sequence is too long (> max_length - 1 for BOS token - 1 for EOS), truncate the prompt + if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: + for k in ["prompt_input_ids", "prompt_attention_mask"]: + if kwargs["truncation_mode"] == "keep_start": + all_tokens[k] = all_tokens[k][: kwargs["max_prompt_length"]] + elif kwargs["truncation_mode"] == "keep_end": + all_tokens[k] = all_tokens[k][-kwargs["max_prompt_length"] :] + else: + raise ValueError(f"Unknown truncation mode: {kwargs['truncation_mode']}") + + # if that's still too long, truncate the response + if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: + for k in ["answer_input_ids", "answer_attention_mask"]: + all_tokens[k] = all_tokens[k][: max_length - kwargs["max_prompt_length"]] + + # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens + batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"] + batch[f"{kwargs['prefix']}completion_input_ids"] = ( + all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"] + ) + batch[f"{kwargs['prefix']}completion_attention_mask"] = ( + all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"] + ) + + # add BOS, which affects both prompt and the full completion + if bos_token_id is not None: + if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]: + batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}prompt_input_ids" + ] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}prompt_attention_mask" + ] + batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[ + f"{kwargs['prefix']}completion_input_ids" + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + # add EOS, which affects only the full completion + if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]: + batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [ + eos_token_id + ] + batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[ + f"{kwargs['prefix']}completion_attention_mask" + ] + [1] + + batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:] + batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [ + kwargs["label_pad_token_id"] + ] * len(batch[f"{kwargs['prefix']}prompt_input_ids"]) + else: + completion_tokens = kwargs["tokenizer"]( + completion, truncation=True, max_length=kwargs["max_completion_length"], add_special_tokens=True + ) + prompt_tokens = kwargs["tokenizer"]( + prompt, truncation=True, max_length=kwargs["max_prompt_length"], add_special_tokens=True + ) + + batch[f"{kwargs['prefix']}prompt_input_ids"] = prompt_tokens["input_ids"] + batch[f"{kwargs['prefix']}prompt_attention_mask"] = prompt_tokens["attention_mask"] + + batch[f"{kwargs['prefix']}completion_labels"] = completion_tokens["input_ids"] + batch[f"{kwargs['prefix']}completion_attention_mask"] = completion_tokens["attention_mask"] + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch[f"{kwargs['prefix']}completion_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["completion_labels"]) + ) + + return batch + + +class KTOTrainer(Trainer): + r""" + Initialize KTOTrainer. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForSequenceClassification`. + ref_model (`PreTrainedModelWrapper`): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no + reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. + args (`KTOConfig`): + The arguments to use for training. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + data_collator (`transformers.DataCollator`, *optional*, defaults to `None`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Dict`, defaults to `None`): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. + disable_dropout (`bool`, defaults to `True`): + Whether or not to disable dropouts in `model` and `ref_model`. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + model_adapter_name (`str`, defaults to `None`): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`str`, defaults to `None`): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + """ + + _tag_names = ["trl", "kto"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.14.0", raise_if_both_names=True) + def __init__( + self, + model: Union[PreTrainedModel, nn.Module, str] = None, + ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + args: KTOConfig = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + data_collator: Optional[DataCollator] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None, + model_adapter_name: Optional[str] = None, + ref_adapter_name: Optional[str] = None, + ): + if type(args) is TrainingArguments: + raise ValueError("Please use `KTOConfig` instead TrainingArguments.") + + if not isinstance(model, str) and ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, you must mass a copy of it, or `None` if you use peft." + ) + + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the KTOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + torch_dtype = model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the KTOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + model_init_kwargs["torch_dtype"] = torch_dtype + + if args.ref_model_init_kwargs is None: + ref_model_init_kwargs = {} + elif not isinstance(ref_model, str): + raise ValueError( + "You passed ref_model_kwargs to the KTOTrainer. But your ref_model is already instantiated." + ) + else: + ref_model_init_kwargs = args.ref_model_init_kwargs + torch_dtype = ref_model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the KTOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + ref_model_init_kwargs["torch_dtype"] = torch_dtype + + if isinstance(model, str): + warnings.warn( + "You passed a model_id to the KTOTrainer. This will automatically create an " + "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you." + ) + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + if isinstance(ref_model, str): + warnings.warn( + "You passed a ref model_id to the KTOTrainer. This will automatically create an " + "`AutoModelForCausalLM`" + ) + ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs) + + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + + if not is_peft_available() and peft_config is not None: + raise ValueError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it with `pip install peft` to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + # if model is a peft model and we have a peft_config, we merge and unload it first + if isinstance(model, PeftModel): + model = model.merge_and_unload() + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not is_wandb_available(): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases to be installed." + " Please install with `pip install wandb` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + self.is_peft_model = is_peft_available() and isinstance(model, PeftModel) + self.model_adapter_name = model_adapter_name + self.ref_adapter_name = ref_adapter_name + + if ref_model: + self.ref_model = ref_model + elif self.is_peft_model or args.precompute_ref_log_probs: + # The `model` with adapters turned off will be used as the reference model + self.ref_model = None + else: + self.ref_model = create_reference_model(model) + + if processing_class is None: + raise ValueError( + "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding" + ) + if args.max_length is None: + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `max_length` in the KTOTrainer's init" + " it will be set to `512` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_length = 512 + if args.max_length is not None: + max_length = args.max_length + + if args.max_prompt_length is None: + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `max_prompt_length` in the KTOTrainer's init" + " it will be set to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_prompt_length = 128 + if args.max_prompt_length is not None: + max_prompt_length = args.max_prompt_length + + max_completion_length = None + if args.max_completion_length is None and self.is_encoder_decoder: + warnings.warn( + "When using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the KTOTrainer's init" + " it will be set to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_completion_length = 128 + if args.max_completion_length is not None and self.is_encoder_decoder: + max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + label_pad_token_id=args.label_pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your KTOConfig" + " we have set it for you, but you should do it yourself in the future.", + UserWarning, + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + if args.disable_dropout: + disable_dropout_in_model(model) + if self.ref_model is not None: + disable_dropout_in_model(self.ref_model) + + self.loss_type = args.loss_type + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.label_pad_token_id = args.label_pad_token_id + self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id + self.max_prompt_length = max_prompt_length + self.truncation_mode = args.truncation_mode + self.max_completion_length = max_completion_length + self.processing_class = processing_class + self.precompute_ref_log_probs = args.precompute_ref_log_probs + + # Not all losses require a KL calculation + self.calculate_KL = True + if self.loss_type in ["apo_zero_unpaired"]: + self.calculate_KL = False + + # Since ref_logs are precomputed on the first call to get_train/eval_dataloader + # keep track of first called to avoid computation of future calls + self._precomputed_train_ref_log_probs = False + self._precomputed_eval_ref_log_probs = False + + # metric + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # KTO parameter + self.beta = args.beta + self.desirable_weight = args.desirable_weight + self.undesirable_weight = args.undesirable_weight + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + warnings.warn( + "You set `output_router_logits` to True in the model config, but `router_aux_loss_coef` is set to 0.0," + " meaning the auxiliary loss will not be used." + ) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().local_main_process_first(): + # Extract the prompt if needed + train_dataset = train_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset" + ) + # Unpair the dataset if needed + train_dataset = maybe_unpair_preference_dataset( + train_dataset, args.dataset_num_proc, desc="Unpairing train dataset" + ) + # Apply the chat template if needed + train_dataset = train_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + desc="Applying chat template to train dataset", + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset" + ) + eval_dataset = maybe_unpair_preference_dataset( + eval_dataset, args.dataset_num_proc, desc="Unpairing eval dataset" + ) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + desc="Applying chat template to eval dataset", + ) + + # Tokenize and prepare the training datasets + train_dataset = train_dataset.map( + _tokenize, + batched=True, + fn_kwargs={"tokenizer": self.processing_class}, + num_proc=args.dataset_num_proc, + desc="Tokenizing train dataset", + ) + + fn_kwargs = { + "prefix": "", + "is_encoder_decoder": self.is_encoder_decoder, + "tokenizer": self.processing_class, + "max_length": self.max_length, + "truncation_mode": self.truncation_mode, + "label_pad_token_id": self.label_pad_token_id, + "max_prompt_length": self.max_prompt_length, + "max_completion_length": self.max_completion_length, + } + + train_dataset = train_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized train dataset", + ) + + # Tokenize and prepare the eval datasets + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + _tokenize, + fn_kwargs={"tokenizer": self.processing_class}, + batched=True, + num_proc=args.dataset_num_proc, + desc="Tokenizing eval dataset", + ) + + eval_dataset = eval_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + desc="Processing tokenized eval dataset", + ) + + # Get KL datasets if needed + if self.calculate_KL: + if args.per_device_train_batch_size <= 1: + raise ValueError( + "Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward." + ) + + # create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size + # i.e., (x_1, y_1), ..., (x_n, y_n) --> (x_1, y_n), ..., (x_n, y_1) = (x'_1, y'_1), ..., (x'_n, y'_n) + train_kl_dataset = train_dataset.map( + _get_kl_dataset, + batched=True, + batch_size=args.per_device_train_batch_size, + num_proc=args.dataset_num_proc, + desc="Extracting KL train dataset", + ) + + fn_kwargs["prefix"] = "KL_" + train_kl_dataset = train_kl_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + remove_columns=[c for c in train_kl_dataset.column_names if c in train_dataset.column_names], + desc="Processing tokenized train KL dataset", + ) + + # merge the datasets + train_dataset = concatenate_datasets([train_dataset, train_kl_dataset], axis=1) + + if eval_dataset is not None: + # Get KL dataset + eval_kl_dataset = eval_dataset.map( + _get_kl_dataset, + batched=True, + batch_size=args.per_device_train_batch_size, + num_proc=args.dataset_num_proc, + desc="Extracting eval KL dataset", + ) + + eval_kl_dataset = eval_kl_dataset.map( + _process_tokens, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + remove_columns=[c for c in eval_kl_dataset.column_names if c in eval_dataset.column_names], + desc="Processing tokenized eval KL dataset", + ) + + # merge the datasets + eval_dataset = concatenate_datasets([eval_dataset, eval_kl_dataset], axis=1) + + # calculate dataset desirability balance + num_desirable = max(sum(train_dataset["label"]), 1) + num_undesirable = max(len(train_dataset["label"]) - num_desirable, 1) # "label" is binary + + if num_desirable != num_undesirable: + # The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306 + des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2) + des_weight_upper_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2) + und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2) + und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2) + + des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound + und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound + + if not (des_weight_in_range or und_weight_in_range): + warnings.warn( + f""" + You have different amounts of desirable/positive and undesirable/negative examples but the + weights on the desirable and undesirable losses don't seem to be in an ideal range. Based + on your data, we recommend EITHER desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] + or undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). + See the documentation on how to optimally set these weights.""", + UserWarning, + ) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + # Deepspeed Zero-3 does not support precompute_ref_log_probs + if self.is_deepspeed_enabled: + if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: + raise ValueError( + "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." + ) + + if self.ref_model is None: + if not (self.is_peft_model or self.precompute_ref_log_probs): + raise ValueError( + "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" + ) + else: + if self.is_deepspeed_enabled: + self.ref_model = self._prepare_deepspeed(self.ref_model) + else: + self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) + + def _prepare_deepspeed(self, model: PreTrainedModelWrapper): + # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + + if model is not None: + if hasattr(model, "config"): + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0) + if config_kwargs["zero_optimization"]["stage"] != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with self.accelerator.unwrap_model( + self.model + ).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext(): + if self.ref_adapter_name: + self.model.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.set_adapter(self.model_adapter_name or "default") + + def get_train_dataloader(self) -> DataLoader: + """ + Returns the training [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. + """ + + if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_train_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) + reference_completion_logps = [] + reference_KL_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): + reference_completion_logp, reference_KL_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + if self.calculate_KL: + reference_KL_logp = self.accelerator.gather_for_metrics(reference_KL_logp) + reference_KL_logps.append(reference_KL_logp.cpu()) + + self.train_dataset = self.train_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + + if self.calculate_KL: + self.train_dataset = self.train_dataset.add_column( + name="reference_KL_logps", column=torch.cat(reference_KL_logps).float().numpy() + ) + + self._precomputed_train_ref_log_probs = True + + return super().get_train_dataloader() + + def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: + """ + Returns the evaluation [`~torch.utils.data.DataLoader`]. + + Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. + + Args: + eval_dataset (`torch.utils.data.Dataset`, *optional*): + If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted + by the `model.forward()` method are automatically removed. It must implement `__len__`. + """ + if eval_dataset is None and self.eval_dataset is None: + raise ValueError("Trainer: evaluation requires an eval_dataset.") + eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset + + if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: + dataloader_params = { + "batch_size": self.args.per_device_eval_batch_size, + "collate_fn": self.data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "shuffle": False, + } + + # prepare dataloader + data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) + + reference_completion_logps = [] + reference_KL_logps = [] + + for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): + reference_completion_logp, reference_KL_logp = self.compute_reference_log_probs(padded_batch) + + reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) + reference_completion_logps.append(reference_completion_logp.cpu()) + + if self.calculate_KL: + reference_KL_logp = self.accelerator.gather_for_metrics(reference_KL_logp) + reference_KL_logps.append(reference_KL_logp.cpu()) + + eval_dataset = eval_dataset.add_column( + name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() + ) + if self.calculate_KL: + eval_dataset = eval_dataset.add_column( + name="reference_KL_logps", column=torch.cat(reference_KL_logps).float().numpy() + ) + + # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs + if self.eval_dataset is not None: + self.eval_dataset = eval_dataset + self._precomputed_eval_ref_log_probs = True + + return super().get_eval_dataloader(eval_dataset=eval_dataset) + + def compute_reference_log_probs(self, padded_batch: Dict) -> Dict: + """Computes log probabilities of the reference model for a single padded batch of a KTO specific dataset.""" + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + if self.is_encoder_decoder: + completion_logits = self.model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + if self.calculate_KL: + KL_logits = self.model( + padded_batch["KL_prompt_input_ids"], + attention_mask=padded_batch["KL_prompt_attention_mask"], + decoder_input_ids=padded_batch.get("KL_completion_decoder_input_ids"), + labels=padded_batch["KL_completion_labels"], + ).logits + else: + completion_logits = self.model( + padded_batch["completion_input_ids"], + attention_mask=padded_batch["completion_attention_mask"], + ).logits + + if self.calculate_KL: + KL_logits = self.model( + padded_batch["KL_completion_input_ids"], + attention_mask=padded_batch["KL_completion_attention_mask"], + ).logits + else: + if self.is_encoder_decoder: + completion_logits = self.ref_model( + padded_batch["prompt_input_ids"], + attention_mask=padded_batch["prompt_attention_mask"], + decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), + labels=padded_batch["completion_labels"], + ).logits + + if self.calculate_KL: + KL_logits = self.ref_model( + padded_batch["KL_prompt_input_ids"], + attention_mask=padded_batch["KL_prompt_attention_mask"], + decoder_input_ids=padded_batch.get("KL_completion_decoder_input_ids"), + labels=padded_batch["KL_completion_labels"], + ).logits + else: + completion_logits = self.ref_model( + padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"] + ).logits + + if self.calculate_KL: + KL_logits = self.ref_model( + padded_batch["KL_completion_input_ids"], + attention_mask=padded_batch["KL_completion_attention_mask"], + ).logits + + completion_logps = self.get_batch_logps( + completion_logits, + padded_batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + + if self.calculate_KL: + KL_logps = self.get_batch_logps( + KL_logits, + padded_batch["KL_completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + else: + KL_logps = None + + return completion_logps, KL_logps + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + label_pad_token_id: int = -100, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) + average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + else: + # Fixes end-dec RuntimeError + labels = labels.clone() + + loss_mask = labels != label_pad_token_id + + # dummy token; we'll ignore the losses on these tokens later + labels[labels == label_pad_token_id] = 0 + + per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def forward( + self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]] + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + if self.calculate_KL: + KL_logps = None + KL_model_kwargs = ( + { + "input_ids": batch["KL_prompt_input_ids"], + "attention_mask": batch["KL_prompt_attention_mask"], + "labels": batch["KL_completion_labels"], + "decoder_input_ids": batch.get("KL_completion_decoder_input_ids"), + } + if self.is_encoder_decoder + else { + "input_ids": batch["KL_completion_input_ids"], + "attention_mask": batch["KL_completion_attention_mask"], + } + ) + with torch.no_grad(): + KL_logits = model( + **KL_model_kwargs, + ).logits + + KL_logps = self.get_batch_logps( + KL_logits, + batch["KL_completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + else: + KL_logps = None + + model_kwargs = ( + { + "labels": batch["completion_labels"], + "decoder_input_ids": batch.get("completion_decoder_input_ids"), + } + if self.is_encoder_decoder + else {} + ) + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + batch["completion_input_ids"], + attention_mask=batch["completion_attention_mask"], + **model_kwargs, + ) + completion_logits = outputs.logits + + completion_logps = self.get_batch_logps( + completion_logits, + batch["completion_labels"], + average_log_prob=False, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + + if completion_logps.shape[0] != len(batch["label"]): + raise ValueError( + "There is a mismatch between the number of examples in this batch and the number of " + "examples for which an output sequence was predicted." + ) + + chosen_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is False] + + chosen_logps = completion_logps[chosen_idx, ...] + rejected_logps = completion_logps[rejected_idx, ...] + + chosen_logits = completion_logits[chosen_idx, ...] + rejected_logits = completion_logits[rejected_idx, ...] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, KL_logps, outputs.aux_loss) + else: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, KL_logps) + + def kto_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + policy_KL_logps: torch.FloatTensor, + reference_chosen_logps: torch.FloatTensor, + reference_rejected_logps: torch.FloatTensor, + reference_KL_logps: torch.FloatTensor, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute the KTO loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,) + policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,) + policy_KL_logps: Log probabilities of the policy model for the KL responses. Shape: (batch_size,) + reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,) + reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in batch_size,) + reference_KL_logps: Log probabilities of the reference model for the KL responses. Shape: (batch_size,) + + Returns: + A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, KL). + The losses tensor contains the KTO loss for each example in the batch. + The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. + The KL tensor contains the detached KL divergence estimate between the policy and reference models. + """ + if self.calculate_KL: + kl = (policy_KL_logps - reference_KL_logps).mean().detach() + kl = self.accelerator.gather(kl).mean().clamp(min=0) + else: + kl = torch.zeros(1).to(policy_chosen_logps.device) + + # Chosen losses + if policy_chosen_logps.shape[0] != 0 or reference_chosen_logps.shape[0] != 0: + chosen_logratios = policy_chosen_logps - reference_chosen_logps + + if self.loss_type == "kto": + # Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306) + chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl)) + elif self.loss_type == "apo_zero_unpaired": + # Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) + # Use this loss when you believe the chosen outputs are better than your model's default output + chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios) + + chosen_rewards = self.beta * chosen_logratios.detach() + + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + chosen_losses = torch.Tensor([]).to(self.accelerator.device) + chosen_rewards = torch.Tensor([]).to(self.accelerator.device) + + # Rejected losses + if policy_rejected_logps.shape[0] != 0 or reference_rejected_logps.shape[0] != 0: + rejected_logratios = policy_rejected_logps - reference_rejected_logps + + if self.loss_type == "kto": + rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios)) + elif self.loss_type == "apo_zero_unpaired": + rejected_losses = F.sigmoid(self.beta * rejected_logratios) + + rejected_rewards = self.beta * rejected_logratios.detach() + else: + # lists can't be empty -- if they are, then accelerate.gather will hang + rejected_losses = torch.Tensor([]).to(self.accelerator.device) + rejected_rewards = torch.Tensor([]).to(self.accelerator.device) + + losses = torch.cat( + (self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses), + 0, + ) + + return losses, chosen_rewards, rejected_rewards, kl + + def get_batch_loss_metrics( + self, + model, + batch: Dict[str, Union[List, torch.LongTensor]], + ): + """Compute the KTO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()} + + forward_output = self.forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_KL_logps, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + # if reference_logps in batch use them, otherwise use the reference model + if "reference_logps" in batch: + chosen_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is True] + rejected_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is False] + + reference_chosen_logps = batch["reference_logps"][chosen_idx, ...] + reference_rejected_logps = batch["reference_logps"][rejected_idx, ...] + if self.calculate_KL: + reference_KL_logps = batch["reference_KL_logps"] + else: + reference_KL_logps = None + else: + with torch.no_grad(): + if self.ref_model is None: + with self.null_ref_context(): + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + reference_KL_logps, + ) = self.forward(self.model, batch)[:5] + else: + ( + reference_chosen_logps, + reference_rejected_logps, + _, + _, + reference_KL_logps, + ) = self.forward(self.ref_model, batch)[:5] + + losses, chosen_rewards, rejected_rewards, kl = self.kto_loss( + policy_chosen_logps, + policy_rejected_logps, + policy_KL_logps, + reference_chosen_logps, + reference_rejected_logps, + reference_KL_logps, + ) + metrics["kl"] = kl.item() + + num_chosen = torch.Tensor([len(chosen_rewards)]).to(self.accelerator.device) + num_rejected = torch.Tensor([len(rejected_rewards)]).to(self.accelerator.device) + + all_num_chosen = self.accelerator.gather(num_chosen).sum().item() + all_num_rejected = self.accelerator.gather(num_rejected).sum().item() + + if all_num_chosen > 0: + metrics["rewards/chosen_sum"] = self.accelerator.gather(chosen_rewards.nansum()).nansum().item() + metrics["logps/chosen_sum"] = self.accelerator.gather(policy_chosen_logps.nansum()).nansum().item() + metrics["logits/chosen_sum"] = self.accelerator.gather(policy_chosen_logits.nansum()).nansum().item() + metrics["count/chosen"] = all_num_chosen + + if all_num_rejected > 0: + metrics["rewards/rejected_sum"] = self.accelerator.gather(rejected_rewards.nansum()).nansum().item() + metrics["logps/rejected_sum"] = self.accelerator.gather(policy_rejected_logps.nansum()).nansum().item() + metrics["logits/rejected_sum"] = self.accelerator.gather(policy_rejected_logits.nansum()).nansum().item() + metrics["count/rejected"] = all_num_rejected + + loss = losses.nanmean() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + return_outputs=False, + num_items_in_batch=None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: + if not self.use_dpo_data_collator: + warnings.warn( + "compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + compute_loss_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs) + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]: + if self.train_dataset is None or not has_length(self.train_dataset): + return None + return SequentialSampler(self.train_dataset) + + def generate_from_model_and_ref(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch cuda amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + # if reference_output in batch use that otherwise use the reference model + if "reference_output" in batch: + reference_output = batch["reference_output"] + else: + if self.ref_model is None: + with self.null_ref_context(): + reference_output = self.model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + else: + reference_output = self.ref_model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id) + reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True) + + return policy_output_decoded, reference_output_decoded + + def prediction_step( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + prediction_loss_only: bool, + ignore_keys: Optional[List[str]] = None, + ): + if not self.use_dpo_data_collator: + warnings.warn( + "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs) + + # force log the metrics + if self.accelerator.is_main_process: + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["logits/chosen"], + "eval_logits/rejected": metrics["logits/rejected"], + } + logits = torch.tensor( + [v for k, v in logits_dict.items() if k not in ignore_keys], device=self.accelerator.device + ) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: Optional[bool] = None, + ignore_keys: Optional[List[str]] = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. + Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + target_indicies = [i for i in range(len(random_batch["label"])) if random_batch["label"][i] is False] + target_batch = { + "prompt_input_ids": random_batch["prompt_input_ids"][target_indicies], + "prompt_attention_mask": random_batch["prompt_attention_mask"][target_indicies], + "prompt": itemgetter(*target_indicies)(random_batch["prompt"]), + } + policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch) + + self.log( + { + "game_log": wandb.Table( + columns=["Prompt", "Policy", "Ref Model"], + rows=[ + [prompt, pol[len(prompt) :], ref[len(prompt) :]] + for prompt, pol, ref in zip( + target_batch["prompt"], policy_output_decoded, ref_output_decoded + ) + ], + ) + } + ) + self.state.log_history.pop() + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: Dict[str, float]) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`Dict[str, float]`): + The values to log. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # train metrics should have no prefix, eval should have 'eval_' + prefix = "eval_" if train_eval == "eval" else "" + # accumulate average metrics from sums and lengths + for split in ["chosen", "rejected"]: + if f"count/{split}" in self._stored_metrics[train_eval]: + count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item() + for metric in ["rewards", "logps", "logits"]: + logs[f"{prefix}{metric}/{split}"] = ( + torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item() + / count_sum + ) + # delete obsolete metric + del self._stored_metrics[train_eval][f"{metric}/{split}_sum"] + del self._stored_metrics[train_eval][f"count/{split}"] + # calculate reward margin + if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs: + logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"] + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{ethayarajh2024kto, + title = {{KTO: Model Alignment as Prospect Theoretic Optimization}}, + author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela}, + year = 2024, + eprint = {arXiv:2402.01306}, + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="KTO", + trainer_citation=citation, + paper_title="KTO: Model Alignment as Prospect Theoretic Optimization", + paper_id="2402.01306", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/model_config.py b/testbed/huggingface__trl/trl/trainer/model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..5518d1979ea3acd35c7289f4854deac6d404e3b7 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/model_config.py @@ -0,0 +1,98 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import List, Literal, Optional + + +@dataclass +class ModelConfig: + """ + Configuration class for the models. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + model_name_or_path (`Optional[str]`, *optional*, defaults to `None`): + Model checkpoint for weights initialization. + model_revision (`str`, *optional*, defaults to `"main"`): + Specific model version to use. It can be a branch name, a tag name, or a commit id. + torch_dtype (`Optional[Literal["auto", "bfloat16", "float16", "float32"]]`, *optional*, defaults to `None`): + Override the default `torch.dtype` and load the model under this dtype. Possible values are + + - `"bfloat16"`: `torch.bfloat16` + - `"float16"`: `torch.float16` + - `"float32"`: `torch.float32` + - `"auto"`: Automatically derive the dtype from the model's weights. + + trust_remote_code (`bool`, *optional*, defaults to `False`): + Whether to allow for custom models defined on the Hub in their own modeling files. This option should only + be set to `True` for repositories you trust and in which you have read the code, as it will execute code + present on the Hub on your local machine. + attn_implementation (`Optional[str]`, *optional*, defaults to `None`): + Which attention implementation to use. You can run `--attn_implementation=flash_attention_2`, in which case + you must install this manually by running `pip install flash-attn --no-build-isolation`. + use_peft (`bool`, *optional*, defaults to `False`): + Whether to use PEFT for training. + lora_r (`int`, *optional*, defaults to `16`): + LoRA R value. + lora_alpha (`int`, *optional*, defaults to `32`): + LoRA alpha. + lora_dropout (`float`, *optional*, defaults to `0.05`): + LoRA dropout. + lora_target_modules (`Optional[Union[str, List[str]]]`, *optional*, defaults to `None`): + LoRA target modules. + lora_modules_to_save (`Optional[List[str]]`, *optional*, defaults to `None`): + Model layers to unfreeze & train. + lora_task_type (`str`, *optional*, defaults to `"CAUSAL_LM"`): + Task type to pass for LoRA (use `"SEQ_CLS"` for reward modeling). + use_rslora (`bool`, *optional*, defaults to `False`): + Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, instead of + the original default value of `lora_alpha/r`. + load_in_8bit (`bool`, *optional*, defaults to `False`): + Whether to use 8 bit precision for the base model. Works only with LoRA. + load_in_4bit (`bool`, *optional*, defaults to `False`): + Whether to use 4 bit precision for the base model. Works only with LoRA. + bnb_4bit_quant_type (`str`, *optional*, defaults to `"nf4"`): + Quantization type (`"fp4"` or `"nf4"`). + use_bnb_nested_quant (`bool`, *optional*, defaults to `False`): + Whether to use nested quantization. + """ + + model_name_or_path: Optional[str] = None + model_revision: str = "main" + torch_dtype: Optional[Literal["auto", "bfloat16", "float16", "float32"]] = None + trust_remote_code: bool = False + attn_implementation: Optional[str] = None + use_peft: bool = False + lora_r: int = 16 + lora_alpha: int = 32 + lora_dropout: float = 0.05 + lora_target_modules: Optional[List[str]] = None + lora_modules_to_save: Optional[List[str]] = None + lora_task_type: str = "CAUSAL_LM" + use_rslora: bool = False + load_in_8bit: bool = False + load_in_4bit: bool = False + bnb_4bit_quant_type: Literal["fp4", "nf4"] = "nf4" + use_bnb_nested_quant: bool = False + + def __post_init__(self): + if self.load_in_8bit and self.load_in_4bit: + raise ValueError("You can't use 8 bit and 4 bit precision at the same time") + + if isinstance(self.lora_target_modules, list) and len(self.lora_target_modules) == 1: + self.lora_target_modules = self.lora_target_modules[0] diff --git a/testbed/huggingface__trl/trl/trainer/nash_md_config.py b/testbed/huggingface__trl/trl/trainer/nash_md_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2089fed2758ad9cf4169c790501a2340f899be --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/nash_md_config.py @@ -0,0 +1,40 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import List + +from trl.trainer.online_dpo_config import OnlineDPOConfig + + +@dataclass +class NashMDConfig(OnlineDPOConfig): + r""" + Configuration class for the [`NashMDTrainer`]. + + Subclass of [`OnlineDPOConfig`] we can use all its arguments and add the following: + + Parameters: + mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`): + Logit mixture coefficient for the model and reference model. If a list of floats is provided then the + mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the + epochs. + """ + + mixture_coef: List[float] = field(default_factory=lambda: [0.5]) + + def __post_init__(self): + super().__post_init__() + if hasattr(self.mixture_coef, "__len__") and len(self.mixture_coef) == 1: + self.mixture_coef = self.mixture_coef[0] diff --git a/testbed/huggingface__trl/trl/trainer/nash_md_trainer.py b/testbed/huggingface__trl/trl/trainer/nash_md_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..c998174765161164e058e7d7ac25b903df75d60d --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/nash_md_trainer.py @@ -0,0 +1,509 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import textwrap +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import jinja2 +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset, IterableDataset +from transformers import ( + BaseImageProcessor, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_wandb_available, +) +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames +from transformers.utils import is_apex_available + +from ..data_utils import is_conversational, maybe_apply_chat_template +from ..models.modeling_base import GeometricMixtureWrapper +from ..models.utils import unwrap_model_for_generation +from .judges import BasePairwiseJudge +from .nash_md_config import NashMDConfig +from .online_dpo_trainer import OnlineDPOTrainer +from .utils import SIMPLE_CHAT_TEMPLATE, empty_cache, generate_model_card, get_reward, truncate_right + + +if is_apex_available(): + from apex import amp + + +if is_wandb_available(): + import wandb + + +class NashMDTrainer(OnlineDPOTrainer): + r""" + Initialize NashMDTrainer as a subclass of [`OnlineDPOConfig`]. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model (`PreTrainedModelWrapper`): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no + reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. + reward_model (`transformers.PreTrainedModel`): + The reward model to score completions with, preferably an `AutoModelForSequenceClassification`. + judge (`BasePairwiseJudge`): + The judge to use for pairwise comparison of model completions. + args (`NashMDConfig`): + The NashMD config arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + peft_config (`Dict`): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "nash-md"] + + def __init__( + self, + model: Union[PreTrainedModel, nn.Module] = None, + ref_model: Union[PreTrainedModel, nn.Module] = None, + reward_model: Union[PreTrainedModel, nn.Module, None] = None, + judge: Optional[BasePairwiseJudge] = None, + args: Optional[NashMDConfig] = None, + data_collator: Optional[Callable] = None, + train_dataset: Optional[Union[Dataset, IterableDataset]] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + ) -> None: + super().__init__( + model=model, + ref_model=ref_model, + reward_model=reward_model, + judge=judge, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_class=processing_class, # for now, NashMDTrainer can't use any reward model + peft_config=peft_config, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + self._mixture_coef = self.args.mixture_coef + + # Overwrite the stats dictionary to include NashMD specific statistics + self.stats = { + # Remove "non_score_reward", "rlhf_reward", "scores_margin" + # Add "mixture_coef" + "loss/kl": [], + "objective/entropy": [], + "loss/score": [], + "rewards/probabilities": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + "val/model_contain_eos_token": [], + "val/ref_contain_eos_token": [], + "beta": [], + "mixture_coef": [], + } + if self.reward_model is not None: + self.stats["rewards/chosen"] = [] + self.stats["rewards/rejected"] = [] + + @property + def mixture_coef(self): + if isinstance(self._mixture_coef, list): + epoch = self.state.epoch + return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1] + else: + return self._mixture_coef + + def _generate_completions(self, model, prompts): + with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model: + model_output = unwrapped_model.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + ref_model = model if self.ref_model is None else self.ref_model + with torch.no_grad(), unwrap_model_for_generation(ref_model, self.accelerator) as unwrapped_ref_model: + mixture_model = GeometricMixtureWrapper( + model=unwrapped_model, + ref_model=unwrapped_ref_model, + generation_config=self.generation_config, + mixture_coef=self.mixture_coef, + device=self.accelerator.device, + ) + + mixture_output = mixture_model.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + return model_output, mixture_output + + def _process_completions(self, model_output, mixture_output, prompts): + context_length = prompts["input_ids"].shape[1] + + # Process model completions + model_completion_ids = model_output[:, context_length:] + model_completion_ids, model_completion_mask = truncate_right( + model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + model_data = { + "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), + "raw": prompts["raw"], + } + + # Process reference model completions + mixture_completion_ids = mixture_output[:, context_length:] + mixture_completion_ids, mixture_completion_mask = truncate_right( + mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + mixture_data = { + "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1), + "raw": prompts["raw"], + } + + return model_data, mixture_data + + def _compute_rewards(self, model_data, mixture_data, context_length): + with torch.no_grad(): + _, model_scores, _ = get_reward( + self.reward_model, model_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + _, mixture_scores, _ = get_reward( + self.reward_model, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + + # Apply EOS penalty if needed + if self.args.missing_eos_penalty is not None: + model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + model_scores[~model_contain_eos] -= self.args.missing_eos_penalty + mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty + + return model_scores, mixture_scores + + def _compute_judge(self, model_data, mixture_data, context_length): + prompts = model_data["raw"] + model_data_completions = self.processing_class.batch_decode( + model_data["input_ids"][:, context_length:], skip_special_tokens=True + ) + model_data_completions = [completion.strip() for completion in model_data_completions] + + mixture_data_completions = self.processing_class.batch_decode( + mixture_data["input_ids"][:, context_length:], skip_special_tokens=True + ) + mixture_data_completions = [completion.strip() for completion in mixture_data_completions] + if is_conversational({"prompt": prompts[0]}): + model_data_completions = [ + [{"role": "assistant", "content": completion}] for completion in model_data_completions + ] + environment = jinja2.Environment() + template = environment.from_string(SIMPLE_CHAT_TEMPLATE) + prompts = [template.render(messages=message) for message in prompts] + model_data_completions = [template.render(messages=completion) for completion in model_data_completions] + + mixture_data_completions = [ + [{"role": "assistant", "content": completion}] for completion in mixture_data_completions + ] + mixture_data_completions = [ + template.render(messages=completion) for completion in mixture_data_completions + ] + + probability = self.judge.judge( + prompts, + list(zip(model_data_completions, mixture_data_completions)), + return_scores=True, + ) + return torch.tensor(probability, device=model_data["input_ids"].device) + + def _compute_logprobs(self, model, model_data, context_length): + def compute_logprobs_for_data(m, data): + output = m(data["input_ids"], attention_mask=data["attention_mask"]) + logits = output.logits[:, context_length - 1 : -1] + logprobs = F.log_softmax(logits, dim=-1) + token_logprobs = torch.gather(logprobs, 2, data["input_ids"][:, context_length:].unsqueeze(-1)).squeeze(-1) + return token_logprobs + + # Compute logprobs for model completions under the model + model_logprobs_model_data = compute_logprobs_for_data(model, model_data) + + # Compute logprobs of model completions under the reference model + with torch.no_grad(): + if self.ref_model is None: + with model.disable_adapter(): + ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) + else: + ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) + + # Mask padding tokens + model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 + model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + + return (model_logprobs_model_data, ref_logprobs_model_data) + + def _compute_losses( + self, + model_logprobs_model_data, + ref_logprobs_model_data, + probability, + ): + # reinforce score where 0.5 is a control variate + score = (probability - 0.5) * model_logprobs_model_data.sum(1) + + # kl divergence via reinforce + with torch.no_grad(): + log_ratio = model_logprobs_model_data - ref_logprobs_model_data + kl_div_log = log_ratio.sum(1) + kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1) + + # final loss + loss = self.beta * kl_div_loss - score + + return loss.mean(), score, kl_div_log + + def _log_statistics( + self, + model_data, + mixture_data, + model_logprobs_model_data, + ref_logprobs_model_data, + probability, + score, + kl_div, + context_length, + model_scores=None, + mixture_scores=None, + ): + # Helper function to gather and compute mean + def gather_mean(tensor): + return self.accelerator.gather(tensor).mean().item() + + # Log score + self.stats["loss/score"].append(gather_mean(score)) + # Log KL divergence + self.stats["loss/kl"].append(gather_mean(kl_div)) + + # Log logprobs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum)) + self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum)) + + # Log rewards + if self.reward_model is not None: + self.stats["rewards/chosen"].append(gather_mean(model_scores)) + self.stats["rewards/rejected"].append(gather_mean(mixture_scores)) + + # Log probabilities + self.stats["rewards/probabilities"].append(gather_mean(probability)) + + # Calculate entropy for model data + entropy_model_data = -model_logprobs_model_data.sum(1) + self.stats["objective/entropy"].append(gather_mean(entropy_model_data)) + + # Calculate margins + margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum + self.stats["rewards/margins"].append(gather_mean(margin)) + + # Calculate accuracy + accuracy = (margin > 0).float() + self.stats["rewards/accuracies"].append(gather_mean(accuracy)) + + # Log EOS token statistics + model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) + self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float())) + + # Log beta and mixture coef + self.stats["beta"].append(self.beta) + self.stats["mixture_coef"].append(self.mixture_coef) + + def training_step( + self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # need the prompt_ only + inputs = self._prepare_inputs(inputs) + context_length = inputs["prompt_input_ids"].shape[1] + prompts = { + "input_ids": inputs["prompt_input_ids"], + "attention_mask": inputs["prompt_attention_mask"], + "raw": prompts, + } + del inputs + + # Sample completions from both the model and the reference model + model_output, mixture_output = self._generate_completions(model, prompts) + + # Process model completions + model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts) + + # Compute rewards + if self.reward_model is not None: + model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length) + # probability of the model data vs the mixture data + probability = F.sigmoid(model_scores - mixture_scores) + else: + model_scores, mixture_scores = None, None + probability = self._compute_judge(model_data, mixture_data, context_length) + + # Compute logprobs + model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length) + + # Compute loss + loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability) + + # Log everything + self._log_statistics( + model_data, + mixture_data, + model_logprobs_model_data.detach(), + ref_logprobs_model_data, + probability, + score.detach(), + kl_div.detach(), + context_length, + model_scores, + mixture_scores, + ) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + if self.use_apex: + with amp.scale_loss(loss, self.optimizer) as scaled_loss: + scaled_loss.backward() + else: + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @inproceedings{munos2024nash, + title = {Nash Learning from Human Feedback}, + author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot}, + year = 2024, + booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, + publisher = {OpenReview.net}, + url = {https://openreview.net/forum?id=Y5AmNYiyCQ} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="Nash-MD", + trainer_citation=citation, + paper_title="Nash Learning from Human Feedback", + paper_id="2312.00886", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/online_dpo_config.py b/testbed/huggingface__trl/trl/trainer/online_dpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..16ae8105fc59ff3bf30ff8885f6df617beb271fa --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/online_dpo_config.py @@ -0,0 +1,77 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import List, Literal, Optional + +from transformers import TrainingArguments + + +@dataclass +class OnlineDPOConfig(TrainingArguments): + r""" + Configuration class for the [`OnlineDPOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + learning_rate (`float`, *optional*, defaults to `5e-7`): + Initial learning rate for [`AdamW`] optimizer. The default value replaces that of + [`~transformers.TrainingArguments`]. + reward_model_path (`Optional[str]`, *optional*, defaults to `None`): + Path to the reward model. Either `judge` or `reward_model_path` must be set, but not both. + judge (`Optional[str]`, *optional*, defaults to `None`): + Name of the judge to use. Either `judge` or `reward_model_path` must be set, but not both. + max_new_tokens (`int`, *optional*, defaults to `64`): + Maximum number of tokens to generate per completion. + temperature (`float`, *optional*, defaults to `0.9`): + Temperature for sampling. The higher the temperature, the more random the completions. + missing_eos_penalty (`Optional[float]`, *optional*, defaults to `None`): + Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage + to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive + value. + beta (`float` or `list[float]`, *optional*, defaults to `0.1`): + Parameter controlling the deviation from the reference model. Higher β means less deviation from the + reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in + the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β is + selected for each new epoch and the last β is used for the rest of the epochs. + loss_type (`str`, *optional*, defaults to `"sigmoid"`): + Type of loss to use. Possible values are: + + - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. + - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. + + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + """ + + learning_rate: float = 5e-7 + reward_model_path: Optional[str] = None + judge: Optional[str] = None + max_new_tokens: int = 64 + temperature: float = 0.9 + missing_eos_penalty: Optional[float] = None + beta: List[float] = field(default_factory=lambda: [0.1]) + loss_type: Literal["sigmoid", "ipo"] = "sigmoid" + dataset_num_proc: Optional[int] = None + disable_dropout: bool = True + + def __post_init__(self): + super().__post_init__() + if hasattr(self.beta, "__len__") and len(self.beta) == 1: + self.beta = self.beta[0] diff --git a/testbed/huggingface__trl/trl/trainer/online_dpo_trainer.py b/testbed/huggingface__trl/trl/trainer/online_dpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..23ca6dd047e24561951971a8db156f33519357c0 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/online_dpo_trainer.py @@ -0,0 +1,728 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import textwrap +import warnings +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import datasets +import jinja2 +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.data +import transformers +from datasets import Dataset +from packaging import version +from torch.utils.data import DataLoader, IterableDataset +from transformers import ( + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainerCallback, + is_apex_available, + is_wandb_available, +) +from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR, EvalPrediction, seed_worker +from transformers.training_args import OptimizerNames +from transformers.utils import is_peft_available, is_sagemaker_mp_enabled, logging +from transformers.utils.deprecation import deprecate_kwarg + +from ..data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template +from ..models import create_reference_model +from ..models.utils import unwrap_model_for_generation +from .judges import BasePairwiseJudge +from .online_dpo_config import OnlineDPOConfig +from .utils import ( + SIMPLE_CHAT_TEMPLATE, + DPODataCollatorWithPadding, + disable_dropout_in_model, + empty_cache, + generate_model_card, + get_reward, + prepare_deepspeed, + truncate_right, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model + +if is_apex_available(): + from apex import amp + + +if is_sagemaker_mp_enabled(): + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") + +else: + IS_SAGEMAKER_MP_POST_1_10 = False + +if is_wandb_available(): + import wandb + +logger = logging.get_logger(__name__) + + +class OnlineDPOTrainer(Trainer): + r""" + Initialize OnlineDPOTrainer. + + Args: + model (`transformers.PreTrainedModel` or `torch.nn.Module`): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model (`transformers.PreTrainedModel` or `torch.nn.Module` or `None`): + The reference model to use for training. If None is specified, the reference model will be created from + the model. + reward_model (`transformers.PreTrainedModel` or `torch.nn.Module` or `None`): + The reward model to score completions with, preferably an `AutoModelForSequenceClassification`. + judge (`BasePairwiseJudge`): + The judge to use for pairwise comparison of model completions. + args (`OnlineDPOConfig`): + The online DPO config arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + peft_config (`Dict`): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "online-dpo"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.14.0", raise_if_both_names=True) + def __init__( + self, + model: Union[PreTrainedModel, nn.Module], + ref_model: Union[PreTrainedModel, nn.Module, None] = None, + reward_model: Union[PreTrainedModel, nn.Module, None] = None, + judge: Optional[BasePairwiseJudge] = None, + args: Optional[OnlineDPOConfig] = None, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Union[Dataset, IterableDataset, "datasets.Dataset"]] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset], "datasets.Dataset"]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + reward_processing_class: Optional[PreTrainedTokenizerBase] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + ) -> None: + if ref_model is model: + raise ValueError( + "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " + "same as `model`, either omit the `ref_model` argument or pass `None`." + ) + + self.ref_model = ref_model + + if reward_model is not None and judge is not None: + warnings.warn( + "Both `reward_model` and `judge` are provided. Please choose provide only one of them. " + "Ignoring `judge` and using `reward_model`." + ) + judge = None + elif reward_model is None and judge is None: + raise ValueError("Either `reward_model` or `judge` must be provided.") + + self.reward_model = reward_model + self.reward_processing_class = reward_processing_class + self.judge = judge + + if args.missing_eos_penalty is not None and judge is not None: + raise ValueError("`missing_eos_penalty` is not supported when `judge` is provided.") + + if args is None: + raise ValueError("`args` must be provided.") + + # Check that the processing_class is provided + if processing_class is None: + raise ValueError("`processing_class` must be provided.") + + # Convert to PEFT model if peft_config is provided + if peft_config is not None: + # Check if PEFT is available + if not is_peft_available(): + raise ImportError( + "PEFT is not available and passed `peft_config`. Please install PEFT with " + "`pip install peft` to use it." + ) + + # If the model is already a PeftModel, we need to merge and unload it. + # Further information here: https://huggingface.co/docs/trl/dpo_trainer#reference-model-considerations-with-peft + if isinstance(model, PeftModel): + model = model.merge_and_unload() + + # Get peft model with the given config + model = get_peft_model(model, peft_config) + + # Disable dropout in the model if specified + if args.disable_dropout: + disable_dropout_in_model(model) + + # Handle the ref_model + # Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to + # get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create + # the ref model from the model by copying it and disable the gradients and set it in evaluation mode. + if ref_model is None: # No ref model provided, the most common case + if peft_config is None: + self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode + else: + self.ref_model = None # we don't need a ref model here, we can just disable the adapter. + else: # rare case, the user provided a ref model + self.ref_model = ref_model + self.ref_model.eval() + + # Disable the gradient and set the reward model in eval mode + if self.reward_model is not None: + self.reward_model.eval() + + # Define the collator is not provided + if data_collator is None: + data_collator = DPODataCollatorWithPadding(pad_token_id=processing_class.pad_token_id) + + self.stats = { + "objective/kl": [], + "objective/entropy": [], + "objective/non_score_reward": [], + "rewards/chosen": [], + "rewards/rejected": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + "val/contain_eos_token": [], + "beta": [], + } + if self.reward_model is not None: + self.stats["objective/rlhf_reward"] = [] + self.stats["objective/scores_margin"] = [] + self.stats["objective/scores"] = [] + + self.generation_config = GenerationConfig( + max_new_tokens=args.max_new_tokens, + temperature=args.temperature, + top_k=0, + top_p=1.0, + do_sample=True, + use_cache=False if args.gradient_checkpointing else True, + ) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + self._beta = args.beta + + # Placed after the super().__init__ because we need self.is_deepspeed_enabled and self.accelerator + if self.is_deepspeed_enabled: + if self.reward_model is not None: + self.reward_model = prepare_deepspeed( + self.reward_model, args.per_device_train_batch_size, args.fp16, args.bf16 + ) + self.ref_model = prepare_deepspeed(self.ref_model, args.per_device_train_batch_size, args.fp16, args.bf16) + else: + if self.ref_model is not None: + self.ref_model = self.ref_model.to(self.accelerator.device) + if self.reward_model is not None: + self.reward_model = self.reward_model.to(self.accelerator.device) + + @property + def beta(self): + if isinstance(self._beta, list): + epoch = self.state.epoch + return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1] + else: + return self._beta + + @staticmethod + def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> Dict[str, Any]: + """Tokenize a single row from a DPO specific dataset.""" + if not is_encoder_decoder: + batch = tokenizer(feature["prompt"], add_special_tokens=False) + # Add BOS token to head of prompt. Avoid adding if it's already there + if tokenizer.bos_token_id is not None: + prompt_len_input_ids = len(batch["input_ids"]) + if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]: + batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"] + batch["attention_mask"] = [1] + batch["attention_mask"] + else: + batch = tokenizer(feature["prompt"], add_special_tokens=True) + batch = {f"prompt_{key}": value for key, value in batch.items()} + return batch + + # Same as Trainer.get_train_dataloader but skip the "remove_unused_columns". + @wraps(Trainer.get_train_dataloader) + def get_train_dataloader(self) -> DataLoader: + if self.train_dataset is None: + raise ValueError("Trainer: training requires a train_dataset.") + + train_dataset = self.train_dataset + data_collator = self.data_collator + dataloader_params = { + "batch_size": self._train_batch_size, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(train_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_train_sampler() + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["worker_init_fn"] = seed_worker + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + + return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) + + # Same as Trainer.get_eval_dataloader but skip the "remove_unused_columns". + @wraps(Trainer.get_eval_dataloader) + def get_eval_dataloader(self, eval_dataset: Optional[Union[str, Dataset]] = None) -> DataLoader: + if eval_dataset is None and self.eval_dataset is None: + raise ValueError("Trainer: evaluation requires an eval_dataset.") + + # If we have persistent workers, don't do a fork bomb especially as eval datasets + # don't change during training + dataloader_key = eval_dataset if isinstance(eval_dataset, str) else "eval" + if ( + hasattr(self, "_eval_dataloaders") + and dataloader_key in self._eval_dataloaders + and self.args.dataloader_persistent_workers + ): + return self.accelerator.prepare(self._eval_dataloaders[dataloader_key]) + + eval_dataset = ( + self.eval_dataset[eval_dataset] + if isinstance(eval_dataset, str) + else eval_dataset + if eval_dataset is not None + else self.eval_dataset + ) + data_collator = self.data_collator + + dataloader_params = { + "batch_size": self.args.eval_batch_size, + "collate_fn": data_collator, + "num_workers": self.args.dataloader_num_workers, + "pin_memory": self.args.dataloader_pin_memory, + "persistent_workers": self.args.dataloader_persistent_workers, + } + + if not isinstance(eval_dataset, torch.utils.data.IterableDataset): + dataloader_params["sampler"] = self._get_eval_sampler(eval_dataset) + dataloader_params["drop_last"] = self.args.dataloader_drop_last + dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor + + # accelerator.free_memory() will destroy the references, so + # we need to store the non-prepared version + eval_dataloader = DataLoader(eval_dataset, **dataloader_params) + if self.args.dataloader_persistent_workers: + if hasattr(self, "_eval_dataloaders"): + self._eval_dataloaders[dataloader_key] = eval_dataloader + else: + self._eval_dataloaders = {dataloader_key: eval_dataloader} + + return self.accelerator.prepare(eval_dataloader) + + def training_step( + self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input. + # We do this on-the-fly to enable the use of reward models and policies with different tokenizers / chat templates. + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # Sample 2 completions per prompt of size `max_new_tokens` from the model + inputs = self._prepare_inputs(inputs) + num_examples, context_length = inputs["prompt_input_ids"].shape + prompt_ids = inputs["prompt_input_ids"].repeat(2, 1) + prompt_mask = inputs["prompt_attention_mask"].repeat(2, 1) + with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model: + output = unwrapped_model.generate( + input_ids=prompt_ids, + attention_mask=prompt_mask, + generation_config=self.generation_config, + ) + del inputs + + completion_ids = output[:, context_length:] + completion_ids, completion_mask = truncate_right( + completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + contain_eos_token = torch.any(completion_ids == self.processing_class.eos_token_id, dim=-1) + prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1) + prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1) + + # Get the logprobs of the completions from the model + output = model(prompt_completion_ids, attention_mask=prompt_completion_mask) + # There is 1 offset, because the model predict the next token + logits = output.logits[:, context_length - 1 : -1] + # Turn logits into logprobs + all_logprobs = F.log_softmax(logits, dim=-1) + # Take the completion tokens logprob + logprobs = torch.take_along_dim(all_logprobs, completion_ids.unsqueeze(-1), dim=2).squeeze(-1) + del output, logits, all_logprobs # free memory + + # Same for the reference model + with torch.no_grad(): + if self.ref_model is not None: + ref_output = self.ref_model(prompt_completion_ids, attention_mask=prompt_completion_mask) + else: # peft case: we just need to disable the adapter + with self.model.disable_adapter(): + ref_output = self.model(prompt_completion_ids, attention_mask=prompt_completion_mask) + ref_logits = ref_output.logits[:, context_length - 1 : -1] + ref_all_logprobs = F.log_softmax(ref_logits, dim=-1) + ref_logprobs = torch.take_along_dim(ref_all_logprobs, completion_ids.unsqueeze(-1), dim=2).squeeze(-1) + del ref_output, ref_logits, ref_all_logprobs # free memory + + # Decode the completions, and format them if the input is conversational + device = prompt_completion_ids.device + completions_ids = prompt_completion_ids[:, context_length:] + completions = self.processing_class.batch_decode(completions_ids, skip_special_tokens=True) + if is_conversational({"prompt": prompts[0]}): + completions = [[{"role": "assistant", "content": completion}] for completion in completions] + + # Get the reward from the reward model or judge + if self.judge is not None: + # Once formatted, conversational data may contain special tokens (such as <|im_start|>) that are not + # directly understandable by the judge and could alter its judgment. To avoid this and make the judge + # independent of the model's chat template, we use the raw conversation data, and apply our own chat + # template to it. + if is_conversational({"prompt": prompts[0]}): + environment = jinja2.Environment() + template = environment.from_string(SIMPLE_CHAT_TEMPLATE) + prompts = [template.render(messages=prompt) for prompt in prompts] + completions = [template.render(messages=completion) for completion in completions] + + ranks_of_first_completion = self.judge.judge( + prompts, list(zip(completions[:num_examples], completions[num_examples:])) + ) + + # convert ranks to a True/False mask: + # when rank == 0, it means the first completion is the best + # when rank == 1, it means the second completion is the best + mask = torch.tensor([rank == 0 for rank in ranks_of_first_completion], device=device) + else: + # The reward model may not have the same chat template or tokenizer as the model, so we need to use the + # raw data (string), apply the chat template (if needed), and tokenize it with the reward processing class. + prompts = 2 * prompts # repeat the prompt: [prompt0, prompt1] -> [prompt0, prompt1, prompt0, prompt1] + if is_conversational({"prompt": prompts[0]}): + examples = [{"prompt": p, "completion": c} for p, c in zip(prompts, completions)] + examples = [apply_chat_template(example, self.reward_processing_class) for example in examples] + prompts = [example["prompt"] for example in examples] + completions = [example["completion"] for example in examples] + + # Tokenize the prompts + prompts_ids = self.reward_processing_class( + prompts, padding=True, return_tensors="pt", padding_side="left" + )["input_ids"].to(device) + context_length = prompts_ids.shape[1] + + # Tokenize the completions + completions_ids = self.reward_processing_class( + completions, padding=True, return_tensors="pt", padding_side="right" + )["input_ids"].to(device) + + # Concatenate the prompts and completions and get the reward + prompt_completion_ids = torch.cat((prompts_ids, completions_ids), dim=1) + with torch.inference_mode(): + _, scores, _ = get_reward( + self.reward_model, prompt_completion_ids, self.reward_processing_class.pad_token_id, context_length + ) + + # Filter completion. Ensure that the sample contains stop_token_id + # Completions not passing that filter will receive a lower score. + if self.args.missing_eos_penalty is not None: + scores[~contain_eos_token] -= self.args.missing_eos_penalty + + # Split the scores in 2 (the prompts of the first half are the same as the second half) + first_half, second_half = scores.split(num_examples) + + # Get the indices of the chosen and rejected examples + mask = first_half >= second_half + + num_examples_range = torch.arange(num_examples, device=device) + chosen_indices = num_examples_range + (~mask * num_examples) + rejected_indices = num_examples_range + (mask * num_examples) + + # Build tensor so that the first half is the chosen examples and the second half the rejected examples + cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected + cr_logprobs = logprobs[cr_indices] + cr_ref_logprobs = ref_logprobs[cr_indices] + + # mask out the padding tokens + padding_mask = ~completion_mask.bool() + cr_padding_mask = padding_mask[cr_indices] + + cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1) + cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1) + + # Split the chosen and rejected examples + chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, num_examples) + chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, num_examples) + pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum + ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum + + logits = pi_logratios - ref_logratios + + if self.args.loss_type == "sigmoid": + losses = -F.logsigmoid(self.beta * logits) + elif self.args.loss_type == "ipo": + losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise NotImplementedError(f"invalid loss type {self.loss_type}") + + loss = losses.mean() + + # Log everything + if self.reward_model is not None: + scores_margin = scores[chosen_indices] - scores[rejected_indices] + self.stats["objective/scores_margin"].append(self.accelerator.gather(scores_margin.mean()).mean().item()) + self.stats["objective/scores"].append(self.accelerator.gather(scores.mean()).mean().item()) + self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item()) + self.stats["logps/chosen"].append(self.accelerator.gather(chosen_logprobs_sum).mean().item()) + self.stats["logps/rejected"].append(self.accelerator.gather(rejected_logprobs_sum).mean().item()) + + kl = logprobs - ref_logprobs + mean_kl = kl.sum(1).mean() + self.stats["objective/kl"].append(self.accelerator.gather(mean_kl).mean().item()) + non_score_reward = (-self.beta * kl).sum(1) + mean_non_score_reward = non_score_reward.mean() + self.stats["objective/non_score_reward"].append(self.accelerator.gather(mean_non_score_reward).mean().item()) + if self.reward_model is not None: + rlhf_reward = scores + non_score_reward + self.stats["objective/rlhf_reward"].append(self.accelerator.gather(rlhf_reward).mean().item()) + mean_entropy = -logprobs.sum(1).mean() + self.stats["objective/entropy"].append(self.accelerator.gather(mean_entropy).mean().item()) + chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum) + gathered_chosen_rewards = self.accelerator.gather(chosen_rewards) + self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item()) + rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum) + gathered_rejected_rewards = self.accelerator.gather(rejected_rewards) + self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item()) + margin = gathered_chosen_rewards - gathered_rejected_rewards + self.stats["rewards/margins"].append(margin.mean().item()) + accuracy = margin > 0 + self.stats["rewards/accuracies"].append(accuracy.float().mean().item()) + self.stats["beta"].append(self.beta) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + + # For LOMO optimizers you need to explicitly use the learnign rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + if self.use_apex: + with amp.scale_loss(loss, self.optimizer) as scaled_loss: + scaled_loss.backward() + else: + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps + + # Same as Trainer._maybe_log_save_evaluate but log our metrics + # start_time defaults to None to allow compatibility with transformers<=4.46 + def _maybe_log_save_evaluate(self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time=None): + if self.control.should_log and self.state.global_step > self._globalstep_last_logged: + logs: Dict[str, float] = {} + + # all_gather + mean() to get average loss over all processes + tr_loss_scalar = self._nested_gather(tr_loss).mean().item() + + # reset tr_loss to zero + tr_loss -= tr_loss + + logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) + if grad_norm is not None: + logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm + logs["learning_rate"] = self._get_learning_rate() + + # Add our metrics + for key, val in self.stats.items(): + logs[key] = sum(val) / len(val) + self.stats = {key: [] for key in self.stats} # reset stats + + self._total_loss_scalar += tr_loss_scalar + self._globalstep_last_logged = self.state.global_step + self.store_flos() + + if version.parse(transformers.__version__) >= version.parse("4.47.0.dev0"): + self.log(logs, start_time) + else: # transformers<=4.46 + self.log(logs) + + metrics = None + if self.control.should_evaluate: + metrics = self._evaluate(trial, ignore_keys_for_eval) + is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial) + + if self.args.save_strategy == "best": + self.control.should_save = is_new_best_metric + + if self.control.should_save: + self._save_checkpoint(model, trial) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + # Copy-pasted from transformers.Trainer to maintain compatibility with earlier versions. + # This can be removed once the minimum transformers version is updated to 4.47. + # Refer to https://github.com/huggingface/trl/pull/2288 for more details. + def _determine_best_metric(self, metrics, trial): + """ + Determine if the model should be saved based on the evaluation metrics. + If args.metric_for_best_model is not set, the loss is used. + Returns: + bool: True if a new best metric was found, else False + """ + is_new_best_metric = False + + if self.args.metric_for_best_model is not None: + metric_to_check = self.args.metric_for_best_model + + if not metric_to_check.startswith("eval_"): + metric_to_check = f"eval_{metric_to_check}" + + try: + metric_value = metrics[metric_to_check] + except KeyError as exc: + raise KeyError( + f"The `metric_for_best_model` training argument is set to '{metric_to_check}', which is not found in the evaluation metrics. " + f"The available evaluation metrics are: {list(metrics.keys())}. Consider changing the `metric_for_best_model` via the TrainingArguments." + ) from exc + + operator = np.greater if self.args.greater_is_better else np.less + + if self.state.best_metric is None: + self.state.best_metric = float("-inf") if self.args.greater_is_better else float("inf") + + if operator(metric_value, self.state.best_metric): + run_dir = self._get_output_dir(trial=trial) + checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" + output_dir = os.path.join(run_dir, checkpoint_folder) + self.state.best_metric = metric_value + self.state.best_model_checkpoint = output_dir + + is_new_best_metric = True + + return is_new_best_metric + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{guo2024direct, + title = {{Direct Language Model Alignment from Online AI Feedback}}, + author = {Shangmin Guo and Biao Zhang and Tianlin Liu and Tianqi Liu and Misha Khalman and Felipe Llinares and Alexandre Ram{\'{e}} and Thomas Mesnard and Yao Zhao and Bilal Piot and Johan Ferret and Mathieu Blondel}, + year = 2024, + eprint = {arXiv:2402.04792} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="Online DPO", + trainer_citation=citation, + paper_title="Direct Language Model Alignment from Online AI Feedback", + paper_id="2402.04792", + ) + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/orpo_config.py b/testbed/huggingface__trl/trl/trainer/orpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2100a1896239229934b5a84358c1d3ba521c8e --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/orpo_config.py @@ -0,0 +1,77 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from transformers import TrainingArguments + + +@dataclass +class ORPOConfig(TrainingArguments): + r""" + Configuration class for the [`ORPOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + learning_rate (`float`, *optional*, defaults to `1e-6`): + Initial learning rate for [`AdamW`] optimizer. The default value replaces that of + [`~transformers.TrainingArguments`]. + max_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + max_prompt_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the prompt. This argument is required if you want to use the default data collator. + max_completion_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the completion. This argument is required if you want to use the default data collator + and your model is an encoder-decoder. + beta (`float`, *optional*, defaults to `0.1`): + Parameter controlling the relative ratio loss weight in the ORPO loss. In the [paper](https://huggingface.co/papers/2403.07691), + it is denoted by λ. In the [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`. + disable_dropout (`bool`, *optional*, defaults to `True`): + Whether to disable dropout in the model. + label_pad_token_id (`int`, *optional*, defaults to `-100`): + Label pad token id. This argument is required if you want to use the default data collator. + padding_value (`Optional[int]`, *optional*, defaults to `None`): + Padding value to use. If `None`, the padding value of the tokenizer is used. + truncation_mode (`str`, *optional*, defaults to `"keep_end"`): + Truncation mode to use when the prompt is too long. Possible values are `"keep_end"` or `"keep_start"`. + This argument is required if you want to use the default data collator. + generate_during_eval (`bool`, *optional*, defaults to `False`): + If `True`, generates and logs completions from the model to W&B during evaluation. + is_encoder_decoder (`Optional[bool]`, *optional*, defaults to `None`): + When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument, + you need to specify if the model returned by the callable is an encoder-decoder model. + model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + """ + + learning_rate: float = 1e-6 + max_length: Optional[int] = None + max_prompt_length: Optional[int] = None + max_completion_length: Optional[int] = None + beta: float = 0.1 + disable_dropout: bool = True + label_pad_token_id: int = -100 + padding_value: Optional[int] = None + truncation_mode: str = "keep_end" + generate_during_eval: bool = False + is_encoder_decoder: Optional[bool] = None + model_init_kwargs: Optional[Dict[str, Any]] = None + dataset_num_proc: Optional[int] = None diff --git a/testbed/huggingface__trl/trl/trainer/orpo_trainer.py b/testbed/huggingface__trl/trl/trainer/orpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e4d3265dd5ebe91cd98850ec5edde0ef132f039a --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/orpo_trainer.py @@ -0,0 +1,1076 @@ +# ORPO Authors: Jiwoo Hong, Noah Lee, and James Thorne +# Official code: https://github.com/xfactlab/orpo +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import os +import random +import textwrap +import warnings +from collections import defaultdict +from contextlib import nullcontext +from copy import deepcopy +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union + +import numpy as np +import torch +import torch.amp as amp +import torch.nn as nn +import torch.nn.functional as F +from accelerate import PartialState +from accelerate.utils import is_deepspeed_available +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForCausalLM, + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + is_torch_xla_available, + is_wandb_available, +) +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalLoopOutput +from transformers.utils import is_peft_available, is_torch_fx_proxy +from transformers.utils.deprecation import deprecate_kwarg + +from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt +from ..models import PreTrainedModelWrapper +from .orpo_config import ORPOConfig +from .utils import ( + DPODataCollatorWithPadding, + add_bos_token_if_needed, + add_eos_token_if_needed, + disable_dropout_in_model, + generate_model_card, + pad_to_length, + peft_module_casting_to_bf16, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training + + +if is_wandb_available(): + import wandb + +if is_deepspeed_available(): + import deepspeed + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +class ORPOTrainer(Trainer): + r""" + Initialize ORPOTrainer. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForSequenceClassification`. + args (`ORPOConfig`): + The ORPO config arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Dict`, defaults to `None`): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + """ + + _tag_names = ["trl", "orpo"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.15.0", raise_if_both_names=True) + def __init__( + self, + model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + args: Optional[ORPOConfig] = None, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None, + ): + if args.model_init_kwargs is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_kwargs to the ORPOTrainer. But your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + torch_dtype = model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the ORPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + model_init_kwargs["torch_dtype"] = torch_dtype + + if isinstance(model, str): + warnings.warn( + "You passed a model_id to the ORPOTrainer. This will automatically create an " + "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you." + ) + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` + # has been called in order to properly call autocast if needed. + self._peft_has_been_casted_to_bf16 = False + + if not is_peft_available() and peft_config is not None: + raise ValueError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + # if model is a peft model and we have a peft_config, we merge and unload it first + if isinstance(model, PeftModel): + model = model.merge_and_unload() + + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # get peft model with the given config + model = get_peft_model(model, peft_config) + if args.bf16 and getattr(model, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(model) + # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager + self._peft_has_been_casted_to_bf16 = True + + # For models that use gradient_checkpointing, we need to attach a hook that enables input + # to explicitly have `requires_grad=True`, otherwise training will either silently + # fail or completely fail. + elif getattr(args, "gradient_checkpointing", False): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if args.generate_during_eval and not is_wandb_available(): + raise ValueError( + "`generate_during_eval=True` requires Weights and Biases to be installed." + " Please install `wandb` to resolve." + ) + + if model is not None: + self.is_encoder_decoder = model.config.is_encoder_decoder + elif args.is_encoder_decoder is None: + raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") + else: + self.is_encoder_decoder = args.is_encoder_decoder + + if self.is_encoder_decoder: + self.decoder_start_token_id = model.config.decoder_start_token_id + self.pad_token_id = model.config.pad_token_id + + if processing_class is None: + raise ValueError("processing_class must be specified to tokenize a ORPO dataset.") + if args.max_length is None: + warnings.warn( + "`max_length` is not set in the ORPOConfig's init" + " it will default to `512` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_length = 512 + else: + max_length = args.max_length + if args.max_prompt_length is None: + warnings.warn( + "`max_prompt_length` is not set in the ORPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + max_prompt_length = 128 + else: + max_prompt_length = args.max_prompt_length + + if args.max_completion_length is None and self.is_encoder_decoder: + warnings.warn( + "When using an encoder decoder architecture, you should set `max_completion_length` in the ORPOConfig's init" + " it will default to `128` by default, but you should do it yourself in the future.", + UserWarning, + ) + self.max_completion_length = 128 + else: + self.max_completion_length = args.max_completion_length + + if data_collator is None: + data_collator = DPODataCollatorWithPadding( + pad_token_id=processing_class.pad_token_id, + label_pad_token_id=args.label_pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + if args.remove_unused_columns: + args.remove_unused_columns = False + # warn users + warnings.warn( + "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" + " we have set it for you, but you should do it yourself in the future.", + UserWarning, + ) + + self.use_dpo_data_collator = True + else: + self.use_dpo_data_collator = False + + if args.disable_dropout: + disable_dropout_in_model(model) + + self.max_length = max_length + self.generate_during_eval = args.generate_during_eval + self.label_pad_token_id = args.label_pad_token_id + self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id + self.max_prompt_length = max_prompt_length + self.truncation_mode = args.truncation_mode + self.processing_class = processing_class + + self.beta = args.beta + self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) + self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) + if self.aux_loss_enabled and self.aux_loss_coef == 0.0: + warnings.warn( + "You set `output_router_logits` to True in the model config, but `router_aux_loss_coef` is set to 0.0," + " meaning the auxiliary loss will not be used." + ) + + self._stored_metrics = defaultdict(lambda: defaultdict(list)) + + # Compute that only on the main process for faster data processing. + # see: https://github.com/huggingface/trl/pull/1255 + with PartialState().local_main_process_first(): + # Extract the prompt if needed, and apply the chat template if needed + train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + train_dataset = train_dataset.map( + maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc + ) + train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + if eval_dataset is not None: + eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, + fn_kwargs={"tokenizer": processing_class}, + num_proc=args.dataset_num_proc, + ) + eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if not hasattr(self, "accelerator"): + raise AttributeError( + "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." + ) + + def _prepare_deepspeed(self, model: PreTrainedModelWrapper): + # Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473 + deepspeed_plugin = self.accelerator.state.deepspeed_plugin + config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config) + + if model is not None: + if hasattr(model, "config"): + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size, + } + ) + + # If ZeRO-3 is used, we shard both the active and reference model. + # Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0) + if config_kwargs["zero_optimization"]["stage"] != 3: + config_kwargs["zero_optimization"]["stage"] = 0 + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + def build_tokenized_answer(self, prompt, answer): + """ + Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. + It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`. + Reference: + https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + """ + + full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) + prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] + + answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] + answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] + + # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` + full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) + + # Prepare input tokens for token by token comparison + full_input_ids = np.array(full_tokenized["input_ids"]) + + if len(full_input_ids) != len(full_concat_input_ids): + raise ValueError("Prompt input ids and answer input ids should have the same length.") + + # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens + # can be merged together when tokenizing prompt+answer. This could result + # on the last token from the prompt being different when tokenized on its own + # vs when done as prompt+answer. + response_token_ids_start_idx = len(prompt_input_ids) + + # If tokenized prompt is different than both prompt+answer, then it means the + # last token has changed due to merging. + if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: + response_token_ids_start_idx -= 1 + + prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] + prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] + + if len(prompt_input_ids) != len(prompt_attention_mask): + raise ValueError("Prompt input ids and attention mask should have the same length.") + + answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] + answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] + + return dict( + prompt_input_ids=prompt_input_ids, + prompt_attention_mask=prompt_attention_mask, + input_ids=answer_input_ids, + attention_mask=answer_attention_mask, + ) + + def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> Dict: + """Tokenize a single row from a ORPO specific dataset. + + At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation + in case the prompt + chosen or prompt + rejected responses is/are too long. First + we truncate the prompt; if we're still too long, we truncate the chosen/rejected. + + We also create the labels for the chosen/rejected responses, which are of length equal to + the sum of the length of the prompt and the chosen/rejected response, with + label_pad_token_id for the prompt tokens. + """ + batch = {} + prompt = feature["prompt"] + chosen = feature["chosen"] + rejected = feature["rejected"] + + if not self.is_encoder_decoder: + # Check issues below for more details + # 1. https://github.com/huggingface/trl/issues/907 + # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 + # 3. https://github.com/LianjiaTech/BELLE/issues/337 + + if not isinstance(prompt, str): + raise ValueError(f"prompt should be an str but got {type(prompt)}") + prompt_tokens = self.processing_class(prompt, add_special_tokens=False) + prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} + + if not isinstance(chosen, str): + raise ValueError(f"chosen should be an str but got {type(chosen)}") + chosen_tokens = self.build_tokenized_answer(prompt, chosen) + + if not isinstance(rejected, str): + raise ValueError(f"rejected should be an str but got {type(rejected)}") + rejected_tokens = self.build_tokenized_answer(prompt, rejected) + + # Last prompt token might get merged by tokenizer and + # it should not be included for generation if that happens + prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) + + chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) + rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) + prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) + + for k, v in prompt_tokens.items(): + prompt_tokens[k] = v[:prompt_len_input_ids] + + # Make sure prompts only have one different token at most an + # and length only differs by 1 at most + num_diff_tokens = sum( + [a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])] + ) + num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) + if num_diff_tokens > 1 or num_diff_len > 1: + raise ValueError( + "Chosen and rejected prompt_input_ids might only differ on the " + "last token due to tokenizer merge ops." + ) + + # add BOS token to head of prompt. Avoid adding if it's already there + prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( + self.processing_class.bos_token_id, + prompt_len_input_ids, + prompt_tokens, + chosen_prompt_len_input_ids, + chosen_tokens, + rejected_prompt_len_input_ids, + rejected_tokens, + ) + + # add EOS token to end of answer. Avoid adding if it's already there + chosen_tokens, rejected_tokens = add_eos_token_if_needed( + self.processing_class.eos_token_id, chosen_tokens, rejected_tokens + ) + + longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) + + # if combined sequence is too long, truncate the prompt + for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + if self.truncation_mode == "keep_start": + for k in ["prompt_input_ids", "prompt_attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_prompt_length] + elif self.truncation_mode == "keep_end": + for k in ["prompt_input_ids", "prompt_attention_mask"]: + answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :] + else: + raise ValueError(f"Unknown truncation mode: {self.truncation_mode}") + + # if that's still too long, truncate the response + for answer_tokens in [chosen_tokens, rejected_tokens]: + if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: + for k in ["input_ids", "attention_mask"]: + answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length] + + # Create labels + chosen_sequence_tokens = { + k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] + } + rejected_sequence_tokens = { + k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] + } + chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] + chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [ + self.label_pad_token_id + ] * len(chosen_tokens["prompt_input_ids"]) + rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] + rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [ + self.label_pad_token_id + ] * len(rejected_tokens["prompt_input_ids"]) + + for k, toks in { + "chosen_": chosen_sequence_tokens, + "rejected_": rejected_sequence_tokens, + "": prompt_tokens, + }.items(): + for type_key, tokens in toks.items(): + if type_key == "token_type_ids": + continue + batch[f"{k}{type_key}"] = tokens + + else: + chosen_tokens = self.processing_class( + chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + rejected_tokens = self.processing_class( + rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True + ) + prompt_tokens = self.processing_class( + prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True + ) + + batch["chosen_labels"] = chosen_tokens["input_ids"] + batch["rejected_labels"] = rejected_tokens["input_ids"] + batch["prompt_input_ids"] = prompt_tokens["input_ids"] + batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] + + if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): + batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["rejected_labels"]) + ) + batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( + labels=torch.tensor(batch["chosen_labels"]) + ) + + if is_torch_xla_available(): + # Pad the sequences to global max_length to avoid TorchXLA recompilation + for k in batch: + if "labels" in k or self.is_encoder_decoder: + pad_value = self.label_pad_token_id + elif k.endswith("_input_ids"): + pad_value = self.padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + batch[k] = batch[k] + [pad_value] * (self.max_length - len(batch[k])) + return batch + + @staticmethod + def concatenated_inputs( + batch: Dict[str, Union[List, torch.LongTensor]], + is_encoder_decoder: bool = False, + label_pad_token_id: int = -100, + padding_value: int = 0, + device: Optional[torch.device] = None, + ) -> Dict[str, torch.LongTensor]: + """Concatenate the chosen and rejected inputs into a single tensor. + + Args: + batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). + is_encoder_decoder: Whether the model is an encoder-decoder model. + label_pad_token_id: The label pad token id. + padding_value: The padding value to use for the concatenated inputs_ids. + device: The device for the concatenated inputs. + + Returns: + A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. + """ + concatenated_batch = {} + + if is_encoder_decoder: + max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) + else: + max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) + + for k in batch: + if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = label_pad_token_id + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("chosen", "concatenated") + concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) + for k in batch: + if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): + if "labels" in k or is_encoder_decoder: + pad_value = label_pad_token_id + elif k.endswith("_input_ids"): + pad_value = padding_value + elif k.endswith("_attention_mask"): + pad_value = 0 + concatenated_key = k.replace("rejected", "concatenated") + concatenated_batch[concatenated_key] = torch.cat( + ( + concatenated_batch[concatenated_key], + pad_to_length(batch[k], max_length, pad_value=pad_value), + ), + dim=0, + ).to(device=device) + + if is_encoder_decoder: + concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) + concatenated_batch["concatenated_attention_mask"] = ( + batch["prompt_attention_mask"].repeat(2, 1).to(device=device) + ) + + return concatenated_batch + + def odds_ratio_loss( + self, + policy_chosen_logps: torch.FloatTensor, + policy_rejected_logps: torch.FloatTensor, + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Compute ORPO's odds ratio (OR) loss for a batch of policy and reference model log probabilities. + + Args: + policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) + policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) + + Returns: + A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). + The losses tensor contains the ORPO loss for each example in the batch. + The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. + The log odds ratio of the chosen responses over the rejected responses ratio for logging purposes. + The `log(sigmoid(log_odds_chosen))` for logging purposes. + """ + + # Derived from Eqs. (4) and (7) from https://huggingface.co/papers/2403.07691 by using log identities and exp(log(P(y|x)) = P(y|x) + log_odds = (policy_chosen_logps - policy_rejected_logps) - ( + torch.log1p(-torch.exp(policy_chosen_logps)) - torch.log1p(-torch.exp(policy_rejected_logps)) + ) + ratio = F.logsigmoid(log_odds) + losses = self.beta * ratio + + chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() + rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() + + return losses, chosen_rewards, rejected_rewards, torch.mean(ratio), torch.mean(log_odds) + + @staticmethod + def get_batch_logps( + logits: torch.FloatTensor, + labels: torch.LongTensor, + average_log_prob: bool = False, + label_pad_token_id: int = -100, + is_encoder_decoder: bool = False, + ) -> torch.FloatTensor: + """Compute the log probabilities of the given labels under the given logits. + + Args: + logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) + labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) + average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. + label_pad_token_id: The label pad token id. + is_encoder_decoder: Whether the model is an encoder-decoder model. + + Returns: + A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. + """ + if logits.shape[:-1] != labels.shape: + raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") + + if not is_encoder_decoder: + labels = labels[:, 1:].clone() + logits = logits[:, :-1, :] + loss_mask = labels != label_pad_token_id + + # dummy token; we'll ignore the losses on these tokens later + labels = torch.where(labels == label_pad_token_id, 0, labels) + + per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2) + + if average_log_prob: + return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) + else: + return (per_token_logps * loss_mask).sum(-1) + + def concatenated_forward( + self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]] + ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: + """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. + + We do this to avoid doing two forward passes, because it's faster for FSDP. + """ + concatenated_batch = self.concatenated_inputs( + batch, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + padding_value=self.padding_value, + device=self.accelerator.device, + ) + len_chosen = batch["chosen_labels"].shape[0] + + model_kwargs = ( + { + "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), + } + if self.is_encoder_decoder + else {} + ) + + if self.aux_loss_enabled: + model_kwargs["output_router_logits"] = True + + outputs = model( + concatenated_batch["concatenated_input_ids"], + attention_mask=concatenated_batch["concatenated_attention_mask"], + use_cache=False, + **model_kwargs, + ) + all_logits = outputs.logits + + def cross_entropy_loss(logits, labels): + if not self.is_encoder_decoder: + # Shift so that tokens < n predict n + logits = logits[..., :-1, :].contiguous() + labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + logits = logits.view(-1, logits.shape[-1]) + labels = labels.view(-1) + # Enable model parallelism + labels = labels.to(logits.device) + loss = loss_fct(logits, labels) + return loss + + if self.is_encoder_decoder: + labels = concatenated_batch["concatenated_labels"].clone() + else: + labels = concatenated_batch["concatenated_input_ids"].clone() + attention_mask = concatenated_batch["concatenated_attention_mask"] + labels = torch.where(attention_mask == 1, labels, self.label_pad_token_id) + + chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) + + all_logps = self.get_batch_logps( + all_logits, + concatenated_batch["concatenated_labels"], + average_log_prob=True, + is_encoder_decoder=self.is_encoder_decoder, + label_pad_token_id=self.label_pad_token_id, + ) + + chosen_logps = all_logps[:len_chosen] + rejected_logps = all_logps[len_chosen:] + + chosen_logits = all_logits[:len_chosen] + rejected_logits = all_logits[len_chosen:] + + if self.aux_loss_enabled: + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss, outputs.aux_loss) + + return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss) + + def get_batch_loss_metrics( + self, + model, + batch: Dict[str, Union[List, torch.LongTensor]], + train_eval: Literal["train", "eval"] = "train", + ): + """Compute the ORPO loss and other metrics for the given batch of inputs for train or test.""" + metrics = {} + + forward_output = self.concatenated_forward(model, batch) + ( + policy_chosen_logps, + policy_rejected_logps, + policy_chosen_logits, + policy_rejected_logits, + policy_nll_loss, + ) = forward_output[:5] + if self.aux_loss_enabled: + aux_loss = forward_output[5] + + losses, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen = self.odds_ratio_loss( + policy_chosen_logps, policy_rejected_logps + ) + # full ORPO loss + loss = policy_nll_loss - losses.mean() + + reward_accuracies = (chosen_rewards > rejected_rewards).float() + + prefix = "eval_" if train_eval == "eval" else "" + metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean() + metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean() + metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean() + metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean() + metrics[f"{prefix}logps/rejected"] = policy_rejected_logps.detach().mean() + metrics[f"{prefix}logps/chosen"] = policy_chosen_logps.detach().mean() + metrics[f"{prefix}logits/rejected"] = policy_rejected_logits.detach().mean() + metrics[f"{prefix}logits/chosen"] = policy_chosen_logits.detach().mean() + metrics[f"{prefix}nll_loss"] = policy_nll_loss.detach().mean() + metrics[f"{prefix}log_odds_ratio"] = log_odds_ratio + metrics[f"{prefix}log_odds_chosen"] = log_odds_chosen + if is_torch_xla_available(): + xm.mark_step() # needed because .item() calls + for k, v in metrics.items(): + metrics[k] = v.item() + if self.aux_loss_enabled: + loss += self.aux_loss_coef * aux_loss + + return loss, metrics + + def compute_loss( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + return_outputs=False, + num_items_in_batch=None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: + if not self.use_dpo_data_collator: + warnings.warn( + "compute_loss is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + + compute_loss_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with compute_loss_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") + + # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: + loss = loss.to(self.args.device) + + # force log the metrics + self.store_metrics(metrics, train_eval="train") + + if return_outputs: + return (loss, metrics) + return loss + + def generate_from_model(self, model, batch: Dict[str, torch.LongTensor]) -> str: + """Generate samples from the model and reference model for the given batch of inputs.""" + + # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with + # the torch cuda amp context manager as some hidden states are silently casted to full precision. + generate_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with generate_context_manager: + policy_output = model.generate( + input_ids=batch["prompt_input_ids"], + attention_mask=batch["prompt_attention_mask"], + max_length=self.max_length, + do_sample=True, + pad_token_id=self.processing_class.pad_token_id, + ) + + policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) + policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) + + return policy_output_decoded + + def prediction_step( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + prediction_loss_only: bool, + ignore_keys: Optional[List[str]] = None, + ): + if not self.use_dpo_data_collator: + warnings.warn( + "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than " + "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator" + ) + if ignore_keys is None: + if hasattr(model, "config"): + ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + prediction_context_manager = amp.autocast("cuda") if self._peft_has_been_casted_to_bf16 else nullcontext() + + with torch.no_grad(), prediction_context_manager: + loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") + + # force log the metrics + self.store_metrics(metrics, train_eval="eval") + + if prediction_loss_only: + return (loss.detach(), None, None) + + # logits for the chosen and rejected samples from model + logits_dict = { + "eval_logits/chosen": metrics["eval_logits/chosen"], + "eval_logits/rejected": metrics["eval_logits/rejected"], + } + logits = tuple(v.unsqueeze(dim=0) for k, v in logits_dict.items() if k not in ignore_keys) + logits = torch.stack(logits).mean(axis=1).to(self.accelerator.device) + labels = torch.zeros(logits.shape[0], device=self.accelerator.device) + + return (loss.detach(), logits, labels) + + def store_metrics(self, metrics: Dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: + for key, value in metrics.items(): + self._stored_metrics[train_eval][key].append(value) + + def evaluation_loop( + self, + dataloader: DataLoader, + description: str, + prediction_loss_only: Optional[bool] = None, + ignore_keys: Optional[List[str]] = None, + metric_key_prefix: str = "eval", + ) -> EvalLoopOutput: + """ + Overriding built-in evaluation loop to store metrics for each batch. + Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. + + Works both with or without labels. + """ + + # Sample and save to game log if requested (for one batch to save time) + if self.generate_during_eval: + # Generate random indices within the range of the total number of samples + num_samples = len(dataloader.dataset) + random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) + + # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader + random_batch_dataset = dataloader.dataset.select(random_indices) + random_batch = self.data_collator(random_batch_dataset) + random_batch = self._prepare_inputs(random_batch) + + policy_output_decoded = self.generate_from_model(self.model, random_batch) + + self.log( + { + "game_log": wandb.Table( + columns=["Prompt", "Policy"], + rows=[ + [prompt, pol[len(prompt) :]] + for prompt, pol in zip(random_batch["prompt"], policy_output_decoded) + ], + ) + } + ) + self.state.log_history.pop() + + # Base evaluation + initial_output = super().evaluation_loop( + dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix + ) + + return initial_output + + def log(self, logs: Dict[str, float]) -> None: + """ + Log `logs` on the various objects watching training, including stored metrics. + + Args: + logs (`Dict[str, float]`): + The values to log. + """ + # logs either has 'loss' or 'eval_loss' + train_eval = "train" if "loss" in logs else "eval" + # Add averaged stored metrics to logs + for key, metrics in self._stored_metrics[train_eval].items(): + logs[key] = torch.tensor(metrics).mean().item() + del self._stored_metrics[train_eval] + return super().log(logs) + + def _shift_right(self, input_ids): + if self.decoder_start_token_id is None: + raise ValueError( + "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." + ) + + # shift inputs to the right + if is_torch_fx_proxy(input_ids): + # Item assignment is not supported natively for proxies. + shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) + shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) + else: + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() + shifted_input_ids[..., 0] = self.decoder_start_token_id + + if self.pad_token_id is None: + raise ValueError("model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) + + return shifted_input_ids + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{hong2024orpo, + title = {{ORPO: Monolithic Preference Optimization without Reference Model}}, + author = {Jiwoo Hong and Noah Lee and James Thorne}, + year = 2024, + eprint = {arXiv:2403.07691} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="ORPO", + trainer_citation=citation, + paper_title="ORPO: Monolithic Preference Optimization without Reference Model", + paper_id="2403.07691", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/ppo_config.py b/testbed/huggingface__trl/trl/trainer/ppo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..465048184b912c48d3f06f939cb96e64b735b3e2 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/ppo_config.py @@ -0,0 +1,69 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from dataclasses import dataclass +from typing import Optional + +from ..trainer.utils import OnPolicyConfig + + +@dataclass +class PPOConfig(OnPolicyConfig): + r""" + Configuration class for the [`PPOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + exp_name (`str`, *optional*, defaults to `os.path.basename(__file__)[:-3]`): + Name of this experiment. + reward_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the reward model. + model_adapter_name (`Optional[str]`, *optional*, defaults to `None`): + Name of the train target PEFT adapter, when using LoRA with multiple adapters. + ref_adapter_name (`Optional[str]`, *optional*, defaults to `None`): + Name of the reference PEFT adapter, when using LoRA with multiple adapters. + num_ppo_epochs (`int`, *optional*, defaults to `4`): + Number of epochs to train. + whiten_rewards (`bool`, *optional*, defaults to `False`): + Whether to whiten the rewards. + kl_coef (`float`, *optional*, defaults to `0.05`): + KL coefficient. + cliprange (`float`, *optional*, defaults to `0.2`): + Clip range. + vf_coef (`float`, *optional*, defaults to `0.1`): + Value function coefficient. + cliprange_value (`float`, *optional*, defaults to `0.2`): + Clip range for the value function. + gamma (`float`, *optional*, defaults to `1.0`): + Discount factor. + lam (`float`, *optional*, defaults to `0.95`): + Lambda value for GAE. + """ + + exp_name: str = os.path.basename(__file__)[: -len(".py")] + reward_model_path: str = "EleutherAI/pythia-160m" + model_adapter_name: Optional[str] = None + ref_adapter_name: Optional[str] = None + num_ppo_epochs: int = 4 + whiten_rewards: bool = False + kl_coef: float = 0.05 + cliprange: float = 0.2 + vf_coef: float = 0.1 + cliprange_value: float = 0.2 + gamma: float = 1.0 + lam: float = 0.95 diff --git a/testbed/huggingface__trl/trl/trainer/ppo_trainer.py b/testbed/huggingface__trl/trl/trainer/ppo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..50f17ddece41b888d0b05f233442c06fb7bdd7e8 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/ppo_trainer.py @@ -0,0 +1,778 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import math +import os +import textwrap +import time +from collections import defaultdict +from contextlib import contextmanager, nullcontext +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import broadcast, gather_object +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import ( + BaseImageProcessor, + DataCollatorWithPadding, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainerCallback, + TrainerControl, + is_wandb_available, +) +from transformers.integrations import get_reporting_integration_callbacks +from transformers.trainer import DEFAULT_CALLBACKS, DEFAULT_PROGRESS_CALLBACK +from transformers.trainer_callback import CallbackHandler, ExportableState, PrinterCallback +from transformers.utils import is_peft_available +from transformers.utils.deprecation import deprecate_kwarg + +from ..core import masked_mean, masked_whiten +from ..models import create_reference_model +from ..models.utils import unwrap_model_for_generation +from ..trainer.utils import ( + OnlineTrainerState, + batch_generation, + disable_dropout_in_model, + exact_div, + first_true_indices, + forward, + get_reward, + prepare_deepspeed, + print_rich_table, + truncate_response, +) +from .ppo_config import PPOConfig +from .utils import generate_model_card, peft_module_casting_to_bf16 + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model + +if is_wandb_available(): + import wandb + + +INVALID_LOGPROB = 1.0 + + +# taken from https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/ppo/ppo_trainer.py#L29 +# we did this we can do a single `model = accelerator.prepare(model)` +class PolicyAndValueWrapper(nn.Module): + def __init__(self, policy, value_model) -> None: + super().__init__() + self.policy = policy + self.value_model = value_model + self.critic_backbone = getattr(value_model, value_model.base_model_prefix) + + def forward(self, **kwargs): + output = self.critic_backbone( + **kwargs, + ) + logits = self.value_model.score(output.hidden_states[-1]) + return self.policy(**kwargs), logits + + +class PPOTrainer(Trainer): + _tag_names = ["trl", "ppo"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.15.0", raise_if_both_names=True) + def __init__( + self, + config: PPOConfig, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ], + policy: nn.Module, + ref_policy: Optional[nn.Module], + reward_model: nn.Module, + train_dataset: Dataset, + value_model: Optional[nn.Module] = None, + data_collator: Optional[DataCollatorWithPadding] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + # less commonly used + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + callbacks: Optional[List[TrainerCallback]] = None, + peft_config: Optional["PeftConfig"] = None, + ) -> None: + if ref_policy is policy: + raise ValueError( + "`policy` and `ref_policy` cannot be the same object. If you want `ref_policy` to be the " + "same as `policy`, you must make a copy of it, or `None` if you use peft." + ) + + self.args = config + args = config + self.processing_class = processing_class + self.policy = policy + + # Define the collator if not provided + if data_collator is None: + data_collator = DataCollatorWithPadding(self.processing_class) + + self.policy.generation_config.eos_token_id = ( + None # disable `pad_token_id` and `eos_token_id` because we just want to + ) + self.policy.generation_config.pad_token_id = None # generate tokens without truncation / padding + + # peft support + if not is_peft_available() and peft_config is not None: + raise ImportError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + # if model is a peft model and we have a peft_confg, we merge and unload it first + if isinstance(self.policy, PeftModel): + self.policy = self.policy.merge_and_unload() + + # get peft model with the given config + self.policy = get_peft_model(self.policy, peft_config) + if args.bf16 and getattr(self.policy, "is_loaded_in_4bit", False): + peft_module_casting_to_bf16(self.policy) + + self.is_peft_model = is_peft_available() and isinstance(self.policy, PeftModel) + self.model_adapter_name = args.model_adapter_name + self.ref_adapter_name = args.ref_adapter_name + + if ref_policy: + self.ref_policy = ref_policy + elif self.is_peft_model: + self.ref_policy = None + else: + self.ref_policy = create_reference_model(self.policy) + + self.reward_model = reward_model + self.train_dataset = train_dataset + self.train_dataset_len = len(train_dataset) + self.value_model = value_model + self.data_collator = data_collator + self.eval_dataset = eval_dataset + self.optimizer, self.lr_scheduler = optimizers + self.optimizer_cls_and_kwargs = None # needed for transformers >= 4.47 + + ######### + # calculate various batch sizes + ######### + if args.total_episodes is None: # allow the users to define episodes in terms of epochs. + args.total_episodes = int(args.num_train_epochs * self.train_dataset_len) + accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps) + self.accelerator = accelerator + args.world_size = accelerator.num_processes + args.local_batch_size = ( + args.per_device_train_batch_size * args.gradient_accumulation_steps * args.num_mini_batches + ) + args.micro_batch_size = int(args.per_device_train_batch_size * args.world_size) + args.batch_size = int(args.local_batch_size * args.world_size) + args.mini_batch_size = exact_div( + args.batch_size, args.num_mini_batches, "`batch_size` must be a multiple of `num_mini_batches`" + ) + args.local_mini_batch_size = exact_div( + args.local_batch_size, args.num_mini_batches, "`local_batch_size` must be a multiple of `num_mini_batches`" + ) + if args.whiten_rewards: + assert ( + args.local_mini_batch_size >= 8 + ), f"Per-rank minibatch size {args.local_mini_batch_size} is insufficient for whitening" + # `per_rank_rollout_batch_size` is our `args.local_batch_size` + # `per_rank_minibatch_size` is our `args.local_mini_batch_size` + args.num_total_batches = math.ceil( + args.total_episodes / args.batch_size + ) # we may train for more than `total_episodes` + time_tensor = torch.tensor(int(time.time()), device=accelerator.device) + time_int = broadcast(time_tensor, 0).item() # avoid different timestamps across processes + args.run_name = f"{args.exp_name}__{args.seed}__{time_int}" + self.local_seed = args.seed + accelerator.process_index * 100003 # Prime + if args.num_sample_generations > 0: + self.sample_generations_freq = max(1, args.num_total_batches // args.num_sample_generations) + self.local_dataloader_batch_size = args.local_batch_size + + ######### + # setup model, optimizer, and others + ######### + for module in [self.policy, self.ref_policy, self.value_model, self.reward_model]: + if module is not None: + disable_dropout_in_model(module) + if args.stop_token and args.stop_token == "eos": + args.stop_token_id = processing_class.eos_token_id + self.model = PolicyAndValueWrapper(self.policy, self.value_model) + self.model.config = self.policy.config # needed for pushing to hub + self.create_optimizer_and_scheduler( + num_training_steps=args.num_total_batches + ) # note that we are calling `self.lr_scheduler.step()` manually only at the batch level + + ######### + ### trainer specifics + ######### + default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) + self.callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks + self.callback_handler = CallbackHandler( + self.callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler + ) + self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) + self.control = TrainerControl() + self.state = OnlineTrainerState( + is_local_process_zero=self.is_local_process_zero(), + is_world_process_zero=self.is_world_process_zero(), + stateful_callbacks=[ + cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState) + ], + ) + self.current_flos = 0 + self.hp_search_backend = None + self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None + self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None + # Create distant repo and output directory if needed + self.hub_model_id = None + if self.args.push_to_hub: + self.init_hf_repo() + if self.args.should_save: + os.makedirs(self.args.output_dir, exist_ok=True) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + ######### + ### setup dataloader + ######### + self.dataloader = DataLoader( + self.train_dataset, + batch_size=self.local_dataloader_batch_size, + shuffle=True, + collate_fn=self.data_collator, + drop_last=True, # needed; otherwise the last batch will be of ragged shape + ) + # sync random states for DataLoader(shuffle=True) before `accelerator.prepare` + # see https://gist.github.com/vwxyzjn/2581bff1e48e185e0b85b6dfe1def79c + torch.manual_seed(args.seed) + self.model, self.optimizer, self.dataloader = accelerator.prepare(self.model, self.optimizer, self.dataloader) + torch.manual_seed(self.local_seed) # reset the local seed again + + self.eval_dataloader = DataLoader( + self.eval_dataset, + batch_size=args.per_device_eval_batch_size, + collate_fn=self.data_collator, + drop_last=True, + ) # no need to shuffle eval dataset + self.eval_dataloader = accelerator.prepare(self.eval_dataloader) + + if self.is_deepspeed_enabled: + self.reward_model = prepare_deepspeed( + self.reward_model, args.per_device_train_batch_size, args.fp16, args.bf16 + ) + + if self.ref_policy is None: + if not self.is_peft_model: + raise ValueError("No reference model and model is not a Peft model.") + else: + self.ref_policy = prepare_deepspeed( + self.ref_policy, args.per_device_train_batch_size, args.fp16, args.bf16 + ) + else: + if self.ref_policy is None: + if not self.is_peft_model: + raise ValueError("No reference model and model is not a Peft model.") + else: + self.ref_policy = self.ref_policy.to(self.accelerator.device) + self.reward_model = self.reward_model.to(self.accelerator.device) + + def get_train_dataloader(self) -> DataLoader: + return self.dataloader + + def get_eval_dataloader(self) -> DataLoader: + return self.eval_dataloader + + @contextmanager + def null_ref_context(self): + """Context manager for handling null reference model (that is, peft adapter manipulation).""" + with self.accelerator.unwrap_model( + self.model.policy + ).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext(): + if self.ref_adapter_name: + self.model.policy.set_adapter(self.ref_adapter_name) + yield + if self.ref_adapter_name: + self.model.policy.set_adapter(self.model_adapter_name or "default") + + def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): + backup_model = self.model + self.model = self.model.policy # save only the policy + + if self.is_deepspeed_enabled: + backup_deepspeed = self.deepspeed + self.deepspeed = self.model + + super().save_model(output_dir, _internal_call) + + self.model = backup_model + + if self.is_deepspeed_enabled: + self.deepspeed = backup_deepspeed + + def train(self): + args = self.args + accelerator = self.accelerator + optimizer = self.optimizer + model = self.model + ref_policy = self.ref_policy + reward_model = self.reward_model + processing_class = self.processing_class + dataloader = self.dataloader + device = accelerator.device + + def repeat_generator(): + while True: + yield from dataloader + + iter_dataloader = iter(repeat_generator()) + generation_config = GenerationConfig( + max_new_tokens=args.response_length, + temperature=(args.temperature + 1e-7), + top_k=0.0, + top_p=1.0, + do_sample=True, + ) + + accelerator.print("===training policy===") + start_time = time.time() + stats_shape = (args.num_ppo_epochs, args.num_mini_batches, args.gradient_accumulation_steps) + approxkl_stats = torch.zeros(stats_shape, device=device) + pg_clipfrac_stats = torch.zeros(stats_shape, device=device) + pg_loss_stats = torch.zeros(stats_shape, device=device) + vf_loss_stats = torch.zeros(stats_shape, device=device) + vf_clipfrac_stats = torch.zeros(stats_shape, device=device) + entropy_stats = torch.zeros(stats_shape, device=device) + ratio_stats = torch.zeros(stats_shape, device=device) + model.train() + + # trainer state initialization + self.state.global_step = 0 + self.state.episode = 0 + self.state.max_steps = args.num_total_batches * args.num_mini_batches + self.state.num_train_epochs = args.total_episodes / self.train_dataset_len + # Compute absolute values for logging, eval, and save if given as ratio + if args.logging_steps is not None: + if args.logging_steps < 1: + self.state.logging_steps = math.ceil(self.state.max_steps * args.logging_steps) + else: + self.state.logging_steps = args.logging_steps + if args.eval_steps is not None: + if args.eval_steps < 1: + self.state.eval_steps = math.ceil(self.state.max_steps * args.eval_steps) + else: + self.state.eval_steps = args.eval_steps + if args.save_steps is not None: + if args.save_steps < 1: + self.state.save_steps = math.ceil(self.state.max_steps * args.save_steps) + else: + self.state.save_steps = args.save_steps + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # backward compatibility + if self.is_deepspeed_enabled: + self.deepspeed = self.model + self.model_wrapped = self.model + + for update in range(1, args.num_total_batches + 1): + self.state.episode += 1 * args.batch_size + data = next(iter_dataloader) + with torch.no_grad(): + queries = data["input_ids"].to(device) + context_length = queries.shape[1] + responses = [] + postprocessed_responses = [] + logprobs = [] + ref_logprobs = [] + scores = [] + sequence_lengths = [] + values = [] + with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model: + query_responses, logitss = batch_generation( + unwrapped_model.policy, + queries, + args.local_rollout_forward_batch_size, + processing_class.pad_token_id, + generation_config, + ) + + for i in range(0, queries.shape[0], args.local_rollout_forward_batch_size): + query = queries[i : i + args.local_rollout_forward_batch_size] + query_response = query_responses[i : i + args.local_rollout_forward_batch_size] + response = query_response[:, context_length:] + logits = logitss[i : i + args.local_rollout_forward_batch_size] + all_logprob = F.log_softmax(logits, dim=-1) + logprob = torch.gather(all_logprob, 2, response.unsqueeze(-1)).squeeze(-1) + del logits, all_logprob + torch.cuda.empty_cache() + + if ref_policy is None: + with self.null_ref_context(): + ref_output = forward(model.policy, query_response, processing_class.pad_token_id) + else: + ref_output = forward(ref_policy, query_response, processing_class.pad_token_id) + ref_logits = ref_output.logits[:, context_length - 1 : -1] + ref_logits /= args.temperature + 1e-7 + ref_all_logprob = F.log_softmax(ref_logits, dim=-1) + ref_logprob = torch.gather(ref_all_logprob, 2, response.unsqueeze(-1)).squeeze(-1) + del ref_output, ref_logits, ref_all_logprob + torch.cuda.empty_cache() + + # Response Processing 1. truncate response after the first occurrence of `stop_token_id` + postprocessed_response = response + if args.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + args.stop_token_id, processing_class.pad_token_id, response + ) + + # Response Processing 2. run reward model on the truncated responses + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + sequence_length = first_true_indices(postprocessed_response == processing_class.pad_token_id) - 1 + unwrapped_value_model = accelerator.unwrap_model(model).value_model + full_value, _, _ = get_reward( + unwrapped_value_model, query_response, processing_class.pad_token_id, context_length + ) + value = full_value[:, context_length - 1 : -1].squeeze(-1) + _, score, _ = get_reward( + reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + + responses.append(response) + postprocessed_responses.append(postprocessed_response) + logprobs.append(logprob) + ref_logprobs.append(ref_logprob) + sequence_lengths.append(sequence_length) + scores.append(score) + values.append(value) + responses = torch.cat(responses, 0) + postprocessed_responses = torch.cat(postprocessed_responses, 0) + logprobs = torch.cat(logprobs, 0) + ref_logprobs = torch.cat(ref_logprobs, 0) + sequence_lengths = torch.cat(sequence_lengths, 0) + scores = torch.cat(scores, 0) + values = torch.cat(values, 0) + del (logprob, ref_logprob, full_value, value, score, unwrapped_model) + torch.cuda.empty_cache() + gc.collect() + + # Response Processing 3. Filter completion. Ensure that the sample contains stop_token_id + # Completions not passing that filter will receive a lower score. + contain_eos_token = torch.any(postprocessed_responses == self.processing_class.eos_token_id, dim=-1) + if self.args.missing_eos_penalty is not None: + scores[~contain_eos_token] -= self.args.missing_eos_penalty + # accelerator.print(f"{scores=}, {(contain_eos_token.sum() / len(contain_eos_token))=}") + + # be very careful with `padding_mask_p1`; see https://excalidraw.com/#json=LWnzG4w2k5DjF_EOL_xPt,e2w3a-hFJ_gX5vOfeyXGTw + response_idxs = torch.arange(responses.shape[1], device=responses.device).repeat(responses.shape[0], 1) + padding_mask = response_idxs > sequence_lengths.unsqueeze(1) + logprobs = torch.masked_fill(logprobs, padding_mask, INVALID_LOGPROB) + ref_logprobs = torch.masked_fill(ref_logprobs, padding_mask, INVALID_LOGPROB) + sequence_lengths_p1 = sequence_lengths + 1 + padding_mask_p1 = response_idxs > (sequence_lengths_p1.unsqueeze(1)) + values = torch.masked_fill(values, padding_mask_p1, 0) + + # 4. compute rewards + kl = logprobs - ref_logprobs + non_score_reward = -args.kl_coef * kl + rewards = non_score_reward.clone() + actual_start = torch.arange(rewards.size(0), device=rewards.device) + actual_end = torch.where(sequence_lengths_p1 < rewards.size(1), sequence_lengths_p1, sequence_lengths) + rewards[[actual_start, actual_end]] += scores + + # 5. whiten rewards + if args.whiten_rewards: + rewards = masked_whiten(rewards, mask=~padding_mask_p1, shift_mean=False) + rewards = torch.masked_fill(rewards, padding_mask_p1, 0) + + # 6. compute advantages and returns + lastgaelam = 0 + advantages_reversed = [] + gen_length = responses.shape[1] + for t in reversed(range(gen_length)): + nextvalues = values[:, t + 1] if t < gen_length - 1 else 0.0 + delta = rewards[:, t] + args.gamma * nextvalues - values[:, t] + lastgaelam = delta + args.gamma * args.lam * lastgaelam + advantages_reversed.append(lastgaelam) + advantages = torch.stack(advantages_reversed[::-1], axis=1) + returns = advantages + values + advantages = masked_whiten(advantages, ~padding_mask) + advantages = torch.masked_fill(advantages, padding_mask, 0) + torch.cuda.empty_cache() + + # Do multiple epochs of PPO training, with a fresh random shuffle in each epoch + for ppo_epoch_idx in range(args.num_ppo_epochs): + b_inds = np.random.permutation(args.local_batch_size) + minibatch_idx = 0 + for mini_batch_start in range(0, args.local_batch_size, args.local_mini_batch_size): + mini_batch_end = mini_batch_start + args.local_mini_batch_size + mini_batch_inds = b_inds[mini_batch_start:mini_batch_end] + gradient_accumulation_idx = 0 + for micro_batch_start in range(0, args.local_mini_batch_size, args.per_device_train_batch_size): + with accelerator.accumulate(model): + micro_batch_end = micro_batch_start + args.per_device_train_batch_size + micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end] + mb_advantage = advantages[micro_batch_inds] + mb_responses = responses[micro_batch_inds] + mb_query_responses = query_responses[micro_batch_inds] + mb_logprobs = logprobs[micro_batch_inds] + mb_return = returns[micro_batch_inds] + mb_values = values[micro_batch_inds] + + output, vpred_temp = forward(model, mb_query_responses, processing_class.pad_token_id) + logits = output.logits[:, context_length - 1 : -1] + logits /= args.temperature + 1e-7 + new_all_logprobs = F.log_softmax(logits, dim=-1) + new_logprobs = torch.gather(new_all_logprobs, 2, mb_responses.unsqueeze(-1)).squeeze(-1) + new_logprobs = torch.masked_fill( + new_logprobs, padding_mask[micro_batch_inds], INVALID_LOGPROB + ) + vpred = vpred_temp[:, context_length - 1 : -1].squeeze(-1) + vpred = torch.masked_fill(vpred, padding_mask_p1[micro_batch_inds], 0) + vpredclipped = torch.clamp( + vpred, + mb_values - args.cliprange_value, + mb_values + args.cliprange_value, + ) + vf_losses1 = torch.square(vpred - mb_return) + vf_losses2 = torch.square(vpredclipped - mb_return) + vf_loss_max = torch.max(vf_losses1, vf_losses2) + vf_loss = 0.5 * masked_mean(vf_loss_max, ~padding_mask_p1[micro_batch_inds]) + vf_clipfrac = masked_mean( + (vf_losses2 > vf_losses1).float(), ~padding_mask_p1[micro_batch_inds] + ) + logprobs_diff = new_logprobs - mb_logprobs + ratio = torch.exp(logprobs_diff) + pg_losses = -mb_advantage * ratio + pg_losses2 = -mb_advantage * torch.clamp(ratio, 1.0 - args.cliprange, 1.0 + args.cliprange) + pg_loss_max = torch.max(pg_losses, pg_losses2) + pg_loss = masked_mean(pg_loss_max, ~padding_mask[micro_batch_inds]) + loss = pg_loss + args.vf_coef * vf_loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + with torch.no_grad(): + pg_clipfrac = masked_mean( + (pg_losses2 > pg_losses).float(), ~padding_mask[micro_batch_inds] + ) + prob_dist = torch.nn.functional.softmax(logits, dim=-1) + entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1) + approxkl = 0.5 * (logprobs_diff**2).mean() + approxkl_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = approxkl + pg_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + pg_clipfrac + ) + pg_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = pg_loss + vf_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = vf_loss + vf_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + vf_clipfrac + ) + entropy_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = entropy.mean() + ratio_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ratio.mean() + gradient_accumulation_idx += 1 + minibatch_idx += 1 + # del everything and empty cache + # fmt: off + del ( + output, vpred_temp, logits, new_all_logprobs, new_logprobs, vpred, vpredclipped, + vf_losses1, vf_losses2, vf_loss, vf_clipfrac, logprobs_diff, ratio, pg_losses, pg_losses2, pg_loss_max, + pg_loss, loss, pg_clipfrac, prob_dist, entropy, approxkl, mb_return, + mb_advantage, mb_values, mb_responses, mb_query_responses, mb_logprobs, + ) + # fmt: on + torch.cuda.empty_cache() + with torch.no_grad(): + mean_kl = kl.sum(1).mean() + mean_entropy = (-logprobs).sum(1).mean() + mean_non_score_reward = non_score_reward.sum(1).mean() + rlhf_reward = mean_non_score_reward + scores.mean() + eps = int(self.state.episode / (time.time() - start_time)) + metrics = {} + metrics["eps"] = eps + metrics["objective/kl"] = self.accelerator.gather(mean_kl).mean().item() + metrics["objective/entropy"] = self.accelerator.gather(mean_entropy).mean().item() + metrics["objective/non_score_reward"] = self.accelerator.gather(mean_non_score_reward).mean().item() + metrics["objective/rlhf_reward"] = self.accelerator.gather(rlhf_reward).mean().item() + metrics["objective/scores"] = self.accelerator.gather(scores.mean()).mean().item() + metrics["policy/approxkl_avg"] = self.accelerator.gather(approxkl_stats).mean().item() + metrics["policy/clipfrac_avg"] = self.accelerator.gather(pg_clipfrac_stats).mean().item() + metrics["loss/policy_avg"] = self.accelerator.gather(pg_loss_stats).mean().item() + metrics["loss/value_avg"] = self.accelerator.gather(vf_loss_stats).mean().item() + metrics["val/clipfrac_avg"] = self.accelerator.gather(vf_clipfrac_stats).mean().item() + metrics["policy/entropy_avg"] = self.accelerator.gather(entropy_stats).mean().item() + metrics["val/ratio"] = self.accelerator.gather(ratio_stats).mean().item() + metrics["val/ratio_var"] = self.accelerator.gather(ratio_stats).var().item() + metrics["val/num_eos_tokens"] = (responses == processing_class.eos_token_id).sum().item() + metrics["lr"] = self.lr_scheduler.get_last_lr()[0] + metrics["episode"] = self.state.episode + self.state.epoch = self.state.episode / self.train_dataset_len # used by self.log + self.state.global_step += 1 + self.log(metrics) + + self.lr_scheduler.step() + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + del kl, mean_kl, mean_entropy, mean_non_score_reward, scores, metrics, non_score_reward + torch.cuda.empty_cache() + gc.collect() + + if args.num_sample_generations > 0 and (update - 1) % self.sample_generations_freq == 0: + self.generate_completions(sampling=True) + torch.cuda.empty_cache() + del ( + query_responses, + responses, + postprocessed_responses, + logprobs, + ref_logprobs, + values, + sequence_lengths, + contain_eos_token, + sequence_lengths_p1, + response_idxs, + padding_mask, + padding_mask_p1, + rewards, + actual_start, + actual_end, + advantages, + returns, + ) + torch.cuda.empty_cache() + + # HF trainer specifics + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None, metrics=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + def generate_completions(self, sampling: bool = False): + args = self.args + processing_class = self.processing_class + generation_config = GenerationConfig( + max_new_tokens=self.args.response_length, + temperature=(0.01 + 1e-7), + top_k=0.0, + top_p=1.0, + do_sample=True, + ) + + table = defaultdict(list) + with unwrap_model_for_generation(self.model, self.accelerator) as unwrapped_model: + for batch in self.eval_dataloader: + query = batch["input_ids"] + with torch.no_grad(): + context_length = query.shape[1] + query_response, _ = batch_generation( + unwrapped_model.policy, + query, + query.shape[0], + processing_class.pad_token_id, + generation_config, + ) + response = query_response[:, context_length:] + postprocessed_response = response + if args.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + args.stop_token_id, processing_class.pad_token_id, response + ) + table["query"].extend( + gather_object(processing_class.batch_decode(query, skip_special_tokens=True)) + ) + table["model response"].extend( + gather_object(processing_class.batch_decode(postprocessed_response)) + ) + + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + _, score, _ = get_reward( + self.reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + table["score"].extend(self.accelerator.gather(score).float().cpu().numpy()) + + if sampling: + break + df = pd.DataFrame(table) + + if self.accelerator.is_main_process: + print_rich_table(df.iloc[0 : 0 + 5]) + if "wandb" in args.report_to: + import wandb + + if wandb.run is not None: + wandb.log({"completions": wandb.Table(dataframe=df)}) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{mziegler2019fine-tuning, + title = {{Fine-Tuning Language Models from Human Preferences}}, + author = {Daniel M. Ziegler and Nisan Stiennon and Jeffrey Wu and Tom B. Brown and Alec Radford and Dario Amodei and Paul F. Christiano and Geoffrey Irving}, + year = 2019, + eprint = {arXiv:1909.08593} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="PPO", + trainer_citation=citation, + paper_title="Fine-Tuning Language Models from Human Preferences", + paper_id="1909.08593", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/reward_config.py b/testbed/huggingface__trl/trl/trainer/reward_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6e3eeab3723974d5daf5653f39913d5454d393f4 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/reward_config.py @@ -0,0 +1,47 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import Optional + +from transformers import TrainingArguments + + +@dataclass +class RewardConfig(TrainingArguments): + r""" + Configuration class for the [`RewardTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + max_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want + to use the default data collator. + dataset_num_proc (`int`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + center_rewards_coefficient (`float`, *optional*, defaults to `None`): + Coefficient to incentivize the reward model to output mean-zero rewards (proposed by + https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`. + remove_unused_columns (`bool`, *optional*, defaults to `False`): + Whether or not to remove the columns that are not used by the model's forward pass. Can be `True` only if + the dataset is pretokenized. + """ + + max_length: Optional[int] = None + dataset_num_proc: Optional[int] = None + center_rewards_coefficient: Optional[float] = None + remove_unused_columns: bool = False diff --git a/testbed/huggingface__trl/trl/trainer/reward_trainer.py b/testbed/huggingface__trl/trl/trainer/reward_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f3456cab4167cf6ae8e5116cb1f35f9a928bfb02 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/reward_trainer.py @@ -0,0 +1,414 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +import os +import warnings +from collections import defaultdict +from dataclasses import FrozenInstanceError, replace +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import pandas as pd +import torch +import torch.nn as nn +from accelerate import PartialState +from accelerate.utils import gather_object +from datasets import Dataset +from transformers import ( + BaseImageProcessor, + DataCollator, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainingArguments, + is_wandb_available, +) +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_pt_utils import nested_detach +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_peft_available +from transformers.utils.deprecation import deprecate_kwarg + +from ..data_utils import maybe_apply_chat_template +from .reward_config import RewardConfig +from .utils import ( + RewardDataCollatorWithPadding, + compute_accuracy, + decode_and_strip_padding, + generate_model_card, + print_rich_table, +) + + +if is_peft_available(): + from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training + +if is_wandb_available(): + import wandb + + +def _tokenize(batch: Dict[str, List[Any]], tokenizer: "PreTrainedTokenizerBase") -> Dict[str, List[Any]]: + """Tokenize a batch from a reward modelling dataset.""" + new_examples = { + "input_ids_chosen": [], + "attention_mask_chosen": [], + "input_ids_rejected": [], + "attention_mask_rejected": [], + } + for chosen, rejected in zip(batch["chosen"], batch["rejected"]): + tokenized_chosen = tokenizer(chosen) + tokenized_rejected = tokenizer(rejected) + new_examples["input_ids_chosen"].append(tokenized_chosen["input_ids"]) + new_examples["attention_mask_chosen"].append(tokenized_chosen["attention_mask"]) + new_examples["input_ids_rejected"].append(tokenized_rejected["input_ids"]) + new_examples["attention_mask_rejected"].append(tokenized_rejected["attention_mask"]) + + return new_examples + + +class RewardTrainer(Trainer): + _tag_names = ["trl", "reward-trainer"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.15.0", raise_if_both_names=True) + def __init__( + self, + model: Optional[Union[PreTrainedModel, nn.Module]] = None, + args: Optional[RewardConfig] = None, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = ( + None, + None, + ), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + max_length: Optional[int] = None, + peft_config: Optional[Dict] = None, + ): + """ + Initialize RewardTrainer. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForSequenceClassification`. + args (`RewardConfig`): + The arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`RewardDataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to `compute_accuracy`): + The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) will be used. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Dict`, defaults to `None`): + The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. + """ + if type(args) is TrainingArguments: + warnings.warn( + "Using `transformers.TrainingArguments` for `args` is deprecated and will be removed in a future version. Please use `RewardConfig` instead.", + FutureWarning, + ) + if max_length is not None: + warnings.warn( + "The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.", + FutureWarning, + ) + else: + if max_length is not None and args.max_length is not None: + raise ValueError( + "You cannot specify both `max_length` and `args.max_length`. Please use the `RewardConfig` to set `max_length` once." + ) + if max_length is not None and args.max_length is None: + warnings.warn( + "The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.", + FutureWarning, + ) + if not is_peft_available() and peft_config is not None: + raise ValueError( + "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models" + ) + elif is_peft_available() and peft_config is not None: + if not isinstance(model, PeftModel): + if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_quantized", False): + _supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + + prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} + + if not _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None: + warnings.warn( + "You passed `gradient_checkpointing_kwargs` in the trainer's kwargs, but your peft version does not support it. " + "please update to the latest version of peft to use `gradient_checkpointing_kwargs`." + ) + elif _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + + model = get_peft_model(model, peft_config) + + if compute_metrics is None: + compute_metrics = compute_accuracy + + if data_collator is None: + if processing_class is None: + raise ValueError( + "A processing_class must be specified when using the default RewardDataCollatorWithPadding" + ) + if max_length is None: + max_length = 512 if type(args) is TrainingArguments or args.max_length is None else args.max_length + + data_collator = RewardDataCollatorWithPadding(processing_class) + + if args.remove_unused_columns: + try: # for bc before https://github.com/huggingface/transformers/pull/25435 + args.remove_unused_columns = False + except FrozenInstanceError: + args = replace(args, remove_unused_columns=False) + # warn users + warnings.warn( + "When using RewardDataCollatorWithPadding, you should set `remove_unused_columns=False` in your RewardConfig" + " we have set it for you, but you should do it yourself in the future.", + UserWarning, + ) + + self.use_reward_data_collator = True + else: + self.use_reward_data_collator = False + + if "input_ids_chosen" not in train_dataset.column_names: + with PartialState().local_main_process_first(): + fn_kwargs = {"tokenizer": processing_class} + train_dataset = train_dataset.map(maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}) + train_dataset = train_dataset.map( + _tokenize, + batched=True, + fn_kwargs=fn_kwargs, + num_proc=args.dataset_num_proc, + ) + # This filter is important because otherwise you get samples that exceed the model's context length and + # get truncated => noisy signal the chosen/rejected label gets lost. The downside is that the + # user might get surprised if N samples are missing from training. + train_dataset = train_dataset.filter( + lambda x: len(x["input_ids_chosen"]) <= max_length and len(x["input_ids_rejected"]) <= max_length, + num_proc=args.dataset_num_proc, + ) + if eval_dataset is not None: + eval_dataset = eval_dataset.map( + maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class} + ) + eval_dataset = eval_dataset.map( + _tokenize, + fn_kwargs=fn_kwargs, + batched=True, + num_proc=args.dataset_num_proc, + ) + # This filter is important because otherwise you get samples that exceed the model's context length and + # get truncated => noisy signal the chosen/rejected label gets lost. The downside is that the + # user might get surprised if N samples are missing from training. + eval_dataset = eval_dataset.filter( + lambda x: len(x["input_ids_chosen"]) <= max_length + and len(x["input_ids_rejected"]) <= max_length, + num_proc=args.dataset_num_proc, + ) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + def compute_loss( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + return_outputs=False, + num_items_in_batch=None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: + if not self.use_reward_data_collator: + warnings.warn( + "The current compute_loss is implemented for RewardDataCollatorWithPadding," + " if you are using a custom data collator make sure you know what you are doing or" + " implement your own compute_loss method." + ) + rewards_chosen = model( + input_ids=inputs["input_ids_chosen"], + attention_mask=inputs["attention_mask_chosen"], + return_dict=True, + )["logits"] + rewards_rejected = model( + input_ids=inputs["input_ids_rejected"], + attention_mask=inputs["attention_mask_rejected"], + return_dict=True, + )["logits"] + # calculate loss, optionally modulate with margin + if "margin" in inputs: + loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean() + else: + loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean() + + if self.args.center_rewards_coefficient is not None: + loss += self.args.center_rewards_coefficient * torch.mean((rewards_chosen + rewards_rejected) ** 2) + + if return_outputs: + return loss, { + "rewards_chosen": rewards_chosen, + "rewards_rejected": rewards_rejected, + } + return loss + + def prediction_step( + self, + model: Union[PreTrainedModel, nn.Module], + inputs: Dict[str, Union[torch.Tensor, Any]], + prediction_loss_only: bool, + ignore_keys: Optional[List[str]] = None, + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: + inputs = self._prepare_inputs(inputs) + if ignore_keys is None: + if hasattr(self.model, "config"): + ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) + else: + ignore_keys = [] + + with torch.no_grad(): + loss, logits_dict = self.compute_loss(model, inputs, return_outputs=True) + + if prediction_loss_only: + return (loss, None, None) + + loss = loss.detach() + logits = tuple(v for k, v in logits_dict.items() if k not in ignore_keys) + logits = nested_detach(logits) + # Stack accepted against rejected, mean over logits + # and softmax to get preferences between accepted and rejected to sum to 1 + logits = torch.stack(logits).mean(dim=2).softmax(dim=0).T + + labels = torch.zeros(logits.shape[0]) + labels = self._prepare_inputs(labels) + + return loss, logits, labels + + def evaluate(self, *args, **kwargs): + num_print_samples = kwargs.pop("num_print_samples", 4) + self.visualize_samples(num_print_samples) + return super().evaluate(*args, **kwargs) + + def visualize_samples(self, num_print_samples: int): + """ + Visualize the reward model logits prediction + + Args: + num_print_samples (`int`, defaults to `4`): + The number of samples to print. Set to `-1` to print all samples. + """ + eval_dataloader = self.get_eval_dataloader() + table = defaultdict(list) + for _, inputs in enumerate(eval_dataloader): + _, logits, _ = self.prediction_step(self.model, inputs, prediction_loss_only=False) + chosen_text = decode_and_strip_padding(inputs["input_ids_chosen"], self.processing_class) + rejected_text = decode_and_strip_padding(inputs["input_ids_rejected"], self.processing_class) + table["chosen_text"].extend(gather_object(chosen_text)) + table["rejected_text"].extend(gather_object(rejected_text)) + table["logits"].extend( + gather_object([[round(inner_item, 4) for inner_item in item] for item in logits.tolist()]) + ) + if num_print_samples >= 0 and len(table["chosen_text"]) >= num_print_samples: + break + df = pd.DataFrame(table) + if self.accelerator.process_index == 0: + print_rich_table(df[:num_print_samples]) + if "wandb" in self.args.report_to: + import wandb + + if wandb.run is not None: + wandb.log({"completions": wandb.Table(dataframe=df)}) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="Reward", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/rloo_config.py b/testbed/huggingface__trl/trl/trainer/rloo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2683fb5eee2eb2d297ce60f3d04c7e894ccb0fbe --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/rloo_config.py @@ -0,0 +1,53 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from dataclasses import dataclass + +from ..trainer.utils import OnPolicyConfig + + +@dataclass +class RLOOConfig(OnPolicyConfig): + r""" + Configuration class for the [`RLOOTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + exp_name (`str`, *optional*, defaults to `os.path.basename(__file__)[: -len(".py")]`): + Name of this experiment. + reward_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the reward model. + num_ppo_epochs (`int`, *optional*, defaults to `4`): + Number of epochs to train. + whiten_rewards (`bool`, *optional*, defaults to `False`): + Whether to whiten the rewards. + kl_coef (`float`, *optional*, defaults to `0.05`): + KL coefficient. + cliprange (`float`, *optional*, defaults to `0.2`): + Clip range. + rloo_k (`int`, *optional*, defaults to `2`): + REINFORCE Leave-One-Out (RLOO) number of online samples per prompt. + """ + + exp_name: str = os.path.basename(__file__)[: -len(".py")] + reward_model_path: str = "EleutherAI/pythia-160m" + num_ppo_epochs: int = 4 + whiten_rewards: bool = False + kl_coef: float = 0.05 + cliprange: float = 0.2 + rloo_k: int = 2 diff --git a/testbed/huggingface__trl/trl/trainer/rloo_trainer.py b/testbed/huggingface__trl/trl/trainer/rloo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..466874e91c6ae399e51ef3813b545511f5d9d96c --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/rloo_trainer.py @@ -0,0 +1,613 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import math +import os +import textwrap +import time +from collections import defaultdict +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd +import torch +import torch.nn as nn +import torch.nn.functional as F +from accelerate import Accelerator +from accelerate.utils import broadcast, gather_object +from datasets import Dataset +from torch.utils.data import DataLoader +from transformers import ( + BaseImageProcessor, + DataCollatorWithPadding, + FeatureExtractionMixin, + GenerationConfig, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + TrainerCallback, + TrainerControl, + is_wandb_available, +) +from transformers.integrations import get_reporting_integration_callbacks +from transformers.trainer import DEFAULT_CALLBACKS, DEFAULT_PROGRESS_CALLBACK +from transformers.trainer_callback import CallbackHandler, ExportableState, PrinterCallback +from transformers.utils.deprecation import deprecate_kwarg + +from ..models.utils import unwrap_model_for_generation +from ..trainer.utils import ( + OnlineTrainerState, + batch_generation, + disable_dropout_in_model, + exact_div, + first_true_indices, + forward, + get_reward, + prepare_deepspeed, + print_rich_table, + truncate_response, +) +from .rloo_config import RLOOConfig +from .utils import generate_model_card + + +if is_wandb_available(): + import wandb + +INVALID_LOGPROB = 1.0 + + +class RLOOTrainer(Trainer): + _tag_names = ["trl", "rloo"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.14.0", raise_if_both_names=True) + def __init__( + self, + config: RLOOConfig, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ], + policy: nn.Module, + ref_policy: nn.Module, + reward_model: nn.Module, + train_dataset: Dataset, + data_collator: Optional[DataCollatorWithPadding] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + # less commonly used + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + callbacks: Optional[List[TrainerCallback]] = None, + ) -> None: + if ref_policy is policy: + raise ValueError( + "`policy` and `ref_policy` cannot be the same object. If you want `ref_policy` to be the " + "same as `policy`, you must mass a copy of it, or `None` if you use peft." + ) + + self.args = config + args = config + self.processing_class = processing_class + self.policy = policy + + # Define the collator if not provided + if data_collator is None: + data_collator = DataCollatorWithPadding(self.processing_class) + + self.policy.generation_config.eos_token_id = ( + None # disable `pad_token_id` and `eos_token_id` because we just want to + ) + self.policy.generation_config.pad_token_id = None # generate tokens without truncation / padding + + self.ref_policy = ref_policy + self.reward_model = reward_model + self.train_dataset = train_dataset + self.train_dataset_len = len(train_dataset) + self.data_collator = data_collator + self.eval_dataset = eval_dataset + self.optimizer, self.lr_scheduler = optimizers + self.optimizer_cls_and_kwargs = None # needed for transformers >= 4.47 + + ######### + # calculate various batch sizes + ######### + if args.total_episodes is None: # allow the users to define episodes in terms of epochs. + args.total_episodes = int(args.num_train_epochs * self.train_dataset_len) + accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps) + self.accelerator = accelerator + args.world_size = accelerator.num_processes + args.local_batch_size = ( + args.per_device_train_batch_size * args.gradient_accumulation_steps * args.num_mini_batches + ) + args.micro_batch_size = int(args.per_device_train_batch_size * args.world_size) + args.batch_size = int(args.local_batch_size * args.world_size) + args.mini_batch_size = exact_div( + args.batch_size, args.num_mini_batches, "`batch_size` must be a multiple of `num_mini_batches`" + ) + args.local_mini_batch_size = exact_div( + args.local_batch_size, args.num_mini_batches, "`local_batch_size` must be a multiple of `num_mini_batches`" + ) + args.num_total_batches = math.ceil( + args.total_episodes / args.batch_size + ) # we may train for more than `total_episodes` + time_tensor = torch.tensor(int(time.time()), device=accelerator.device) + time_int = broadcast(time_tensor, 0).item() # avoid different timestamps across processes + args.run_name = f"{args.exp_name}__{args.seed}__{time_int}" + self.local_seed = args.seed + accelerator.process_index * 100003 # Prime + if args.num_sample_generations > 0: + self.sample_generations_freq = max(1, args.num_total_batches // args.num_sample_generations) + self.local_dataloader_batch_size = exact_div( + args.local_batch_size, args.rloo_k, "`local_batch_size` must be a multiple of rloo_k" + ) # RLOO logic: needed because RLOO repeats the same prompt args.rloo_k times + + ######### + # setup model, optimizer, and others + ######### + for module in [policy, ref_policy, reward_model]: + disable_dropout_in_model(module) + if args.stop_token and args.stop_token == "eos": + args.stop_token_id = self.processing_class.eos_token_id + self.model = policy + self.create_optimizer_and_scheduler( + num_training_steps=args.num_total_batches + ) # note that we are calling `self.lr_scheduler.step()` manually only at the batch level + + ######### + ### trainer specifics + ######### + default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) + self.callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks + self.callback_handler = CallbackHandler( + self.callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler + ) + self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) + self.control = TrainerControl() + self.state = OnlineTrainerState( + is_local_process_zero=self.is_local_process_zero(), + is_world_process_zero=self.is_world_process_zero(), + stateful_callbacks=[ + cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState) + ], + ) + + self.current_flos = 0 + self.hp_search_backend = None + self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None + self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None + # Create distant repo and output directory if needed + self.hub_model_id = None + if self.args.push_to_hub: + self.init_hf_repo() + if self.args.should_save: + os.makedirs(self.args.output_dir, exist_ok=True) + self.backup_model = None + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + ######### + ### setup dataloader + ######### + self.dataloader = DataLoader( + self.train_dataset, + batch_size=self.local_dataloader_batch_size, + shuffle=True, + collate_fn=self.data_collator, + drop_last=True, # needed; otherwise the last batch will be of ragged shape + ) + # sync random states for DataLoader(shuffle=True) before `accelerator.prepare` + # see https://gist.github.com/vwxyzjn/2581bff1e48e185e0b85b6dfe1def79c + torch.manual_seed(args.seed) + self.model, self.optimizer, self.dataloader = accelerator.prepare(self.model, self.optimizer, self.dataloader) + torch.manual_seed(self.local_seed) # reset the local seed again + + self.eval_dataloader = DataLoader( + self.eval_dataset, + batch_size=args.per_device_eval_batch_size, + collate_fn=self.data_collator, + drop_last=True, + ) # no need to shuffle eval dataset + self.eval_dataloader = accelerator.prepare(self.eval_dataloader) + + if self.is_deepspeed_enabled: + self.reward_model = prepare_deepspeed( + self.reward_model, args.per_device_train_batch_size, args.fp16, args.bf16 + ) + self.ref_policy = prepare_deepspeed( + self.ref_policy, args.per_device_train_batch_size, args.fp16, args.bf16 + ) + self.deepspeed = self.model + else: + self.ref_policy = self.ref_policy.to(self.accelerator.device) + self.reward_model = self.reward_model.to(self.accelerator.device) + + def get_train_dataloader(self) -> DataLoader: + return self.dataloader + + def get_eval_dataloader(self) -> DataLoader: + return self.eval_dataloader + + def train(self): + args = self.args + accelerator = self.accelerator + optimizer = self.optimizer + model = self.model + self.model_wrapped = self.model + ref_policy = self.ref_policy + reward_model = self.reward_model + processing_class = self.processing_class + dataloader = self.dataloader + device = accelerator.device + + def repeat_generator(): + while True: + yield from dataloader + + iter_dataloader = iter(repeat_generator()) + generation_config = GenerationConfig( + max_new_tokens=args.response_length, + temperature=(args.temperature + 1e-7), + top_k=0.0, + top_p=1.0, + do_sample=True, + ) + + accelerator.print("===training policy===") + start_time = time.time() + stats_shape = (args.num_ppo_epochs, args.num_mini_batches, args.gradient_accumulation_steps) + approxkl_stats = torch.zeros(stats_shape, device=device) + pg_clipfrac_stats = torch.zeros(stats_shape, device=device) + pg_loss_stats = torch.zeros(stats_shape, device=device) + vf_clipfrac_stats = torch.zeros(stats_shape, device=device) + entropy_stats = torch.zeros(stats_shape, device=device) + ratio_stats = torch.zeros(stats_shape, device=device) + model.train() + + # trainer state initialization + self.state.global_step = 0 + self.state.episode = 0 + self.state.max_steps = args.num_total_batches * args.num_mini_batches + self.state.num_train_epochs = args.total_episodes / self.train_dataset_len + # Compute absolute values for logging, eval, and save if given as ratio + if args.logging_steps is not None: + if args.logging_steps < 1: + self.state.logging_steps = math.ceil(self.state.max_steps * args.logging_steps) + else: + self.state.logging_steps = args.logging_steps + if args.eval_steps is not None: + if args.eval_steps < 1: + self.state.eval_steps = math.ceil(self.state.max_steps * args.eval_steps) + else: + self.state.eval_steps = args.eval_steps + if args.save_steps is not None: + if args.save_steps < 1: + self.state.save_steps = math.ceil(self.state.max_steps * args.save_steps) + else: + self.state.save_steps = args.save_steps + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + for update in range(1, args.num_total_batches + 1): + self.state.episode += 1 * args.batch_size + data = next(iter_dataloader) + with torch.no_grad(): + queries = data["input_ids"].to(device) + queries = queries.repeat(args.rloo_k, 1) + context_length = queries.shape[1] + responses = [] + postprocessed_responses = [] + logprobs = [] + ref_logprobs = [] + scores = [] + sequence_lengths = [] + with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model: + query_responses, logitss = batch_generation( + unwrapped_model, + queries, + args.local_rollout_forward_batch_size, + processing_class.pad_token_id, + generation_config, + ) + + for i in range(0, queries.shape[0], args.local_rollout_forward_batch_size): + query = queries[i : i + args.local_rollout_forward_batch_size] + query_response = query_responses[i : i + args.local_rollout_forward_batch_size] + response = query_response[:, context_length:] + logits = logitss[i : i + args.local_rollout_forward_batch_size] + all_logprob = F.log_softmax(logits, dim=-1) + logprob = torch.gather(all_logprob, 2, response.unsqueeze(-1)).squeeze(-1) + del logits, all_logprob + torch.cuda.empty_cache() + + ref_output = forward(ref_policy, query_response, processing_class.pad_token_id) + ref_logits = ref_output.logits[:, context_length - 1 : -1] + ref_logits /= args.temperature + 1e-7 + ref_all_logprob = F.log_softmax(ref_logits, dim=-1) + ref_logprob = torch.gather(ref_all_logprob, 2, response.unsqueeze(-1)).squeeze(-1) + del ref_output, ref_logits, ref_all_logprob + torch.cuda.empty_cache() + + # Response Processing 1. truncate response after the first occurrence of `stop_token_id` + postprocessed_response = response + if args.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + args.stop_token_id, processing_class.pad_token_id, response + ) + + # Response Processing 2. run reward model on the truncated responses + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + sequence_length = first_true_indices(postprocessed_response == processing_class.pad_token_id) - 1 + _, score, _ = get_reward( + reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + + responses.append(response) + postprocessed_responses.append(postprocessed_response) + logprobs.append(logprob) + ref_logprobs.append(ref_logprob) + sequence_lengths.append(sequence_length) + scores.append(score) + responses = torch.cat(responses, 0) + postprocessed_responses = torch.cat(postprocessed_responses, 0) + logprobs = torch.cat(logprobs, 0) + ref_logprobs = torch.cat(ref_logprobs, 0) + sequence_lengths = torch.cat(sequence_lengths, 0) + scores = torch.cat(scores, 0) + del (logprob, ref_logprob, score) + torch.cuda.empty_cache() + gc.collect() + + # Response Processing 3. filter response. Ensure that the sample contains stop_token_id + # responses not passing that filter will receive a low (fixed) score + # only query humans on responses that pass that filter + contain_eos_token = torch.any(postprocessed_responses == processing_class.eos_token_id, dim=-1) + if args.missing_eos_penalty is not None: + scores[~contain_eos_token] -= self.args.missing_eos_penalty + # accelerator.print(f"{scores=}, {(contain_eos_token.sum() / len(contain_eos_token))=}") + + # be very careful with `padding_mask_p1`; see https://excalidraw.com/#json=LWnzG4w2k5DjF_EOL_xPt,e2w3a-hFJ_gX5vOfeyXGTw + response_idxs = torch.arange(responses.shape[1], device=responses.device).repeat(responses.shape[0], 1) + padding_mask = response_idxs > sequence_lengths.unsqueeze(1) + logprobs = torch.masked_fill(logprobs, padding_mask, INVALID_LOGPROB) + ref_logprobs = torch.masked_fill(ref_logprobs, padding_mask, INVALID_LOGPROB) + + # 4. compute rewards + kl = logprobs - ref_logprobs + non_score_reward = (-args.kl_coef * kl).sum(1) + rlhf_reward = scores + non_score_reward + + # vectorized RLOO advantages implementation + rlhf_reward = rlhf_reward.reshape(args.rloo_k, -1) + baseline = (rlhf_reward.sum(0) - rlhf_reward) / (args.rloo_k - 1) + advantages = rlhf_reward - baseline + advantages = advantages.flatten() + torch.cuda.empty_cache() + + # Do multiple epochs of PPO training, with a fresh random shuffle in each epoch + for ppo_epoch_idx in range(args.num_ppo_epochs): + b_inds = np.random.permutation(args.local_batch_size) + minibatch_idx = 0 + for mini_batch_start in range(0, args.local_batch_size, args.local_mini_batch_size): + mini_batch_end = mini_batch_start + args.local_mini_batch_size + mini_batch_inds = b_inds[mini_batch_start:mini_batch_end] + gradient_accumulation_idx = 0 + for micro_batch_start in range(0, args.local_mini_batch_size, args.per_device_train_batch_size): + with accelerator.accumulate(model): + micro_batch_end = micro_batch_start + args.per_device_train_batch_size + micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end] + mb_advantage = advantages[micro_batch_inds] + mb_responses = responses[micro_batch_inds] + mb_query_responses = query_responses[micro_batch_inds] + mb_logprobs = logprobs[micro_batch_inds] + + output = forward(model, mb_query_responses, processing_class.pad_token_id) + logits = output.logits[:, context_length - 1 : -1] + logits /= args.temperature + 1e-7 + new_all_logprobs = F.log_softmax(logits, dim=-1) + new_logprobs = torch.gather(new_all_logprobs, 2, mb_responses.unsqueeze(-1)).squeeze(-1) + new_logprobs = torch.masked_fill( + new_logprobs, padding_mask[micro_batch_inds], INVALID_LOGPROB + ) + new_ratio = (new_logprobs - mb_logprobs).exp() + new_logprobs = new_logprobs.sum(1) + mb_logprobs = mb_logprobs.sum(1) + logprobs_diff = new_logprobs - mb_logprobs + ratio = torch.exp(logprobs_diff) + pg_losses = -mb_advantage * ratio + pg_losses2 = -mb_advantage * torch.clamp(ratio, 1.0 - args.cliprange, 1.0 + args.cliprange) + pg_loss_max = torch.max(pg_losses, pg_losses2) + pg_loss = pg_loss_max.mean() + loss = pg_loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + with torch.no_grad(): + pg_clipfrac = (pg_losses2 > pg_losses).float().mean() + prob_dist = torch.nn.functional.softmax(logits, dim=-1) + entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1) + approxkl = 0.5 * (logprobs_diff**2).mean() + approxkl_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = approxkl + pg_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ( + pg_clipfrac + ) + pg_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = pg_loss + entropy_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = entropy.mean() + ratio_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = new_ratio.mean() + gradient_accumulation_idx += 1 + minibatch_idx += 1 + # del everything and empty cache + # fmt: off + del ( + output, logits, new_all_logprobs, new_logprobs, + logprobs_diff, ratio, pg_losses, pg_losses2, + pg_loss, loss, pg_clipfrac, prob_dist, entropy, approxkl, + mb_advantage, mb_responses, mb_query_responses, mb_logprobs, + ) + # fmt: on + torch.cuda.empty_cache() + with torch.no_grad(): + mean_kl = kl.sum(1).mean() + mean_entropy = (-logprobs).sum(1).mean() + mean_non_score_reward = non_score_reward.mean() + eps = int(self.state.episode / (time.time() - start_time)) + metrics = {} + metrics["eps"] = eps + metrics["objective/kl"] = self.accelerator.gather(mean_kl).mean().item() + metrics["objective/entropy"] = self.accelerator.gather(mean_entropy).mean().item() + metrics["objective/non_score_reward"] = self.accelerator.gather(mean_non_score_reward).mean().item() + metrics["objective/rlhf_reward"] = self.accelerator.gather(rlhf_reward).mean().item() + metrics["objective/scores"] = self.accelerator.gather(scores.mean()).mean().item() + metrics["policy/approxkl_avg"] = self.accelerator.gather(approxkl_stats).mean().item() + metrics["policy/clipfrac_avg"] = self.accelerator.gather(pg_clipfrac_stats).mean().item() + metrics["loss/policy_avg"] = self.accelerator.gather(pg_loss_stats).mean().item() + metrics["val/clipfrac_avg"] = self.accelerator.gather(vf_clipfrac_stats).mean().item() + metrics["policy/entropy_avg"] = self.accelerator.gather(entropy_stats).mean().item() + metrics["val/ratio"] = self.accelerator.gather(ratio_stats).mean().item() + metrics["val/ratio_var"] = self.accelerator.gather(ratio_stats).var().item() + metrics["val/num_eos_tokens"] = (responses == processing_class.eos_token_id).sum().item() + metrics["lr"] = self.lr_scheduler.get_last_lr()[0] + metrics["episode"] = self.state.episode + self.state.epoch = self.state.episode / (args.rloo_k * self.train_dataset_len) # used by self.log + self.log(metrics) + del kl, mean_kl, mean_entropy, scores + + self.lr_scheduler.step() + self.state.global_step += 1 + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + torch.cuda.empty_cache() + gc.collect() + + if args.num_sample_generations > 0 and (update - 1) % self.sample_generations_freq == 0: + self.generate_completions(sampling=True) + + # HF trainer specifics + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + if self.control.should_save: + self._save_checkpoint(model, trial=None, metrics=None) + self.control = self.callback_handler.on_save(self.args, self.state, self.control) + + def generate_completions(self, sampling: bool = False): + args = self.args + processing_class = self.processing_class + generation_config = GenerationConfig( + max_new_tokens=self.args.response_length, + temperature=(0.01 + 1e-7), + top_k=0.0, + top_p=1.0, + do_sample=True, + ) + + table = defaultdict(list) + with unwrap_model_for_generation(self.model, self.accelerator) as unwrapped_model: + for batch in self.eval_dataloader: + query = batch["input_ids"] + with torch.no_grad(): + context_length = query.shape[1] + query_response, _ = batch_generation( + unwrapped_model, + query, + query.shape[0], + processing_class.pad_token_id, + generation_config, + ) + response = query_response[:, context_length:] + postprocessed_response = response + if args.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0 + postprocessed_response = truncate_response( + args.stop_token_id, processing_class.pad_token_id, response + ) + table["query"].extend( + gather_object(processing_class.batch_decode(query, skip_special_tokens=True)) + ) + table["model response"].extend( + gather_object(processing_class.batch_decode(postprocessed_response)) + ) + + postprocessed_query_response = torch.cat((query, postprocessed_response), 1) + _, score, _ = get_reward( + self.reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length + ) + table["score"].extend(self.accelerator.gather(score).float().cpu().numpy()) + + if sampling: + break + df = pd.DataFrame(table) + + if self.accelerator.is_main_process: + print_rich_table(df.iloc[0 : 0 + 5]) + if "wandb" in args.report_to: + import wandb + + if wandb.run is not None: + wandb.log({"completions": wandb.Table(dataframe=df)}) + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @inproceedings{ahmadian2024back, + title = {{Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs}}, + author = {Arash Ahmadian and Chris Cremer and Matthias Gall{\'{e}} and Marzieh Fadaee and Julia Kreutzer and Olivier Pietquin and Ahmet {\"{U}}st{\"{u}}n and Sara Hooker}, + year = 2024, + booktitle = {Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), {ACL} 2024, Bangkok, Thailand, August 11-16, 2024}, + publisher = {Association for Computational Linguistics}, + pages = {12248--12267}, + editor = {Lun{-}Wei Ku and Andre Martins and Vivek Srikumar}, + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="RLOO", + trainer_citation=citation, + paper_title="Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs", + paper_id="2402.14740", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/sft_config.py b/testbed/huggingface__trl/trl/trainer/sft_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a407a01ee6c126c43c1f6d82fa5e528f4f6c6da4 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/sft_config.py @@ -0,0 +1,72 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from transformers import TrainingArguments + + +@dataclass +class SFTConfig(TrainingArguments): + r""" + Configuration class for the [`SFTTrainer`]. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + dataset_text_field (`str`, *optional*, defaults to `"text"`): + Name of the text field of the dataset. If provided, the trainer will automatically create a + [`ConstantLengthDataset`] based on `dataset_text_field`. + packing (`bool`, *optional*, defaults to `False`): + Controls whether the [`ConstantLengthDataset`] packs the sequences of the dataset. + learning_rate (`float`, *optional*, defaults to `2e-5`): + Initial learning rate for [`AdamW`] optimizer. The default value replaces that of [`~transformers.TrainingArguments`]. + max_seq_length (`Optional[int]`, *optional*, defaults to `None`): + Maximum sequence length for the [`ConstantLengthDataset`] and for automatically creating the dataset. If + `None`, it uses the smaller value between `tokenizer.model_max_length` and `1024`. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. Only used when `packing=False`. + dataset_batch_size (`Union[int, None]`, *optional*, defaults to `1000`): + Number of examples to tokenize per batch. If `dataset_batch_size <= 0` or `dataset_batch_size is None`, + tokenizes the full dataset as a single batch. + model_init_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a + string. + dataset_kwargs (`Optional[Dict[str, Any]]`, *optional*, defaults to `None`): + Dictionary of optional keyword arguments to pass when creating packed or non-packed datasets. + eval_packing (`Optional[bool]`, *optional*, defaults to `None`): + Whether to pack the eval dataset. If `None`, uses the same value as `packing`. + num_of_sequences (`int`, *optional*, defaults to `1024`): + Number of sequences to use for the [`ConstantLengthDataset`]. + chars_per_token (`float`, *optional*, defaults to `3.6`): + Number of characters per token to use for the [`ConstantLengthDataset`]. See + [chars_token_ratio](https://github.com/huggingface/trl/blob/08f550674c553c36c51d1027613c29f14f3676a5/examples/stack_llama/scripts/supervised_finetuning.py#L53) for more details. + use_liger (`bool`, *optional*, defaults to `False`): + Monkey patch the model with Liger kernels to increase throughput and reduce memory usage. + """ + + dataset_text_field: str = "text" + packing: bool = False + learning_rate: float = 2.0e-5 + max_seq_length: Optional[int] = None + dataset_num_proc: Optional[int] = None + dataset_batch_size: int = 1000 + model_init_kwargs: Optional[Dict[str, Any]] = None + dataset_kwargs: Optional[Dict[str, Any]] = None + eval_packing: Optional[bool] = None + num_of_sequences: int = 1024 + chars_per_token: float = 3.6 + use_liger: bool = False diff --git a/testbed/huggingface__trl/trl/trainer/sft_trainer.py b/testbed/huggingface__trl/trl/trainer/sft_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2dce57b12be7c143ebbae10bea88b3e9a7b43cd4 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/sft_trainer.py @@ -0,0 +1,544 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import dataclasses +import inspect +import os +import warnings +from typing import Callable, Dict, List, Optional, Tuple, Union + +import datasets +import torch +import torch.nn as nn +from accelerate.state import PartialState +from datasets import Dataset +from datasets.arrow_writer import SchemaInferenceError +from datasets.builder import DatasetGenerationError +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + BaseImageProcessor, + DataCollator, + DataCollatorForLanguageModeling, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + Trainer, + is_wandb_available, +) +from transformers.trainer_callback import TrainerCallback +from transformers.trainer_utils import EvalPrediction +from transformers.utils import is_liger_kernel_available, is_peft_available +from transformers.utils.deprecation import deprecate_kwarg + +from ..extras.dataset_formatting import get_formatting_func_from_dataset +from .sft_config import SFTConfig +from .utils import ( + ConstantLengthDataset, + DataCollatorForCompletionOnlyLM, + generate_model_card, + peft_module_casting_to_bf16, +) + + +if is_peft_available(): + from peft import PeftConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training + +if is_liger_kernel_available(): + from liger_kernel.transformers import AutoLigerKernelForCausalLM + +if is_wandb_available(): + import wandb + + +class SFTTrainer(Trainer): + r""" + Class definition of the Supervised Finetuning Trainer (SFT Trainer). + This class is a wrapper around the `transformers.Trainer` class and inherits all of its attributes and methods. + The trainer takes care of properly initializing the PeftModel in case a user passes a `PeftConfig` object. + + Args: + model (Union[`transformers.PreTrainedModel`, `nn.Module`, `str`]): + The model to train, can be a `PreTrainedModel`, a `torch.nn.Module` or a string with the model name to + load from cache or download. The model can be also converted to a `PeftModel` if a `PeftConfig` object is + passed to the `peft_config` argument. + args (`Optional[SFTConfig]`): + The arguments to tweak for training. Will default to a basic instance of [`SFTConfig`] with the `output_dir` + set to a directory named *tmp_trainer* in the current directory if not provided. + data_collator (`Optional[transformers.DataCollator]`): + The data collator to use for training. + train_dataset (`Optional[datasets.Dataset]`): + The dataset to use for training. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset. + eval_dataset (Optional[Union[`datasets.Dataset`, Dict[`str`, `datasets.Dataset`]]]): + The dataset to use for evaluation. We recommend users to use `trl.trainer.ConstantLengthDataset` to create their dataset. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + This supercedes the `tokenizer` argument, which is now deprecated. + model_init (`Callable[[], transformers.PreTrainedModel]`): + The model initializer to use for training. If None is specified, the default model initializer will be used. + compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to None): + The function used to compute metrics during evaluation. It should return a dictionary mapping metric names to metric values. + If not specified, only the loss will be computed during evaluation. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + peft_config (`Optional[PeftConfig]`): + The PeftConfig object to use to initialize the PeftModel. + formatting_func (`Optional[Callable]`): + The formatting function to be used for creating the `ConstantLengthDataset`. + """ + + _tag_names = ["trl", "sft"] + + @deprecate_kwarg("tokenizer", new_name="processing_class", version="0.16.0", raise_if_both_names=True) + def __init__( + self, + model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, + args: Optional[SFTConfig] = None, + data_collator: Optional[DataCollator] = None, # type: ignore + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + model_init: Optional[Callable[[], PreTrainedModel]] = None, + compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + peft_config: Optional["PeftConfig"] = None, + formatting_func: Optional[Callable] = None, + ): + if args is None: + output_dir = "tmp_trainer" + warnings.warn(f"No `SFTConfig` passed, using `output_dir={output_dir}`.") + args = SFTConfig(output_dir=output_dir) + elif args is not None and args.__class__.__name__ == "TrainingArguments": + args_as_dict = args.to_dict() + # Manually copy token values as TrainingArguments.to_dict() redacts them + args_as_dict.update({k: getattr(args, k) for k in args_as_dict.keys() if k.endswith("_token")}) + args = SFTConfig(**args_as_dict) + + if getattr(args, "model_init_kwargs", None) is None: + model_init_kwargs = {} + elif not isinstance(model, str): + raise ValueError("You passed model_init_kwargs to the SFTConfig, but your model is already instantiated.") + else: + model_init_kwargs = args.model_init_kwargs + torch_dtype = model_init_kwargs.get("torch_dtype") + if torch_dtype is not None: + # Convert to `torch.dtype` if an str is passed + if isinstance(torch_dtype, str) and torch_dtype != "auto": + torch_dtype = getattr(torch, torch_dtype) + if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): + raise ValueError( + f"Invalid `torch_dtype` passed to the SFTConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." + ) + model_init_kwargs["torch_dtype"] = torch_dtype + + if isinstance(model, str): + warnings.warn( + "You passed a model_id to the SFTTrainer. This will automatically create an " + "`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you." + ) + if args.use_liger: + model = AutoLigerKernelForCausalLM.from_pretrained(model, **model_init_kwargs) + else: + model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) + + if args.packing and data_collator is not None and isinstance(data_collator, DataCollatorForCompletionOnlyLM): + raise ValueError( + "You passed a `DataCollatorForCompletionOnlyLM` to the SFTTrainer. This is not compatible with the `packing` argument." + ) + + if is_peft_available() and peft_config is not None: + if not isinstance(peft_config, PeftConfig): + raise ValueError( + "If you want to use the PeftModel, you need to pass a PeftConfig object to the SFTTrainer." + f" and you passed a {type(peft_config)}." + ) + + if not isinstance(model, PeftModel): + _support_gc_kwargs = hasattr( + args, "gradient_checkpointing_kwargs" + ) and "gradient_checkpointing_kwargs" in list( + inspect.signature(prepare_model_for_kbit_training).parameters + ) + gradient_checkpointing_kwargs = getattr(args, "gradient_checkpointing_kwargs", None) or {} + is_sharded_qlora = False + # Below is to support QLoRA + FSDP / DS-Zero3 - one should never call + # peft_module_casting_to_bf16 or prepare_model_for_kbit_training when doing + # QLoRA + FSDP / DS-Zero3 + if getattr(model, "is_loaded_in_4bit", False): + for _, param in model.named_parameters(): + if param.__class__.__name__ == "Params4bit": + is_sharded_qlora = param.data.device.type in {"cpu", "meta"} + break + if getattr(model, "is_loaded_in_8bit", False) or ( + getattr(model, "is_loaded_in_4bit", False) and not is_sharded_qlora + ): + prepare_model_kwargs = { + "use_gradient_checkpointing": getattr(args, "gradient_checkpointing", False) + } + + if _support_gc_kwargs: + prepare_model_kwargs["gradient_checkpointing_kwargs"] = gradient_checkpointing_kwargs + + model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) + + if args is not None: + args = dataclasses.replace(args, gradient_checkpointing=False) + elif getattr(args, "gradient_checkpointing", False) and ( + "use_reentrant" not in gradient_checkpointing_kwargs + or gradient_checkpointing_kwargs["use_reentrant"] + ): + # For backward compatibility with older versions of transformers + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + if ( + "autocast_adapter_dtype" in list(inspect.signature(get_peft_model).parameters) + and getattr(model, "is_loaded_in_4bit", False) + and is_sharded_qlora + ): + model = get_peft_model(model, peft_config, autocast_adapter_dtype=False) + else: + model = get_peft_model(model, peft_config) + if ( + args is not None + and args.bf16 + and getattr(model, "is_loaded_in_4bit", False) + and not is_sharded_qlora + ): + peft_module_casting_to_bf16(model) + + if processing_class is None: + processing_class = AutoTokenizer.from_pretrained(model.config._name_or_path) + if getattr(processing_class, "pad_token", None) is None: + processing_class.pad_token = processing_class.eos_token + + if args.max_seq_length is None: + # to overcome some issues with broken tokenizers + args.max_seq_length = min(processing_class.model_max_length, 1024) + + warnings.warn( + f"You didn't pass a `max_seq_length` argument to the SFTTrainer, this will default to {args.max_seq_length}" + ) + + self.dataset_num_proc = args.dataset_num_proc + self.dataset_batch_size = args.dataset_batch_size + + if args.dataset_kwargs is None: + args.dataset_kwargs = {} + + if formatting_func is None: + # check if dataset has ChatML format or instruction format and is supported + # if not stays None + formatting_func = get_formatting_func_from_dataset(train_dataset, processing_class) + # if a template is detected, we don't need to add special tokens again + if formatting_func is not None: + args.dataset_kwargs["add_special_tokens"] = False + + if not args.packing: + if data_collator is None: + data_collator = DataCollatorForLanguageModeling(tokenizer=processing_class, mlm=False) + + # Pre-process the datasets only once per node. The remaining processes will use the cache. + with PartialState().local_main_process_first(): + if train_dataset is not None: + train_dataset = self._prepare_dataset( + train_dataset, + processing_class, + args.packing, + args.dataset_text_field, + args.max_seq_length, + formatting_func, + args.num_of_sequences, + args.chars_per_token, + remove_unused_columns=args.remove_unused_columns if args is not None else True, + **args.dataset_kwargs, + ) + if eval_dataset is not None: + _multiple = isinstance(eval_dataset, dict) + _eval_datasets = eval_dataset if _multiple else {"singleton": eval_dataset} + + eval_packing = args.packing if args.eval_packing is None else args.eval_packing + + for _eval_dataset_name, _eval_dataset in _eval_datasets.items(): + _eval_datasets[_eval_dataset_name] = self._prepare_dataset( + _eval_dataset, + processing_class, + eval_packing, + args.dataset_text_field, + args.max_seq_length, + formatting_func, + args.num_of_sequences, + args.chars_per_token, + remove_unused_columns=args.remove_unused_columns if args is not None else True, + **args.dataset_kwargs, + ) + if not _multiple: + eval_dataset = _eval_datasets["singleton"] + + if processing_class.padding_side is not None and processing_class.padding_side != "right": + warnings.warn( + "You passed a processing_class with `padding_side` not equal to `right` to the SFTTrainer. This might lead to some unexpected behaviour due to " + "overflow issues when training a model in half-precision. You might consider adding `processing_class.padding_side = 'right'` to your code." + ) + + super().__init__( + model=model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + model_init=model_init, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + # Add tags for models that have been loaded with the correct transformers version + if hasattr(self.model, "add_model_tags"): + self.model.add_model_tags(self._tag_names) + + if self.train_dataset is not None: + if self.args.max_steps > 0 and args.packing: + warnings.warn( + "You passed `packing=True` to the SFTTrainer/SFTConfig, and you are training your model with `max_steps` strategy. The dataset will be iterated until the `max_steps` are reached." + ) + self.train_dataset.infinite = True + elif self.args.max_steps == -1 and args.packing: + self.train_dataset.infinite = False + + def _prepare_dataset( + self, + dataset, + processing_class, + packing, + dataset_text_field: str, + max_seq_length, + formatting_func: Optional[Callable], + num_of_sequences, + chars_per_token, + remove_unused_columns=True, + append_concat_token=True, + add_special_tokens=True, + skip_prepare_dataset=False, + ): + if dataset is None: + raise ValueError("The dataset should not be None") + + if skip_prepare_dataset: + return dataset + + # If the dataset is already preprocessed (tokenized), return as-is. Only works if dataset is + # a datasets.Dataset or datasets.IterableDataset -- not for torch Dataset + column_names = ( + dataset.column_names if isinstance(dataset, (datasets.Dataset, datasets.IterableDataset)) else None + ) + if column_names and "input_ids" in column_names: + if formatting_func is not None: + warnings.warn( + "You passed a dataset that is already processed (contains an `input_ids` field) together with a valid formatting function. Therefore `formatting_func` will be ignored." + ) + + return dataset + + # check if torch dataset / dataloader and do nothing + # see https://github.com/huggingface/trl/pull/1468 for why datasets.IterableDataset needs a separate check + if isinstance( + dataset, (torch.utils.data.IterableDataset, torch.utils.data.Dataset, ConstantLengthDataset) + ) and not isinstance(dataset, datasets.IterableDataset): + return dataset + + if not packing: + return self._prepare_non_packed_dataloader( + processing_class, + dataset, + dataset_text_field, + max_seq_length, + formatting_func, + add_special_tokens, + remove_unused_columns, + ) + + else: + return self._prepare_packed_dataloader( + processing_class, + dataset, + dataset_text_field, + max_seq_length, + num_of_sequences, + chars_per_token, + formatting_func, + append_concat_token, + add_special_tokens, + ) + + def _prepare_non_packed_dataloader( + self, + processing_class, + dataset, + dataset_text_field: str, + max_seq_length, + formatting_func: Optional[Callable] = None, + add_special_tokens=True, + remove_unused_columns=True, + ): + # Inspired from: https://huggingface.co/learn/nlp-course/chapter7/6?fw=pt + def tokenize(element): + outputs = processing_class( + element[dataset_text_field] if formatting_func is None else formatting_func(element), + add_special_tokens=add_special_tokens, + truncation=True, + padding=False, + max_length=max_seq_length, + return_overflowing_tokens=False, + return_length=False, + ) + + if formatting_func is not None and not isinstance(formatting_func(element), list): + raise ValueError( + "The `formatting_func` should return a list of processed strings since it can lead to silent bugs." + ) + + return {"input_ids": outputs["input_ids"], "attention_mask": outputs["attention_mask"]} + + signature_columns = ["input_ids", "labels", "attention_mask"] + + if dataset.column_names is not None: # None for IterableDataset + extra_columns = list(set(dataset.column_names) - set(signature_columns)) + else: + extra_columns = [] + + if not remove_unused_columns and len(extra_columns) > 0: + warnings.warn( + "You passed `remove_unused_columns=False` on a non-packed dataset. This might create some issues with the default collator and yield to errors. If you want to " + f"inspect dataset other columns (in this case {extra_columns}), you can subclass `DataCollatorForLanguageModeling` in case you used the default collator and create your own data collator in order to inspect the unused dataset columns." + ) + + map_kwargs = { + "batched": True, + "remove_columns": dataset.column_names if remove_unused_columns else None, + "batch_size": self.dataset_batch_size, + } + if isinstance(dataset, datasets.Dataset): + map_kwargs["num_proc"] = self.dataset_num_proc # this arg is not available for IterableDataset + tokenized_dataset = dataset.map(tokenize, **map_kwargs) + + return tokenized_dataset + + def _prepare_packed_dataloader( + self, + processing_class, + dataset, + dataset_text_field: str, + max_seq_length, + num_of_sequences, + chars_per_token, + formatting_func: Optional[Callable] = None, + append_concat_token=True, + add_special_tokens=True, + ): + if processing_class is None: + raise ValueError("You need to pass a processing_class with `SFTTrainer`.") + + constant_length_iterator = ConstantLengthDataset( + processing_class, + dataset, + dataset_text_field=None if formatting_func is not None else dataset_text_field, + formatting_func=formatting_func, + seq_length=max_seq_length, + infinite=False, + num_of_sequences=num_of_sequences, + chars_per_token=chars_per_token, + eos_token_id=processing_class.eos_token_id, + append_concat_token=append_concat_token, + add_special_tokens=add_special_tokens, + ) + + if isinstance(dataset, datasets.IterableDataset): + return constant_length_iterator + + def data_generator(constant_length_iterator): + yield from constant_length_iterator + + try: + packed_dataset = Dataset.from_generator( + data_generator, gen_kwargs={"constant_length_iterator": constant_length_iterator} + ) + except (DatasetGenerationError, SchemaInferenceError) as exc: + raise ValueError( + "Error occurred while packing the dataset. " + "Make sure that your dataset has enough samples to at least yield one packed sequence." + ) from exc + return packed_dataset + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="SFT", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/trainer/utils.py b/testbed/huggingface__trl/trl/trainer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..96dc8fba244c32f5a6e65303f326774037fa36f8 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/utils.py @@ -0,0 +1,1466 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import dataclasses +import importlib.resources as pkg_resources +import json +import random +import warnings +from collections import deque +from dataclasses import dataclass +from importlib.metadata import version +from typing import Any, Dict, List, Literal, Optional, Tuple, Union + +import numpy as np +import pandas as pd +import torch +import torch.utils.data +from accelerate import Accelerator, PartialState +from accelerate.state import AcceleratorState +from huggingface_hub import ModelCard, ModelCardData +from rich.console import Console +from rich.table import Table +from torch.nn.utils.rnn import pad_sequence +from torch.utils.data import IterableDataset +from transformers import ( + BitsAndBytesConfig, + DataCollatorForLanguageModeling, + GenerationConfig, + PreTrainedTokenizerBase, + TrainerState, + TrainingArguments, +) +from transformers.utils import ( + is_peft_available, + is_torch_mlu_available, + is_torch_npu_available, + is_torch_xpu_available, +) + +from ..import_utils import is_unsloth_available +from ..trainer.model_config import ModelConfig + + +if is_peft_available(): + from peft import LoraConfig, PeftConfig + + +class AdaptiveKLController: + """ + Adaptive KL controller described in the paper: + https://huggingface.co/papers/1909.08593 + """ + + def __init__(self, init_kl_coef, target, horizon): + self.value = init_kl_coef + self.target = target + self.horizon = horizon + + def update(self, current, n_steps): + target = self.target + proportional_error = np.clip(current / target - 1, -0.2, 0.2) + mult = 1 + proportional_error * n_steps / self.horizon + self.value *= mult + + +class FixedKLController: + """Fixed KL controller.""" + + def __init__(self, kl_coef): + self.value = kl_coef + + def update(self, current, n_steps): + pass + + +class DataCollatorForCompletionOnlyLM(DataCollatorForLanguageModeling): + """ + Data collator used for completion tasks. It ensures that all the tokens of the labels are set to an 'ignore_index' + when they do not come from the assistant. This ensure that the loss is only + calculated on the completion made by the assistant. + + Args: + response_template (`Union[str, List[int]]`): the template form that indicates the start of the response, typically something like + '### Response:\n'. It can also be passed as tokenized ids, which can be useful when using a tokenizer that encodes the response + differently if it does not have proper context. + instruction_template (`Union[str, List[int]]`): the template form that indicates the start of the human instruction, typically something like + '### Human:\n'. Useful for assistant-style conversation datasets. It can also be passed as tokenized ids. + mlm (`bool`, *optional*, defaults to `False`): Whether or not to use masked language modeling in the underlying + `DataCollatorForLanguageModeling` class. Note that this option currently has no effect but is present + for flexibility and backwards-compatibility. + ignore_index (`int`, *optional*, defaults to `-100`): + The index to use to ignore the initial tokens with + """ + + def __init__( + self, + response_template: Union[str, List[int]], + instruction_template: Optional[Union[str, List[int]]] = None, + *args, + mlm: bool = False, + ignore_index: int = -100, + padding_free: bool = False, + **kwargs, + ): + super().__init__(*args, mlm=mlm, **kwargs) + + self.instruction_template = instruction_template + if isinstance(instruction_template, str): + # The user provides a string, must tokenize + self.instruction_token_ids = self.tokenizer.encode(self.instruction_template, add_special_tokens=False) + else: + # The user already provides the token ids + self.instruction_token_ids = instruction_template + + self.response_template = response_template + if isinstance(response_template, str): + # The user provides a string, must tokenize + self.response_token_ids = self.tokenizer.encode(self.response_template, add_special_tokens=False) + else: + # The user already provides the token ids + self.response_token_ids = response_template + + if not self.mlm and self.instruction_template and self.tokenizer.pad_token_id == self.tokenizer.eos_token_id: + warnings.warn( + "The pad_token_id and eos_token_id values of this tokenizer are identical. " + "If you are planning for multi-turn training, " + "it can result in the model continuously generating questions and answers without eos token. " + "To avoid this, set the pad_token_id to a different value." + ) + + self.ignore_index = ignore_index + self.padding_free = padding_free + + def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]: + batch = super().torch_call(examples) + + if self.instruction_template is None: + for i in range(len(examples)): + response_token_ids_start_idx = None + + for idx in np.where(batch["labels"][i] == self.response_token_ids[0])[0]: + # `response_token_ids` is `'### Response:\n'`, here we are just making sure that the token IDs match + if ( + self.response_token_ids + == batch["labels"][i][idx : idx + len(self.response_token_ids)].tolist() + ): + response_token_ids_start_idx = idx + + if response_token_ids_start_idx is None: + warnings.warn( + f"Could not find response key `{self.response_template}` in the " + f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} ' + f"This instance will be ignored in loss calculation. " + f"Note, if this happens often, consider increasing the `max_seq_length`." + ) + batch["labels"][i, :] = self.ignore_index + else: + response_token_ids_end_idx = response_token_ids_start_idx + len(self.response_token_ids) + + # Make pytorch loss function ignore all tokens up through the end of the response key + batch["labels"][i, :response_token_ids_end_idx] = self.ignore_index + + else: + for i in range(len(examples)): + response_token_ids_idxs = [] + human_token_ids_idxs = [] + + for assistant_idx in np.where(batch["labels"][i] == self.response_token_ids[0])[0]: + # find the indexes of the start of a response. + if ( + self.response_token_ids + == batch["labels"][i][assistant_idx : assistant_idx + len(self.response_token_ids)].tolist() + ): + response_token_ids_idxs.append(assistant_idx + len(self.response_token_ids)) + + if len(response_token_ids_idxs) == 0: + warnings.warn( + f"Could not find response key `{self.response_template}` in the " + f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} ' + f"This instance will be ignored in loss calculation. " + f"Note, if this happens often, consider increasing the `max_seq_length`." + ) + batch["labels"][i, :] = self.ignore_index + + human_token_ids = self.instruction_token_ids + for human_idx in np.where(batch["labels"][i] == human_token_ids[0])[0]: + # find the indexes of the start of a human answer. + if human_token_ids == batch["labels"][i][human_idx : human_idx + len(human_token_ids)].tolist(): + human_token_ids_idxs.append(human_idx) + + if len(human_token_ids_idxs) == 0: + warnings.warn( + f"Could not find instruction key `{self.instruction_template}` in the " + f'following instance: {self.tokenizer.decode(batch["input_ids"][i])} ' + f"This instance will be ignored in loss calculation. " + f"Note, if this happens often, consider increasing the `max_seq_length`." + ) + batch["labels"][i, :] = self.ignore_index + + if ( + len(human_token_ids_idxs) > 0 + and len(response_token_ids_idxs) > 0 + and human_token_ids_idxs[0] > response_token_ids_idxs[0] + ): + human_token_ids_idxs = [0] + human_token_ids_idxs + + for idx, (start, end) in enumerate(zip(human_token_ids_idxs, response_token_ids_idxs)): + # Make pytorch loss function ignore all non response tokens + if idx != 0: + batch["labels"][i, start:end] = self.ignore_index + else: + batch["labels"][i, :end] = self.ignore_index + + if len(response_token_ids_idxs) < len(human_token_ids_idxs): + batch["labels"][i, human_token_ids_idxs[-1] :] = self.ignore_index + + if self.padding_free: + # remove padding, `attention_mask` and add `position_ids` + attn_mask = batch.pop("attention_mask") + batch["input_ids"] = batch["input_ids"][attn_mask.bool()].unsqueeze(0) + batch["position_ids"] = attn_mask.cumsum(1)[attn_mask.bool()].unsqueeze(0) - 1 + batch["labels"] = batch["labels"][attn_mask.bool()].unsqueeze(0) + batch["labels"][batch["position_ids"] == 0] = self.ignore_index + + return batch + + +@dataclass +class DataCollatorForChatML: + """ + Data collator for ChatML format datasets. + """ + + tokenizer: PreTrainedTokenizerBase + ignore_index: int = -100 + max_length: int = None + prompt_key: str = "prompt" + messages_key: str = "messages" + + def __post_init__(self): + if self.tokenizer.pad_token_id is None: + raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.") + if self.max_length is None: + # set a sensible default + self.max_length = min(self.tokenizer.model_max_length, 1024) + + def __call__(self, examples: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]: + input_ids = [] + attention_mask = [] + prompts_input_ids = [] + prompt_attention_mask = [] + labels = [] + + for example in examples: + formatted_prompt = example.get(self.prompt_key, None) + if formatted_prompt is None: + prompt = example[self.messages_key][:-1] + formatted_prompt = self.tokenizer.apply_chat_template( + prompt, tokenize=False, add_generation_prompt=True + ) + + if "input_ids" not in example: + message = example[self.messages_key] + formatted_message = self.tokenizer.apply_chat_template( + message, tokenize=False, add_generation_prompt=True + ) + tokenized_message = self.tokenizer( + formatted_message, + truncation=True, + max_length=self.max_length, + padding=False, + return_tensors=None, + add_special_tokens=False, + ) + input_ids.append(tokenized_message["input_ids"]) + attention_mask.append(tokenized_message["attention_mask"]) + else: + input_ids.append(example["input_ids"]) + attention_mask.append(example["attention_mask"]) + + tokenized_prompt = self.tokenizer( + formatted_prompt, + truncation=True, + max_length=len(input_ids[-1]), + padding=False, + return_tensors=None, + add_special_tokens=False, + ) + + prompts_input_ids.append(tokenized_prompt["input_ids"]) + prompt_attention_mask.append(tokenized_prompt["attention_mask"]) + + # Create the labels that will have all but the completion tokens of the example["input_ids"] set to ignore_index + label = [self.ignore_index] * len(input_ids[-1]) + completion_start_idx = len(tokenized_prompt["input_ids"]) + label[completion_start_idx:] = input_ids[-1][completion_start_idx:] + labels.append(label) + + # convert to list of tensors and pad + input_ids = [torch.tensor(ids, dtype=torch.long) for ids in input_ids] + attention_mask = [torch.tensor(mask, dtype=torch.long) for mask in attention_mask] + labels = [torch.tensor(label, dtype=torch.long) for label in labels] + input_ids = pad(input_ids, padding_side="left", padding_value=self.tokenizer.pad_token_id) + attention_mask = pad(attention_mask, padding_side="left", padding_value=0) + labels = pad(labels, padding_side="left", padding_value=self.ignore_index) + + prompts_input_ids = [torch.tensor(ids, dtype=torch.long) for ids in prompts_input_ids] + prompt_attention_mask = [torch.tensor(mask, dtype=torch.long) for mask in prompt_attention_mask] + prompts_input_ids = pad(prompts_input_ids, padding_side="left", padding_value=self.tokenizer.pad_token_id) + prompt_attention_mask = pad(prompt_attention_mask, padding_side="left", padding_value=0) + + return { + "input_ids": input_ids, + "attention_mask": attention_mask, + "labels": labels, + "prompts": prompts_input_ids, + "prompt_attention_mask": prompt_attention_mask, + } + + +@dataclass +class RewardDataCollatorWithPadding: + r""" + Reward DataCollator class that pads the inputs to the maximum length of the batch. + + Args: + tokenizer (`PreTrainedTokenizerBase`): + The tokenizer used for encoding the data. + padding (`Union[bool, str, `PaddingStrategy`]`, `optional`, defaults to `True`): + padding_strategy to pass to the tokenizer. + pad_to_multiple_of (`Optional[int]`, `optional`, defaults to `None`): + If set will pad the sequence to a multiple of the provided value. + return_tensors (`str`, `optional`, defaults to `"pt"`): + The tensor type to use. + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str] = True + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + features_chosen = [] + features_rejected = [] + margin = [] + # check if we have a margin. If we do, we need to batch it as well + has_margin = "margin" in features[0] + for feature in features: + # check if the keys are named as expected + if ( + "input_ids_chosen" not in feature + or "input_ids_rejected" not in feature + or "attention_mask_chosen" not in feature + or "attention_mask_rejected" not in feature + ): + raise ValueError( + "The features should include `input_ids_chosen`, `attention_mask_chosen`, `input_ids_rejected` and `attention_mask_rejected`" + ) + + features_chosen.append( + { + "input_ids": feature["input_ids_chosen"], + "attention_mask": feature["attention_mask_chosen"], + } + ) + features_rejected.append( + { + "input_ids": feature["input_ids_rejected"], + "attention_mask": feature["attention_mask_rejected"], + } + ) + if has_margin: + margin.append(feature["margin"]) + batch_chosen = self.tokenizer.pad( + features_chosen, + padding=self.padding, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + batch_rejected = self.tokenizer.pad( + features_rejected, + padding=self.padding, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + batch = { + "input_ids_chosen": batch_chosen["input_ids"], + "attention_mask_chosen": batch_chosen["attention_mask"], + "input_ids_rejected": batch_rejected["input_ids"], + "attention_mask_rejected": batch_rejected["attention_mask"], + "return_loss": True, + } + if has_margin: + margin = torch.tensor(margin, dtype=torch.float) + batch["margin"] = margin + return batch + + +def pad(tensors: List[torch.Tensor], padding_value: int = 0, padding_side: str = "right") -> torch.Tensor: + """ + Pads a list of tensors to the same shape along the first dimension. + + Args: + tensors (`List[torch.Tensor]`): + List of input tensors to pad. + padding_value (`int`): + Value to use for padding. Default is 0. + padding_side (`str`): + Side on which to add padding. Must be 'left' or 'right'. Default is 'right'. + + Returns: + `torch.Tensor`: + A single tensor containing the padded tensors. + + Examples: + >>> import torch + >>> pad([torch.tensor([1, 2, 3]), torch.tensor([4, 5])]) + tensor([[1, 2, 3], + [4, 5, 0]]) + >>> pad([torch.tensor([[1, 2], [3, 4]]), torch.tensor([[5, 6]])]) + tensor([[[1, 2], + [3, 4]], + + [[5, 6], + [0, 0]]]) + """ + # Determine the maximum shape for each dimension + output_shape = np.max([t.shape for t in tensors], 0).tolist() + + # Create an output tensor filled with the padding value + output = torch.full((len(tensors), *output_shape), padding_value, dtype=tensors[0].dtype, device=tensors[0].device) + + for i, t in enumerate(tensors): + # Determine the slice for the sequence dimension + if padding_side == "left": + seq_slice = slice(output_shape[0] - t.shape[0], output_shape[0]) + elif padding_side == "right": + seq_slice = slice(0, t.shape[0]) + else: + raise ValueError("padding_side must be 'left' or 'right'") + + slices = (seq_slice,) + tuple(slice(0, s) for s in t.shape[1:]) + output[i][slices] = t + + return output + + +@dataclass +class DPODataCollatorWithPadding: + r""" + DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch. + + Args: + pad_token_id (`int` defaults to 0): + The tokenizer's pad_token_id. + label_pad_token_id (`int`, defaults to -100): + The label used for masking. + is_encoder_decoder (`Optional[bool]`, `optional`, defaults to `None`): + Whether or not you model has an encoder_decoder architecture. + """ + + pad_token_id: int = 0 + label_pad_token_id: int = -100 + is_encoder_decoder: Optional[bool] = False + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + # first, pad everything to the same length + padded_batch = {} + for k in features[0].keys(): + if k.endswith(("_input_ids", "_attention_mask", "_labels", "_pixel_values")): + if self.is_encoder_decoder: + to_pad = [torch.LongTensor(ex[k]) for ex in features] + + if (k.startswith("prompt")) and (k.endswith("input_ids")): + if self.pad_token_id is None: + raise ValueError( + "Padding is enabled, but the tokenizer is not configured with a padding token." + " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" + " before calling the trainer." + ) + padding_value = self.pad_token_id + elif k.endswith("_attention_mask"): + padding_value = 0 + elif k.startswith(("chosen", "rejected", "completion")) or ("decoder" in k): + padding_value = self.label_pad_token_id + else: + raise ValueError(f"Unexpected key in batch '{k}'") + padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value) + else: + # Set padding value based on the key + if k.endswith("_input_ids"): + if self.pad_token_id is None: + raise ValueError( + "Padding is enabled, but the tokenizer is not configured with a padding token." + " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)" + " before calling the trainer." + ) + padding_value = self.pad_token_id + elif k.endswith("_labels"): + padding_value = self.label_pad_token_id + elif k.endswith("_attention_mask"): + padding_value = 0 + elif k.endswith("_pixel_values"): + padding_value = 0 # TODO: check if this is correct + else: + raise ValueError(f"Unexpected key in batch '{k}'") + + # Set padding side based on the key + if k in ["prompt_input_ids", "prompt_attention_mask"]: + padding_side = "left" + else: + padding_side = "right" + + # Set the dtype + if k.endswith("_pixel_values"): + dtype = torch.float32 # will be downcasted if necessary by the Trainer + else: + dtype = torch.int64 + + # Convert to tensor and pad + to_pad = [torch.tensor(ex[k], dtype=dtype) for ex in features] + padded_batch[k] = pad(to_pad, padding_value=padding_value, padding_side=padding_side) + elif k.endswith("_logps"): + # the cached reference model logprobs + padded_batch[k] = torch.tensor([ex[k] for ex in features]) + else: + padded_batch[k] = [ex[k] for ex in features] + + return padded_batch + + +class ConstantLengthDataset(IterableDataset): + """ + Iterable dataset that returns constant length chunks of tokens from stream of text files. + The dataset also formats the text before tokenization with a specific format that is provided + by the user. + + Args: + tokenizer (`transformers.PreTrainedTokenizer`): + The processor used for processing the data. + dataset (`dataset.Dataset`): + Dataset with text files. + dataset_text_field (`Optional[str]`, *optional*, defaults to `None`): + Name of the field in the dataset that contains the text. Only one of `dataset_text_field` and + `formatting_func` should be provided. + formatting_func (`Callable`, *optional*): + Function that formats the text before tokenization. Usually it is recommended to have follows a certain + pattern such as `"### Question: {question} ### Answer: {answer}"`. Only one of `dataset_text_field` and + `formatting_func` should be provided. + infinite (`bool`, *optional*, defaults to `False`): + If True the iterator is reset after dataset reaches end else stops. + seq_length (`int`, *optional*, defaults to `1024`): + Length of token sequences to return. + num_of_sequences (`int`, *optional*, defaults to `1024`): + Number of token sequences to keep in buffer. + chars_per_token (`int`, *optional*, defaults to `3.6`): + Number of characters per token used to estimate number of tokens in text buffer. + eos_token_id (`int`, *optional*, defaults to `0`): + Id of the end of sequence token if the passed tokenizer does not have an EOS token. + shuffle (`bool`, *optional*, defaults to `True`) + Shuffle the examples before they are returned + append_concat_token (`bool`, *optional*, defaults to `True`) + If true, appends `eos_token_id` at the end of each sample being packed. + add_special_tokens (`bool`, *optional*, defaults to `True`) + If true, tokenizers adds special tokens to each sample being packed. + """ + + def __init__( + self, + tokenizer, + dataset, + dataset_text_field=None, + formatting_func=None, + infinite=False, + seq_length=1024, + num_of_sequences=1024, + chars_per_token=3.6, + eos_token_id=0, + shuffle=True, + append_concat_token=True, + add_special_tokens=True, + ): + self.tokenizer = tokenizer + + if tokenizer.eos_token_id is None: + warnings.warn( + "The passed tokenizer does not have an EOS token. We will use the passed eos_token_id instead which corresponds" + f" to {eos_token_id}. If this is not the correct EOS token, make sure to pass the correct eos_token_id." + ) + + self.concat_token_id = tokenizer.eos_token_id if tokenizer.eos_token_id else eos_token_id + self.dataset = dataset + self.seq_length = seq_length + self.infinite = infinite + self.current_size = 0 + self.max_buffer_size = seq_length * chars_per_token * num_of_sequences + self.shuffle = shuffle + self.append_concat_token = append_concat_token + self.add_special_tokens = add_special_tokens + + if dataset_text_field is not None and formatting_func is not None: + warnings.warn( + "Only one of `dataset_text_field` and `formatting_func` should be provided. " + "Ignoring `dataset_text_field` and using `formatting_func`." + ) + + if formatting_func is not None: + self.formatting_func = formatting_func + elif dataset_text_field is not None: + self.formatting_func = lambda x: x[dataset_text_field] + else: # neither is provided + raise ValueError("Either `dataset_text_field` or `formatting_func` should be provided.") + + if formatting_func is not None: + if formatting_func.__code__.co_argcount > 1: + warnings.warn( + "The passed formatting_func has more than one argument. Usually that function should have a single argument `example`" + " which corresponds to the dictionary returned by each element of the dataset. Make sure you know what you are doing." + ) + + def __len__(self): + return len(self.dataset) + + def __iter__(self): + iterator = iter(self.dataset) + more_examples = True + while more_examples: + buffer, buffer_len = [], 0 + while True: + if buffer_len >= self.max_buffer_size: + break + try: + buffer.append(self.formatting_func(next(iterator))) + buffer_len += len(buffer[-1]) + except StopIteration: + if self.infinite: + iterator = iter(self.dataset) + warnings.warn("The dataset reached end and the iterator is reset to the start.") + else: + more_examples = False + break + if self.shuffle: + random.shuffle(buffer) + tokenized_inputs = self.tokenizer(buffer, add_special_tokens=self.add_special_tokens, truncation=False)[ + "input_ids" + ] + all_token_ids = [] + for tokenized_input in tokenized_inputs: + if self.append_concat_token: + tokenized_input = tokenized_input + [self.concat_token_id] + all_token_ids.extend(tokenized_input) + examples = [] + for i in range(0, len(all_token_ids), self.seq_length): + input_ids = all_token_ids[i : i + self.seq_length] + if len(input_ids) == self.seq_length: + examples.append(input_ids) + if self.shuffle: + # Shuffle again, otherwise split examples occur in consecutive tensors. + random.shuffle(examples) + for example in examples: + self.current_size += 1 + yield { + "input_ids": torch.LongTensor(example), + "labels": torch.LongTensor(example), + } + + +@dataclass +class RunningMoments: + """ + Calculates the running mean and standard deviation of a data stream. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75 + """ + + accelerator: Accelerator + mean: float = 0 + std: float = 1 + var: float = 1 + count: float = 1e-24 + + @torch.no_grad() + def update(self, xs: torch.Tensor) -> Tuple[float, float]: + """ + Updates running moments from batch's moments computed across ranks + """ + if self.accelerator.use_distributed: + xs_mean, xs_var, xs_count = get_global_statistics(self.accelerator, xs) + else: + xs_count = xs.numel() + xs_var, xs_mean = torch.var_mean(xs, unbiased=False) + xs_mean, xs_var = xs_mean.float(), xs_var.float() + + delta = xs_mean - self.mean + tot_count = self.count + xs_count + + new_sum = xs_var * xs_count + # correct old_sum deviation accounting for the new mean + old_sum = self.var * self.count + delta**2 * self.count * xs_count / tot_count + tot_sum = old_sum + new_sum + + self.mean += (delta * xs_count / tot_count).item() + new_var = tot_sum / tot_count + self.std = (new_var * tot_count / (tot_count - 1)).float().sqrt().item() + self.var = new_var.item() + self.count = tot_count + + return xs_mean.item(), (xs_var * xs_count / (xs_count - 1)).float().sqrt().item() + + def save_to_json(self, json_path: str): + """Save the content of this instance in JSON format inside `json_path`.""" + # save everything except accelerator + if self.accelerator.is_main_process: + save_dict = dataclasses.asdict(self, dict_factory=lambda x: {k: v for (k, v) in x if k != "accelerator"}) + json_string = json.dumps(save_dict, indent=2, sort_keys=True) + "\n" + with open(json_path, "w", encoding="utf-8") as f: + f.write(json_string) + + @classmethod + def load_from_json(cls, accelerator: Accelerator, json_path: str): + """Create an instance from the content of `json_path`.""" + # load everything except accelerator + with open(json_path, encoding="utf-8") as f: + text = f.read() + return cls(accelerator=accelerator, **json.loads(text)) + + +@torch.no_grad() +def get_global_statistics( + accelerator, xs: torch.Tensor, mask=None, device="cpu" +) -> Tuple[torch.Tensor, torch.Tensor, int]: + """ + Computes element-wise mean and variance of the tensor across processes. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75 + """ + xs = xs.to(accelerator.device) + sum_and_count = torch.tensor([xs.sum(), (xs.numel() if mask is None else mask.sum())], device=xs.device) + sum_and_count = accelerator.reduce(sum_and_count) + global_sum, count = sum_and_count + global_mean = global_sum / count + + sum_var = torch.sum(((xs - global_mean) ** 2).mul(1 if mask is None else mask)) + sum_var = accelerator.reduce(sum_var) + global_var = sum_var / count + + return global_mean.to(device), global_var.to(device), count.item() + + +def compute_accuracy(eval_pred) -> Dict[str, float]: + predictions, labels = eval_pred + # Here, predictions is rewards_chosen and rewards_rejected. + # We want to see how much of the time rewards_chosen > rewards_rejected. + if np.array(predictions[:, 0] == predictions[:, 1], dtype=float).sum() > 0: + warnings.warn( + f"There are {np.array(predictions[:, 0] == predictions[:, 1]).sum()} out of {len(predictions[:, 0])} instances where the predictions for both options are equal. As a consequence the accuracy can be misleading." + ) + predictions = np.argmax(predictions, axis=1) + + accuracy = np.array(predictions == labels, dtype=float).mean().item() + return {"accuracy": accuracy} + + +def pad_to_length(tensor: torch.Tensor, length: int, pad_value: Union[int, float], dim: int = -1) -> torch.Tensor: + if tensor.size(dim) >= length: + return tensor + else: + pad_size = list(tensor.shape) + pad_size[dim] = length - tensor.size(dim) + return torch.cat( + [ + tensor, + pad_value * torch.ones(*pad_size, dtype=tensor.dtype, device=tensor.device), + ], + dim=dim, + ) + + +def disable_dropout_in_model(model: torch.nn.Module) -> None: + for module in model.modules(): + if isinstance(module, torch.nn.Dropout): + module.p = 0 + + +def exact_div(a, b, custom_error_message=""): + q = a // b + if a != q * b: + raise ValueError(f"{custom_error_message}, inexact division: {a} / {b} = {a / b}") + return q + + +# copied from https://github.com/kvablack/ddpo-pytorch/blob/main/ddpo_pytorch/stat_tracking.py#L5 +class PerPromptStatTracker: + r""" + Class for tracking statistics per prompt. Mainly used to calculate advantage for the DPPO algorithm + + Args: + buffer_size (`int`): + Size of the buffer to keep for each prompt. + min_count (`int`): + Minimum number of samples to keep in the buffer before calculating the mean and std. + """ + + def __init__(self, buffer_size, min_count): + self.buffer_size = buffer_size + self.min_count = min_count + self.stats = {} + + def update(self, prompts, rewards): + prompts = np.array(prompts) + rewards = np.array(rewards) + unique = np.unique(prompts) + advantages = np.empty_like(rewards) + for prompt in unique: + prompt_rewards = rewards[prompts == prompt] + if prompt not in self.stats: + self.stats[prompt] = deque(maxlen=self.buffer_size) + self.stats[prompt].extend(prompt_rewards) + + if len(self.stats[prompt]) < self.min_count: + mean = np.mean(rewards) + std = np.std(rewards) + 1e-6 + else: + mean = np.mean(self.stats[prompt]) + std = np.std(self.stats[prompt]) + 1e-6 + advantages[prompts == prompt] = (prompt_rewards - mean) / std + + return advantages + + def get_stats(self): + return {k: {"mean": np.mean(v), "std": np.std(v), "count": len(v)} for k, v in self.stats.items()} + + +def peft_module_casting_to_bf16(model): + for name, module in model.named_modules(): + if isinstance(module, torch.nn.LayerNorm) or "norm" in name: + module = module.to(torch.float32) + elif any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]): + if hasattr(module, "weight"): + if module.weight.dtype == torch.float32: + module = module.to(torch.bfloat16) + + +def trl_sanitze_kwargs_for_tagging(model, tag_names, kwargs=None): + if is_unsloth_available(): + # Unsloth adds a new attribute in the model config `unsloth_version` + # to keep track of models that have been patched with unsloth. + if hasattr(model, "config") and getattr(model.config, "unsloth_version", None) is not None: + tag_names.append("unsloth") + + if kwargs is not None: + if "tags" not in kwargs: + kwargs["tags"] = tag_names + elif "tags" in kwargs and isinstance(kwargs["tags"], list): + kwargs["tags"].extend(tag_names) + elif "tags" in kwargs and isinstance(kwargs["tags"], str): + tag_names.append(kwargs["tags"]) + kwargs["tags"] = tag_names + return kwargs + + +def get_quantization_config(model_config: ModelConfig) -> Optional[BitsAndBytesConfig]: + if model_config.load_in_4bit: + quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=model_config.torch_dtype, # For consistency with model weights, we use the same value as `torch_dtype` + bnb_4bit_quant_type=model_config.bnb_4bit_quant_type, + bnb_4bit_use_double_quant=model_config.use_bnb_nested_quant, + bnb_4bit_quant_storage=model_config.torch_dtype, + ) + elif model_config.load_in_8bit: + quantization_config = BitsAndBytesConfig( + load_in_8bit=True, + ) + else: + quantization_config = None + + return quantization_config + + +def get_kbit_device_map() -> Optional[Dict[str, int]]: + if is_torch_xpu_available(): + return {"": f"xpu:{PartialState().local_process_index}"} + elif torch.cuda.is_available(): + return {"": PartialState().local_process_index} + else: + return None + + +def get_peft_config(model_config: ModelConfig) -> "Optional[PeftConfig]": + if model_config.use_peft is False: + return None + + if not is_peft_available(): + raise ValueError( + "You need to have PEFT library installed in your environment, make sure to install `peft`. " + "Make sure to run `pip install -U peft`." + ) + + peft_config = LoraConfig( + task_type=model_config.lora_task_type, + r=model_config.lora_r, + target_modules=model_config.lora_target_modules, + lora_alpha=model_config.lora_alpha, + lora_dropout=model_config.lora_dropout, + bias="none", + use_rslora=model_config.use_rslora, + modules_to_save=model_config.lora_modules_to_save, + ) + + return peft_config + + +def get_exp_cap(value, decimal=4): + """ + Get the exponent cap of a value. This is used to cap the exponent of a value to avoid overflow. + The formula is : log(value.dtype.max) + E.g. + For float32 data type, the maximum exponent value is 88.7228 to 4 decimal points. + ``` + + Args: + value (`torch.Tensor`): + The input tensor to obtain the data type + decimal (`int`): + The number of decimal points of the output exponent cap. + eg: direct calling exp(log(torch.float32.max)) will result in inf + so we cap the exponent to 88.7228 to avoid overflow. + """ + vdtype_max = torch.zeros([1]).to(value.dtype) + torch.finfo(value.dtype).max + vdtype_log_max = torch.log(vdtype_max).to(value.device) + return torch.floor(vdtype_log_max * 10**decimal) / 10**decimal if decimal > 0 else vdtype_log_max + + +def cap_exp(value, cap=-1): + # Cap the exponent value below the upper-bound to avoid overflow, before calling torch.exp + cap = get_exp_cap(value) if cap < 0 else cap + return torch.exp(torch.clamp(value, max=cap)) + + +def print_rich_table(df: pd.DataFrame) -> Table: + console = Console() + table = Table(show_lines=True) + for column in df.columns: + table.add_column(column) + for _, row in df.iterrows(): + table.add_row(*row.astype(str).tolist()) + console.print(table) + + +SIMPLE_SFT_CHAT_TEMPLATE = "{% for message in messages %}{{' ' + message['content']}}{% endfor %}{{ eos_token }}" +# SIMPLE_SFT_CHAT_TEMPLATE simply ends things with an EOS token, this helps the SFT model learn to end the completions with EOS tokens + +SIMPLE_CHAT_TEMPLATE = "{% for message in messages %}{{message['role'].capitalize() + ': ' + message['content'] + '\n\n'}}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}" + + +@dataclass +class OnlineTrainerState(TrainerState): + episode: int = 0 + + +@dataclass +class OnPolicyConfig(TrainingArguments): + r""" + Base configuration class for on-policy trainers. + + Using [`~transformers.HfArgumentParser`] we can turn this class into + [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the + command line. + + Parameters: + run_name (`Optional[str]`, *optional*, defaults to `None`): + Name of the run. + dataset_num_proc (`Optional[int]`, *optional*, defaults to `None`): + Number of processes to use for processing the dataset. + num_mini_batches (`int`, *optional*, defaults to `1`): + Number of minibatches to split a batch into. + total_episodes (`Optional[int]`, *optional*, defaults to `None`): + Total number of episodes in the dataset. + local_rollout_forward_batch_size (`int`, *optional*, defaults to `64`): + Per rank no grad forward pass in the rollout phase. + num_sample_generations (`int`, *optional*, defaults to `10`): + Number of debugging samples generations (i.e., `generate_completions` calls) throughout training. + response_length (`int`, *optional*, defaults to `53`): + Length of the response. + stop_token (`Optional[str]`, *optional*, defaults to `None`): + Stop token. + stop_token_id (`Optional[int]`, *optional*, defaults to `None`): + Truncation token id. + temperature (`float`, *optional*, defaults to `0.7`): + Sampling temperature. + missing_eos_penalty (`Optional[float]`, *optional*, defaults to `None`): + Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage + to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive + value. + sft_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`): + Path to the SFT model. + world_size (`Optional[int]`, *optional*, defaults to `None`): + Number of processes (GPUs) to use for the training. + num_total_batches (`Optional[int]`, *optional*, defaults to `None`): + Number of total batches to train. + micro_batch_size (`Optional[int]`, *optional*, defaults to `None`): + Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`). + local_batch_size (`Optional[int]`, *optional*, defaults to `None`): + Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`). + batch_size (`Optional[int]`, *optional*, defaults to `None`): + Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * `gradient_accumulation_steps`). + local_mini_batch_size (`Optional[int]`, *optional*, defaults to `None`): + Mini batch size per GPU. + mini_batch_size (`Optional[int]`, *optional*, defaults to `None`): + Mini batch size across GPUs. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether to push the model to the Hub after training. + """ + + run_name: Optional[str] = None + dataset_num_proc: Optional[int] = None + num_mini_batches: int = 1 + total_episodes: Optional[int] = None + local_rollout_forward_batch_size: int = 64 + num_sample_generations: int = 10 + response_length: int = 53 + stop_token: Optional[Literal["eos"]] = None + stop_token_id: Optional[int] = None + temperature: float = 0.7 + missing_eos_penalty: Optional[float] = None + sft_model_path: str = "EleutherAI/pythia-160m" + world_size: Optional[int] = None + num_total_batches: Optional[int] = None + micro_batch_size: Optional[int] = None + local_batch_size: Optional[int] = None + batch_size: Optional[int] = None + local_mini_batch_size: Optional[int] = None + mini_batch_size: Optional[int] = None + push_to_hub: bool = False + + +def first_true_indices(bools: torch.Tensor, dtype=torch.long): + """ + Takes an N-dimensional bool tensor and returns an (N-1)-dimensional tensor of integers giving + the position of the first True in each "row". + + Returns the length of the rows (bools.size(-1)) if no element is True in a given row. + + Args: + bools (`torch.Tensor`): + An N-dimensional boolean tensor. + dtype (`torch.dtype`, optional): + The desired data type of the output tensor. Defaults to `torch.long`. + + Returns: + `torch.Tensor`: + An (N-1)-dimensional tensor of integers indicating the position of the first True + in each row. If no True value is found in a row, returns the length of the row. + """ + row_len = bools.size(-1) + zero_or_index = row_len * (~bools).type(dtype) + torch.arange(row_len, dtype=dtype, device=bools.device) + return torch.min(zero_or_index, dim=-1).values + + +def get_reward( + model: torch.nn.Module, query_responses: torch.Tensor, pad_token_id: int, context_length: int +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the reward logits and the rewards for a given model and query responses. + + Args: + model (`torch.nn.Module`): + The model used to compute the reward logits. + query_responses (`torch.Tensor`): + The tensor containing the query responses. + pad_token_id (`int`): + The token ID representing the pad token. + context_length (`int`): + The length of the context in the query responses. + + Returns: + tuple: + - `reward_logits` (`torch.Tensor`): + The logits for the reward model. + - `final_rewards` (`torch.Tensor`): + The final rewards for each query response. + - `sequence_lengths` (`torch.Tensor`): + The lengths of the sequences in the query responses. + """ + attention_mask = query_responses != pad_token_id + position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum + lm_backbone = getattr(model, model.base_model_prefix) + input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) + output = lm_backbone( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + output_hidden_states=True, + use_cache=False, # otherwise mistral-based RM would error out + ) + reward_logits = model.score(output.hidden_states[-1]) + sequence_lengths = first_true_indices(query_responses[:, context_length:] == pad_token_id) - 1 + context_length + # https://github.com/huggingface/transformers/blob/dc68a39c8111217683bf49a4912d0c9018bab33d/src/transformers/models/gpt2/modeling_gpt2.py#L1454 + return ( + reward_logits, + reward_logits[ + torch.arange(reward_logits.size(0), device=reward_logits.device), + sequence_lengths, + ].squeeze(-1), + sequence_lengths, + ) + + +def forward( + model: torch.nn.Module, + query_responses: torch.Tensor, + pad_token_id: int, +) -> torch.nn.Module: + """ + Performs a forward pass through the model with the given query responses and pad token ID. + + Args: + model (`torch.nn.Module`): + The model to perform the forward pass. + query_responses (`torch.Tensor`): + The tensor containing the query responses. + pad_token_id (`int`): + The token ID representing the pad token. + + Returns: + `torch.nn.Module`: + The output of the model, including hidden states. + """ + attention_mask = query_responses != pad_token_id + position_ids = attention_mask.cumsum(1) - attention_mask.long() + input_ids = torch.masked_fill(query_responses, ~attention_mask, 0) + return model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + return_dict=True, + output_hidden_states=True, + ) + + +def prepare_deepspeed( + model: torch.nn.Module, per_device_train_batch_size: int, fp16: bool = False, bf16: bool = False +): + """ + Prepares the model for training with DeepSpeed (both for stage 2 and 3), configuring the appropriate settings based on the model and + batch size. + + Args: + model (`torch.nn.Module`): + The model to be prepared for DeepSpeed training. + per_device_train_batch_size (`int`): + The training batch size per device. + + Returns: + `torch.nn.Module`: + The model initialized and configured with DeepSpeed for training. + """ + import deepspeed + + deepspeed_plugin = AcceleratorState().deepspeed_plugin + config_kwargs = deepspeed_plugin.deepspeed_config + if config_kwargs["zero_optimization"]["stage"] != 3: + config_kwargs["train_micro_batch_size_per_gpu"] = per_device_train_batch_size + config_kwargs = { + "train_micro_batch_size_per_gpu": config_kwargs["train_micro_batch_size_per_gpu"], + "prescale_gradients": False, + "wall_clock_breakdown": False, + } + if bf16: + config_kwargs["bf16"] = {"enabled": True} + elif fp16: + config_kwargs["fp16"] = {"enabled": True} + else: + if hasattr(model, "config"): + hidden_size = ( + max(model.config.hidden_sizes) + if getattr(model.config, "hidden_sizes", None) + else getattr(model.config, "hidden_size", None) + ) + if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3: + # Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0` + # This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081 + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": 0, + } + ) + model, *_ = deepspeed.initialize(model=model, config=config_kwargs) + model.eval() + return model + + +def truncate_response(stop_token_id: int, pad_token_id: int, responses: torch.Tensor): + """ + Truncates the responses at the first occurrence of the stop token, filling the rest with pad tokens. + + Args: + stop_token_id (`int`): + The token ID representing the stop token where truncation occurs. + pad_token_id (`int`): + The token ID representing the pad token used to fill the truncated responses. + responses (`torch.Tensor`): + The tensor containing the responses to be truncated. + + Returns: + `torch.Tensor`: + The truncated responses tensor with pad tokens filled after the stop token. + """ + trunc_idxs = first_true_indices(responses == stop_token_id).unsqueeze(-1) + new_size = [1] * (len(responses.size()) - 1) + [responses.shape[1]] + idxs = torch.arange(responses.shape[1], device=responses.device).view(*new_size) + postprocessed_responses = torch.masked_fill(responses, idxs > trunc_idxs, pad_token_id) + return postprocessed_responses + + +def generate( + lm_backbone: torch.nn.Module, queries: torch.Tensor, pad_token_id: int, generation_config: GenerationConfig +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Generates sequences from the language model backbone in a way that does not affect padding tokens. + + Args: + lm_backbone (`torch.nn.Module`): + The language model backbone used for generation. + queries (`torch.Tensor`): + The tensor containing the input queries. + pad_token_id (`int`): + The token ID representing the pad token. + generation_config (`GenerationConfig`): + The configuration for the generation process. + + Returns: + tuple: + - `generated_sequences` (`torch.Tensor`): + The concatenated tensor of input queries and generated sequences. + - `logits` (`torch.Tensor`): + The logits output from the generation process. + """ + context_length = queries.shape[1] + attention_mask = queries != pad_token_id + input_ids = torch.masked_fill(queries, ~attention_mask, 0) + output = lm_backbone.generate( + input_ids=input_ids, + attention_mask=attention_mask, + # position_ids=attention_mask.cumsum(1) - attention_mask.long(), # not needed: already adjusted in generations + # https://github.com/huggingface/transformers/blob/ac33aeeeee2a7a89b89c93c2962e6feb90daef0a/src/transformers/models/gpt2/modeling_gpt2.py#L1227-L1250 + generation_config=generation_config, + return_dict_in_generate=True, + output_scores=True, + ) + logits = torch.stack(output.scores, 1) + return torch.cat((queries, output.sequences[:, context_length:]), dim=1), logits + + +@torch.no_grad() +def batch_generation( + model: torch.nn.Module, + queries: torch.Tensor, + local_rollout_forward_batch_size: int, + pad_token_id: int, + generation_config: GenerationConfig, +): + query_responses = [] + logitss = [] + batch_size = queries.shape[0] + for i in range(0, batch_size, local_rollout_forward_batch_size): + query = queries[i : i + local_rollout_forward_batch_size] + query_response, logits = generate( + model, + query, + pad_token_id, + generation_config, + ) + query_responses.append(query_response) + logitss.append(logits) + + # padding tensors + padded_query_responses = pad(query_responses, padding_value=pad_token_id, padding_side="right") + padded_logitss = pad(logitss, padding_value=0, padding_side="right") + + # reshaping + padded_query_responses = padded_query_responses.view(-1, padded_query_responses.shape[-1])[:batch_size] + padded_logitss = padded_logitss.view(-1, *padded_logitss.shape[2:])[:batch_size] + + return padded_query_responses, padded_logitss + + +def add_bos_token_if_needed( + bos_token_id: Optional[int], + prompt_len_input_ids: int, + prompt_tokens: Dict[str, List[int]], + chosen_prompt_len_input_ids: int, + chosen_tokens: Dict[str, List[int]], + rejected_prompt_len_input_ids: int, + rejected_tokens: Dict[str, List[int]], +): + if bos_token_id is not None: + if prompt_len_input_ids == 0 or bos_token_id != prompt_tokens["prompt_input_ids"][0]: + prompt_tokens["prompt_input_ids"] = [bos_token_id] + prompt_tokens["prompt_input_ids"] + prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"] + if chosen_prompt_len_input_ids == 0 or bos_token_id != chosen_tokens["prompt_input_ids"][0]: + chosen_tokens["prompt_input_ids"] = [bos_token_id] + chosen_tokens["prompt_input_ids"] + chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"] + if rejected_prompt_len_input_ids == 0 or bos_token_id != rejected_tokens["prompt_input_ids"][0]: + rejected_tokens["prompt_input_ids"] = [bos_token_id] + rejected_tokens["prompt_input_ids"] + rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"] + return prompt_tokens, chosen_tokens, rejected_tokens + + +def add_eos_token_if_needed( + eos_token_id: int, chosen_tokens: Dict[str, List[int]], rejected_tokens: Dict[str, List[int]] +): + if len(chosen_tokens["input_ids"]) == 0 or eos_token_id != chosen_tokens["input_ids"][-1]: + chosen_tokens["input_ids"].append(eos_token_id) + chosen_tokens["attention_mask"].append(1) + if len(rejected_tokens["input_ids"]) == 0 or eos_token_id != rejected_tokens["input_ids"][-1]: + rejected_tokens["input_ids"].append(eos_token_id) + rejected_tokens["attention_mask"].append(1) + return chosen_tokens, rejected_tokens + + +def truncate_right( + input_ids: torch.Tensor, stop_token_id: int, pad_token_id: int +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Truncates the input tensor from the right side after the first occurrence of the stop token. + + Args: + input_ids (`torch.Tensor`): + The tensor containing the responses to be truncated + stop_token_id (`int`): + The token ID representing the stop token where truncation occurs + pad_token_id (`int`): + The token ID representing the pad token used to fill the truncated responses + + Returns: + tuple: + - `output_ids` (`torch.Tensor`): + The truncated responses tensor with pad tokens filled after the stop token + - `mask` (`torch.Tensor`): + The mask tensor to indicate the padding tokens + """ + trunc_idxs = first_true_indices(input_ids == stop_token_id).unsqueeze(-1) + new_size = [1] * (len(input_ids.size()) - 1) + [input_ids.shape[1]] + idxs = torch.arange(input_ids.shape[1], device=input_ids.device).view(*new_size) + output_ids = torch.masked_fill(input_ids, idxs > trunc_idxs, pad_token_id) + mask = torch.masked_fill(torch.ones_like(input_ids), idxs > trunc_idxs, 0) + return output_ids, mask + + +def empty_cache() -> None: + """Empties the cache of the available torch device. + + This function checks for the availability of different torch devices (XPU, MLU, NPU, CUDA) + and empties the cache of the first available device it finds. + + If none of the specific devices are available, it defaults to emptying the CUDA cache. + """ + if is_torch_xpu_available(): + torch.xpu.empty_cache() + elif is_torch_mlu_available(): + torch.mlu.empty_cache() + elif is_torch_npu_available(): + torch.npu.empty_cache() + else: + torch.cuda.empty_cache() + + +def decode_and_strip_padding(inputs: torch.Tensor, tokenizer: PreTrainedTokenizerBase) -> List[str]: + """ + Decodes the input tensor and strips the padding tokens. + + Args: + inputs (`torch.Tensor`): + The input tensor to be decoded. + tokenizer (`transformers.PreTrainedTokenizerBase`): + The tokenizer used to decode the input tensor. + + Returns: + `List[str]`: + The list of decoded strings with padding tokens stripped. + """ + decoded = tokenizer.batch_decode(inputs, skip_special_tokens=False) + return [d.replace(tokenizer.pad_token, "") for d in decoded] + + +def generate_model_card( + base_model: Optional[str], + model_name: str, + hub_model_id: str, + dataset_name: Optional[str], + tags: List[str], + wandb_url: Optional[str], + trainer_name: str, + trainer_citation: Optional[str] = None, + paper_title: Optional[str] = None, + paper_id: Optional[str] = None, +) -> ModelCard: + """ + Generate a `ModelCard` from a template. + + Args: + base_model (`str` or `None`): + Base model name. + model_name (`str`): + Model name. + hub_model_id (`str`): + Hub model ID as `username/model_id`. + dataset_name (`str` or `None`): + Dataset name. + tags (`List[str]`): + Tags. + wandb_url (`str` or `None`): + Weights & Biases run URL. + trainer_name (`str`): + Trainer name. + trainer_citation (`str` or `None`, defaults to `None`): + Trainer citation as a BibTeX entry. + paper_title (`str` or `None`, defaults to `None`): + Paper title. + paper_id (`str` or `None`, defaults to `None`): + ArXiv paper ID as `YYMM.NNNNN`. + + Returns: + `ModelCard`: + A ModelCard object. + """ + card_data = ModelCardData( + base_model=base_model, + datasets=dataset_name, + library_name="transformers", + licence="license", + model_name=model_name, + tags=["generated_from_trainer", *tags], + ) + card = ModelCard.from_template( + card_data, + template_path=str(pkg_resources.files("trl").joinpath("templates/lm_model_card.md")), + base_model=base_model, + model_name=model_name, + hub_model_id=hub_model_id, + dataset_name=dataset_name, + wandb_url=wandb_url, + trainer_name=trainer_name, + trainer_citation=trainer_citation, + paper_title=paper_title, + paper_id=paper_id, + trl_version=version("trl"), + transformers_version=version("transformers"), + pytorch_version=version("torch"), + datasets_version=version("datasets"), + tokenizers_version=version("tokenizers"), + ) + return card diff --git a/testbed/huggingface__trl/trl/trainer/xpo_config.py b/testbed/huggingface__trl/trl/trainer/xpo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5a46def78cefaceb0719096414ac9b0a10c83e --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/xpo_config.py @@ -0,0 +1,38 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import List + +from trl.trainer.online_dpo_config import OnlineDPOConfig + + +@dataclass +class XPOConfig(OnlineDPOConfig): + r""" + Configuration class for the [`XPOTrainer`]. + + Subclass of [`OnlineDPOConfig`] we can use all its arguments and add the following: + + Parameters: + alpha (`float` or `List[float]`, *optional*, defaults to `1e-5`): + Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each new epoch and the last alpha is used for the rest of the epochs. + """ + + alpha: List[float] = field(default_factory=lambda: [1e-5]) + + def __post_init__(self): + super().__post_init__() + if hasattr(self.alpha, "__len__") and len(self.alpha) == 1: + self.alpha = self.alpha[0] diff --git a/testbed/huggingface__trl/trl/trainer/xpo_trainer.py b/testbed/huggingface__trl/trl/trainer/xpo_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec501c7f0e1ef75bcf2ca4694c24091338c7145 --- /dev/null +++ b/testbed/huggingface__trl/trl/trainer/xpo_trainer.py @@ -0,0 +1,564 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import textwrap +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import jinja2 +import torch +import torch.nn as nn +import torch.nn.functional as F +from datasets import Dataset, IterableDataset +from transformers import ( + BaseImageProcessor, + FeatureExtractionMixin, + PreTrainedModel, + PreTrainedTokenizerBase, + ProcessorMixin, + TrainerCallback, + is_apex_available, + is_wandb_available, +) +from transformers.trainer_utils import EvalPrediction +from transformers.training_args import OptimizerNames + +from ..data_utils import is_conversational, maybe_apply_chat_template +from ..models.utils import unwrap_model_for_generation +from .judges import BasePairwiseJudge +from .online_dpo_trainer import OnlineDPOTrainer +from .utils import SIMPLE_CHAT_TEMPLATE, empty_cache, generate_model_card, get_reward, truncate_right +from .xpo_config import XPOConfig + + +if is_apex_available(): + from apex import amp + + +if is_wandb_available(): + import wandb + + +class XPOTrainer(OnlineDPOTrainer): + r""" + Initialize XPOTrainer as a subclass of [`OnlineDPOConfig`]. + + Args: + model (`transformers.PreTrainedModel`): + The model to train, preferably an `AutoModelForCausalLM`. + ref_model (`PreTrainedModelWrapper`): + Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no + reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. + reward_model (`transformers.PreTrainedModel`): + The reward model to score completions with, preferably an `AutoModelForSequenceClassification`. + judge (`BasePairwiseJudge`): + The judge to use for pairwise comparison of model completions. + args (`XPOConfig`): + The XPO config arguments to use for training. + data_collator (`transformers.DataCollator`): + The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used + which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. + train_dataset (`datasets.Dataset`): + The dataset to use for training. + eval_dataset (`datasets.Dataset`): + The dataset to use for evaluation. + processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): + Processing class used to process the data. If provided, will be used to automatically process the inputs + for the model, and it will be saved along the model to make it easier to rerun an interrupted training or + reuse the fine-tuned model. + peft_config (`Dict`): + The peft config to use for training. + compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): + The function to use to compute the metrics. Must take a `EvalPrediction` and return + a dictionary string to metric values. + callbacks (`List[transformers.TrainerCallback]`): + The callbacks to use for training. + optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): + The optimizer and scheduler to use for training. + preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): + The function to use to preprocess the logits before computing the metrics. + """ + + _tag_names = ["trl", "xpo"] + + def __init__( + self, + model: Union[PreTrainedModel, nn.Module] = None, + ref_model: Union[PreTrainedModel, nn.Module] = None, + reward_model: Optional[nn.Module] = None, + judge: Optional[BasePairwiseJudge] = None, + args: Optional[XPOConfig] = None, + data_collator: Optional[Callable] = None, + train_dataset: Optional[Union[Dataset, IterableDataset]] = None, + eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, + processing_class: Optional[ + Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] + ] = None, + peft_config: Optional[Dict] = None, + compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, + callbacks: Optional[List[TrainerCallback]] = None, + optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), + preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, + ) -> None: + super().__init__( + model=model, + ref_model=ref_model, + judge=judge, + reward_model=reward_model, + args=args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + processing_class=processing_class, + reward_processing_class=processing_class, # for now, XPOTrainer can't use any reward model + peft_config=peft_config, + compute_metrics=compute_metrics, + callbacks=callbacks, + optimizers=optimizers, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + self._alpha = self.args.alpha + + # Overwrite the stats dictionary to include XPO specific statistics + self.stats = { + # Remove "non_score_reward", "rlhf_reward", "scores" + # Add "loss/dpo", "loss/xpo" + "loss/dpo": [], + "loss/xpo": [], + "objective/kl": [], + "objective/entropy": [], + "rewards/chosen": [], + "rewards/rejected": [], + "rewards/accuracies": [], + "rewards/margins": [], + "logps/chosen": [], + "logps/rejected": [], + # Replace "contain_eos_token" by "model_contain_eos_token" and "ref_contain_eos_token" + "val/model_contain_eos_token": [], + "val/ref_contain_eos_token": [], + "alpha": [], + "beta": [], + } + if self.reward_model is not None: + # Replace "scores" by "model_scores" and "ref_scores" + self.stats["objective/model_scores"] = [] + self.stats["objective/ref_scores"] = [] + self.stats["objective/scores_margin"] = [] + + @property + def alpha(self): + if isinstance(self._alpha, list): + epoch = self.state.epoch + return self._alpha[epoch] if epoch < len(self._alpha) else self._alpha[-1] + else: + return self._alpha + + def _generate_completions(self, prompts, model): + with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model: + model_output = unwrapped_model.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + ref_model = model if self.ref_model is None else self.ref_model + with torch.no_grad(), unwrap_model_for_generation(ref_model, self.accelerator) as unwrapped_ref_model: + ref_output = unwrapped_ref_model.generate( + input_ids=prompts["input_ids"], + attention_mask=prompts["attention_mask"], + generation_config=self.generation_config, + ) + + return model_output, ref_output + + def _process_completions(self, model_output, ref_output, prompts): + context_length = prompts["input_ids"].shape[1] + + # Process model completions + model_completion_ids = model_output[:, context_length:] + model_completion_ids, model_completion_mask = truncate_right( + model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + model_data = { + "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), + "raw": prompts["raw"], + } + + # Process reference model completions + ref_completion_ids = ref_output[:, context_length:] + ref_completion_ids, ref_completion_mask = truncate_right( + ref_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id + ) + ref_data = { + "input_ids": torch.cat((prompts["input_ids"], ref_completion_ids), dim=1), + "attention_mask": torch.cat((prompts["attention_mask"], ref_completion_mask), dim=1), + "raw": prompts["raw"], + } + + return model_data, ref_data + + def _compute_rewards(self, model_data, ref_data, context_length): + with torch.no_grad(): + _, model_scores, _ = get_reward( + self.reward_model, model_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + _, ref_scores, _ = get_reward( + self.reward_model, ref_data["input_ids"], self.processing_class.pad_token_id, context_length + ) + + # Apply EOS penalty if needed + if self.args.missing_eos_penalty is not None: + model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + ref_contain_eos = torch.any(ref_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) + model_scores[~model_contain_eos] -= self.args.missing_eos_penalty + ref_scores[~ref_contain_eos] -= self.args.missing_eos_penalty + + return model_scores, ref_scores + + def _compute_judge(self, model_data, ref_data, context_length): + prompts = model_data["raw"] + model_data_completions = self.processing_class.batch_decode( + model_data["input_ids"][:, context_length:], skip_special_tokens=True + ) + model_data_completions = [completion.strip() for completion in model_data_completions] + + ref_data_completions = self.processing_class.batch_decode( + ref_data["input_ids"][:, context_length:], skip_special_tokens=True + ) + ref_data_completions = [completion.strip() for completion in ref_data_completions] + + if is_conversational({"prompt": prompts[0]}): + model_data_completions = [ + [{"role": "assistant", "content": completion}] for completion in model_data_completions + ] + environment = jinja2.Environment() + template = environment.from_string(SIMPLE_CHAT_TEMPLATE) + prompts = [template.render(messages=message) for message in prompts] + model_data_completions = [template.render(messages=completion) for completion in model_data_completions] + + ref_data_completions = [ + [{"role": "assistant", "content": completion}] for completion in ref_data_completions + ] + ref_data_completions = [template.render(messages=completion) for completion in ref_data_completions] + + ranks_of_first_completion = self.judge.judge( + prompts, + list(zip(model_data_completions, ref_data_completions)), + ) + # convert ranks to a True/False mask: + # when rank == 0, it means the first completion is the best + # when rank == 1, it means the second completion is the best + return torch.tensor([rank == 0 for rank in ranks_of_first_completion], device=model_data["input_ids"].device) + + def _compute_logprobs(self, model, model_data, ref_data, context_length): + def compute_logprobs_for_data(m, data): + output = m(data["input_ids"], attention_mask=data["attention_mask"]) + logits = output.logits[:, context_length - 1 : -1] + logprobs = F.log_softmax(logits, dim=-1) + token_logprobs = torch.gather(logprobs, 2, data["input_ids"][:, context_length:].unsqueeze(-1)).squeeze(-1) + return token_logprobs + + # Compute logprobs for model completions + model_logprobs_model_data = compute_logprobs_for_data(model, model_data) + # Compute logprobs for model on reference completions (for XPO loss) + model_logprobs_ref_data = compute_logprobs_for_data(model, ref_data) + + # Compute logprobs for reference model completions + with torch.no_grad(): + if self.ref_model is None: + with model.disable_adapter(): + ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) + ref_logprobs_ref_data = compute_logprobs_for_data(model, ref_data) + else: + ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) + ref_logprobs_ref_data = compute_logprobs_for_data(self.ref_model, ref_data) + + # Mask padding tokens + model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 + ref_padding_mask = ref_data["attention_mask"][:, context_length:] == 0 + model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + model_logprobs_ref_data = model_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0) + ref_logprobs_ref_data = ref_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0) + ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) + + return model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data + + def _compute_losses( + self, + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + ): + # Compute log probs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1) + ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs + + rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs + + # Compute logits as the difference between chosen and rejected log ratios + logits = chosen_log_ratios - rejected_log_ratios + + if self.args.loss_type == "sigmoid": + dpo_losses = -F.logsigmoid(self.beta * logits) + elif self.args.loss_type == "ipo": + dpo_losses = (logits - 1 / (2 * self.beta)) ** 2 + else: + raise NotImplementedError(f"invalid loss type {self.args.loss_type}") + + # Compute XPO specific loss + xpo_losses = self.alpha * model_logprobs_ref_data_sum + + # Total loss + loss = (dpo_losses + xpo_losses).mean() + + return loss, dpo_losses, xpo_losses + + def _log_statistics( + self, + model_data, + ref_data, + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + dpo_losses, + xpo_losses, + context_length, + model_scores=None, + ref_scores=None, + ): + # Helper function to gather and compute mean + def gather_mean(tensor): + return self.accelerator.gather(tensor).mean().item() + + # Log losses + self.stats["loss/dpo"].append(gather_mean(dpo_losses)) + self.stats["loss/xpo"].append(gather_mean(xpo_losses)) + + # Log scores + if self.reward_model is not None: + self.stats["objective/model_scores"].append(gather_mean(model_scores)) + self.stats["objective/ref_scores"].append(gather_mean(ref_scores)) + self.stats["objective/scores_margin"].append(gather_mean(model_scores - ref_scores)) + + # Log logprobs + model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) + model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1) + ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1) + ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) + + chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs + + rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum) + rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum) + rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs + + self.stats["logps/chosen"].append(gather_mean(chosen_model_logprobs.mean() + chosen_ref_logprobs.mean())) + self.stats["logps/rejected"].append(gather_mean(rejected_model_logprobs.mean() + rejected_ref_logprobs.mean())) + + # Log rewards + # Compute various statistics + chosen_rewards = chosen_log_ratios * self.beta + rejected_rewards = rejected_log_ratios * self.beta + self.stats["rewards/chosen"].append(gather_mean(chosen_rewards.mean())) + self.stats["rewards/rejected"].append(gather_mean(rejected_rewards.mean())) + + # Calculate KL divergence for model and ref data + kl_model_data = model_logprobs_model_data - ref_logprobs_model_data + kl_ref_data = model_logprobs_ref_data - ref_logprobs_ref_data + mean_kl = (kl_model_data.sum(1) + kl_ref_data.sum(1)).mean() / 2 + self.stats["objective/kl"].append(gather_mean(mean_kl)) + + # Calculate entropy for model and ref data + entropy_model_data = -model_logprobs_model_data.sum(1) + entropy_ref_data = -model_logprobs_ref_data.sum(1) + mean_entropy = (entropy_model_data.mean() + entropy_ref_data.mean()) / 2 + self.stats["objective/entropy"].append(gather_mean(mean_entropy)) + + # Calculate margins + margin = chosen_rewards - rejected_rewards + self.stats["rewards/margins"].append(gather_mean(margin.mean())) + + # Calculate accuracy + accuracy = (margin > 0).float() + self.stats["rewards/accuracies"].append(gather_mean(accuracy.mean())) + + # Log EOS token statistics + model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + ref_eos = (ref_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) + self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) + self.stats["val/ref_contain_eos_token"].append(gather_mean(ref_eos.float())) + + # Log alpha and beta + self.stats["alpha"].append(self.alpha) + self.stats["beta"].append(self.beta) + + def training_step( + self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None + ) -> torch.Tensor: + model.train() + + # Apply chat template and tokenize the input + batch_size = len(next(iter(inputs.values()))) + prompts = inputs["prompt"] + inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] + inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] + inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] + inputs = self.data_collator(inputs) + + # need the prompt_ only + inputs = self._prepare_inputs(inputs) + context_length = inputs["prompt_input_ids"].shape[1] + prompts = { + "input_ids": inputs["prompt_input_ids"], + "attention_mask": inputs["prompt_attention_mask"], + "raw": prompts, + } + del inputs + + # Sample completions from both the model and the reference model + model_output, ref_output = self._generate_completions(prompts, model) + + # Process model completions + model_data, ref_data = self._process_completions(model_output, ref_output, prompts) + + # Compute rewards + if self.reward_model is not None: + model_scores, ref_scores = self._compute_rewards(model_data, ref_data, context_length) + chosen_mask = model_scores >= ref_scores + else: + model_scores, ref_scores = None, None + chosen_mask = self._compute_judge(model_data, ref_data, context_length) + + # Compute logprobs + model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data = ( + self._compute_logprobs(model, model_data, ref_data, context_length) + ) + + # Compute loss + loss, dpo_losses, xpo_losses = self._compute_losses( + model_logprobs_model_data, + model_logprobs_ref_data, + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + ) + + # Log everything + self._log_statistics( + model_data, + ref_data, + model_logprobs_model_data.detach(), + model_logprobs_ref_data.detach(), + ref_logprobs_ref_data, + ref_logprobs_model_data, + chosen_mask, + dpo_losses.detach(), + xpo_losses.detach(), + context_length, + model_scores, + ref_scores, + ) + + if ( + self.args.torch_empty_cache_steps is not None + and self.state.global_step % self.args.torch_empty_cache_steps == 0 + ): + empty_cache() + + kwargs = {} + # For LOMO optimizers you need to explicitly use the learning rate + if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: + kwargs["learning_rate"] = self._get_learning_rate() + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + if self.use_apex: + with amp.scale_loss(loss, self.optimizer) as scaled_loss: + scaled_loss.backward() + else: + self.accelerator.backward(loss, **kwargs) + + return loss.detach() / self.args.gradient_accumulation_steps + + def create_model_card( + self, + model_name: Optional[str] = None, + dataset_name: Optional[str] = None, + tags: Union[str, List[str], None] = None, + ): + """ + Creates a draft of a model card using the information available to the `Trainer`. + + Args: + model_name (`str`, *optional*, defaults to `None`): + The name of the model. + dataset_name (`str`, *optional*, defaults to `None`): + The name of the dataset used for training. + tags (`str`, `List[str]` or `None`, *optional*, defaults to `None`): + Tags to be associated with the model card. + """ + if not self.is_world_process_zero(): + return + + if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): + base_model = self.model.config._name_or_path + else: + base_model = None + + tags = tags or [] + if isinstance(tags, str): + tags = [tags] + + if hasattr(self.model.config, "unsloth_version"): + tags.append("unsloth") + + citation = textwrap.dedent("""\ + @article{jung2024binary, + title = {{Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF}}, + author = {Tengyang Xie and Dylan J. Foster and Akshay Krishnamurthy and Corby Rosset and Ahmed Awadallah and Alexander Rakhlin}, + year = 2024, + eprint = {arXiv:2405.21046} + }""") + + model_card = generate_model_card( + base_model=base_model, + model_name=model_name, + hub_model_id=self.hub_model_id, + dataset_name=dataset_name, + tags=tags, + wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, + trainer_name="XPO", + trainer_citation=citation, + paper_title="Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF", + paper_id="2405.21046", + ) + + model_card.save(os.path.join(self.args.output_dir, "README.md")) diff --git a/testbed/huggingface__trl/trl/utils.py b/testbed/huggingface__trl/trl/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2c20b516680473c9ecae65aafccb40c8a11490d3 --- /dev/null +++ b/testbed/huggingface__trl/trl/utils.py @@ -0,0 +1,44 @@ +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class ScriptArguments: + """ + Arguments common to all scripts. + + dataset_name (`str`): + Dataset name. + dataset_train_split (`str`, *optional*, defaults to `"train"`): + Dataset split to use for training. + dataset_test_split (`str`, *optional*, defaults to `"test"`): + Dataset split to use for evaluation. + config (`str` or `None`, *optional*, defaults to `None`): + Path to the optional config file. + gradient_checkpointing_use_reentrant (`bool`, *optional*, defaults to `False`): + Whether to apply `use_reentrant` for gradient_checkpointing. + ignore_bias_buffers (`bool`, *optional*, defaults to `False`): + Debug argument for distributed training. Fix for DDP issues with LM bias/mask buffers - invalid scalar type, + inplace operation. See https://github.com/huggingface/transformers/issues/22482#issuecomment-1595790992. + """ + + dataset_name: str + dataset_train_split: str = "train" + dataset_test_split: str = "test" + config: Optional[str] = None + gradient_checkpointing_use_reentrant: bool = False + ignore_bias_buffers: bool = False diff --git a/testbed/joblib__joblib/.codecov.yml b/testbed/joblib__joblib/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..196a6d6ffb30f093a17aa7e37124f2ee92ea6a45 --- /dev/null +++ b/testbed/joblib__joblib/.codecov.yml @@ -0,0 +1,9 @@ +codecov: + token: 1b7eb264-fd77-469a-829a-e9cd5efd7cef +coverage: + status: + project: + default: + # Allow coverage to drop by up to 1% in a PR before marking it as + # failed + threshold: '1%' diff --git a/testbed/joblib__joblib/.gitignore b/testbed/joblib__joblib/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3e6adc62e52ab539fbfd9289b04afc5f4d474335 --- /dev/null +++ b/testbed/joblib__joblib/.gitignore @@ -0,0 +1,55 @@ +*.py[oc] +*.so +# setup.py working directory +build +# setup.py dist directory +dist +# Editor temporary/working/backup files +*$ +.*.sw[nop] +.sw[nop] +*~ +[#]*# +.#* +*.bak +*.tmp +*.tgz +*.rej +*.org +.project +*.diff +.settings/ +*.svn/ +# Egg metadata +*.egg-info +# The shelf plugin uses this dir +./.shelf +# Some IDEs add this directory +.idea +.vscode + +# Mac droppings +.DS_Store +doc/documentation.zip +doc/generated +doc/CHANGES.rst +doc/README.rst +# Coverage report +.coverage + +# pytest cache on failure +.cache +.pytest_cache + +# Generated ctags +tags + +# Generated by sphinx +doc/auto_examples/ +doc/_build + +# Dask worker space directory in generated examples +dask-worker-space/ + +# Binary files created by benchmarks +*.npy diff --git a/testbed/joblib__joblib/.mailmap b/testbed/joblib__joblib/.mailmap new file mode 100644 index 0000000000000000000000000000000000000000..c234be0354119d27f82e5a8305f08a40f77aa6d4 --- /dev/null +++ b/testbed/joblib__joblib/.mailmap @@ -0,0 +1,6 @@ +Gael Varoquaux Gael Varoquaux +Gael Varoquaux Gael varoquaux +Gael Varoquaux GaelVaroquaux +Gael Varoquaux Gael VAROQUAUX +Gael Varoquaux gvaroquaux + diff --git a/testbed/joblib__joblib/.readthedocs-requirements.txt b/testbed/joblib__joblib/.readthedocs-requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..07fa6e4c3fbf9b9b5c1ba6b5d4a8b27d6b69b29f --- /dev/null +++ b/testbed/joblib__joblib/.readthedocs-requirements.txt @@ -0,0 +1,11 @@ +sphinx +docutils<0.18 +numpy +matplotlib +pillow +sphinx-gallery +numpydoc +pandas +lz4 +distributed +psutil diff --git a/testbed/joblib__joblib/.readthedocs.yaml b/testbed/joblib__joblib/.readthedocs.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d14bb8f9b7c7584fad6acd8851710d27fd936b5a --- /dev/null +++ b/testbed/joblib__joblib/.readthedocs.yaml @@ -0,0 +1,19 @@ +version: 2 + +# Set the version of Python and OS +build: + os: ubuntu-22.04 + tools: + python: "3.11" + +python: + # make sure joblib is installed in the virtualenv (it is imported in + # conf.py) + install: + - requirements: .readthedocs-requirements.txt + - method: pip + path: . + +sphinx: + fail_on_warning: true + diff --git a/testbed/joblib__joblib/CHANGES.rst b/testbed/joblib__joblib/CHANGES.rst new file mode 100644 index 0000000000000000000000000000000000000000..5bf9c956eda9e3684a7e5cfef36a3399cd206a1f --- /dev/null +++ b/testbed/joblib__joblib/CHANGES.rst @@ -0,0 +1,1429 @@ +Latest changes +============== + +In development +-------------- + +- Try to cast ``n_jobs`` to int in parallel and raise an error if + it fails. This means that ``n_jobs=2.3`` will now result in + ``effective_n_jobs=2`` instead of failing. + https://github.com/joblib/joblib/pull/1539 + +- Ensure that errors in the task generator given to Parallel's call + are raised in the results consumming thread. + https://github.com/joblib/joblib/pull/1491 + +- Adjust codebase to NumPy 2.0 by changing ``np.NaN`` to ``np.nan`` + and importing ``byte_bounds`` from ``np.lib.array_utils``. + https://github.com/joblib/joblib/pull/1501 + +- The parameter ``return_as`` in ``joblib.Parallel`` can now be set to + ``generator_unordered``. In this case the results will be returned in the + order of task completion rather than the order of submission. + https://github.com/joblib/joblib/pull/1463 + +- dask backend now supports ``return_as=generator`` and + ``return_as=generator_unordered``. + https://github.com/joblib/joblib/pull/1520 + +- Vendor cloudpickle 3.0.0 and end support for Python 3.7 which has + reached end of life. + https://github.com/joblib/joblib/pull/1487 + https://github.com/joblib/joblib/pull/1515 + +Release 1.3.2 -- 2023/08/08 +--------------------------- + +- Fix a regression in ``joblib.Parallel`` introduced in 1.3.0 where + explicitly setting ``n_jobs=None`` was not interpreted as "unset". + https://github.com/joblib/joblib/pull/1475 + +- Fix a regression in ``joblib.Parallel`` introduced in 1.3.0 where + ``joblib.Parallel`` logging methods exposed from inheritance to + ``joblib.Logger`` didn't work because of missing logger + initialization. + https://github.com/joblib/joblib/pull/1494 + +- Various maintenance updates to the doc, the ci and the test. + https://github.com/joblib/joblib/pull/1480, + https://github.com/joblib/joblib/pull/1481, + https://github.com/joblib/joblib/pull/1476, + https://github.com/joblib/joblib/pull/1492 + +Release 1.3.1 -- 2023/06/29 +--------------------------- + +- Fix compatibility with python 3.7 by vendor loky 3.4.1 + which is compatible with this version. + https://github.com/joblib/joblib/pull/1472 + + +Release 1.3.0 -- 2023/06/28 +--------------------------- + +- Ensure native byte order for memmap arrays in ``joblib.load``. + https://github.com/joblib/joblib/issues/1353 + +- Add ability to change default Parallel backend in tests by setting the + ``JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND`` environment variable. + https://github.com/joblib/joblib/pull/1356 + +- Fix temporary folder creation in `joblib.Parallel` on Linux subsystems on Windows + which do have `/dev/shm` but don't have the `os.statvfs` function + https://github.com/joblib/joblib/issues/1353 + +- Drop runtime dependency on ``distutils``. ``distutils`` is going away + in Python 3.12 and is deprecated from Python 3.10 onwards. This import + was kept around to avoid breaking scikit-learn, however it's now been + long enough since scikit-learn deployed a fixed (verion 1.1 was released + in May 2022) that it should be safe to remove this. + https://github.com/joblib/joblib/pull/1361 + +- A warning is raised when a pickling error occurs during caching operations. + In version 1.5, this warning will be turned into an error. For all other + errors, a new warning has been introduced: ``joblib.memory.CacheWarning``. + https://github.com/joblib/joblib/pull/1359 + +- Avoid (module, name) collisions when caching nested functions. This fix + changes the module name of nested functions, invalidating caches from + previous versions of Joblib. + https://github.com/joblib/joblib/pull/1374 + +- Add ``cache_validation_callback`` in :meth:`joblib.Memory.cache`, to allow + custom cache invalidation based on the metadata of the function call. + https://github.com/joblib/joblib/pull/1149 + +- Add a ``return_as`` parameter for ``Parallel``, that enables consuming + results asynchronously. + https://github.com/joblib/joblib/pull/1393, + https://github.com/joblib/joblib/pull/1458 + +- Improve the behavior of ``joblib`` for ``n_jobs=1``, with simplified + tracebacks and more efficient running time. + https://github.com/joblib/joblib/pull/1393 + +- Add the ``parallel_config`` context manager to allow for more fine-grained + control over the backend configuration. It should be used in place of the + ``parallel_backend`` context manager. In particular, it has the advantage + of not requiring to set a specific backend in the context manager. + https://github.com/joblib/joblib/pull/1392, + https://github.com/joblib/joblib/pull/1457 + +- Add ``items_limit`` and ``age_limit`` in :meth:`joblib.Memory.reduce_size` + to make it easy to limit the number of items and remove items that have + not been accessed for a long time in the cache. + https://github.com/joblib/joblib/pull/1200 + +- Deprecate ``bytes_limit`` in ``Memory`` as this is not automatically enforced, + the limit can be directly passed to :meth:`joblib.Memory.reduce_size` which + needs to be called to actually enforce the limit. + https://github.com/joblib/joblib/pull/1447 + +- Vendor ``loky`` 3.4.0 which includes various fixes. + https://github.com/joblib/joblib/pull/1422 + +- Various updates to the documentation and to benchmarking tools. + https://github.com/joblib/joblib/pull/1343, + https://github.com/joblib/joblib/pull/1348, + https://github.com/joblib/joblib/pull/1411, + https://github.com/joblib/joblib/pull/1451, + https://github.com/joblib/joblib/pull/1427, + https://github.com/joblib/joblib/pull/1400 + +- Move project metadata to ``pyproject.toml``. + https://github.com/joblib/joblib/pull/1382, + https://github.com/joblib/joblib/pull/1433 + +- Add more tests to improve python ``nogil`` support. + https://github.com/joblib/joblib/pull/1394, + https://github.com/joblib/joblib/pull/1395 + + +Release 1.2.0 +------------- + +- Fix a security issue where ``eval(pre_dispatch)`` could potentially run + arbitrary code. Now only basic numerics are supported. + https://github.com/joblib/joblib/pull/1327 + +- Make sure that joblib works even when multiprocessing is not available, + for instance with Pyodide + https://github.com/joblib/joblib/pull/1256 + +- Avoid unnecessary warnings when workers and main process delete + the temporary memmap folder contents concurrently. + https://github.com/joblib/joblib/pull/1263 + +- Fix memory alignment bug for pickles containing numpy arrays. + This is especially important when loading the pickle with + ``mmap_mode != None`` as the resulting ``numpy.memmap`` object + would not be able to correct the misalignment without performing + a memory copy. + This bug would cause invalid computation and segmentation faults + with native code that would directly access the underlying data + buffer of a numpy array, for instance C/C++/Cython code compiled + with older GCC versions or some old OpenBLAS written in platform + specific assembly. + https://github.com/joblib/joblib/pull/1254 + +- Vendor cloudpickle 2.2.0 which adds support for PyPy 3.8+. + +- Vendor loky 3.3.0 which fixes several bugs including: + + - robustly forcibly terminating worker processes in case of a crash + (https://github.com/joblib/joblib/pull/1269); + + - avoiding leaking worker processes in case of nested loky parallel + calls; + + - reliability spawn the correct number of reusable workers. + +Release 1.1.1 +------------- + +- Fix a security issue where ``eval(pre_dispatch)`` could potentially run + arbitrary code. Now only basic numerics are supported. + https://github.com/joblib/joblib/pull/1327 + +Release 1.1.0 +-------------- + +- Fix byte order inconsistency issue during deserialization using joblib.load + in cross-endian environment: the numpy arrays are now always loaded to + use the system byte order, independently of the byte order of the system + that serialized the pickle. + https://github.com/joblib/joblib/pull/1181 + +- Fix joblib.Memory bug with the ``ignore`` parameter when the cached function + is a decorated function. + https://github.com/joblib/joblib/pull/1165 + +- Fix `joblib.Memory` to properly handle caching for functions defined + interactively in a IPython session or in Jupyter notebook cell. + https://github.com/joblib/joblib/pull/1214 + +- Update vendored loky (from version 2.9 to 3.0) and cloudpickle (from + version 1.6 to 2.0) + https://github.com/joblib/joblib/pull/1218 + +Release 1.0.1 +------------- + +- Add check_call_in_cache method to check cache without calling function. + https://github.com/joblib/joblib/pull/820 + +- dask: avoid redundant scattering of large arguments to make a more + efficient use of the network resources and avoid crashing dask with + "OSError: [Errno 55] No buffer space available" + or "ConnectionResetError: [Errno 104] connection reset by peer". + https://github.com/joblib/joblib/pull/1133 + +Release 1.0.0 +------------- + +- Make `joblib.hash` and `joblib.Memory` caching system compatible with `numpy + >= 1.20.0`. Also make it explicit in the documentation that users should now + expect to have their `joblib.Memory` cache invalidated when either `joblib` + or a third party library involved in the cached values definition is + upgraded. In particular, users updating `joblib` to a release that includes + this fix will see their previous cache invalidated if they contained + reference to `numpy` objects. + https://github.com/joblib/joblib/pull/1136 + +- Remove deprecated `check_pickle` argument in `delayed`. + https://github.com/joblib/joblib/pull/903 + +Release 0.17.0 +-------------- + +- Fix a spurious invalidation of `Memory.cache`'d functions called with + `Parallel` under Jupyter or IPython. + https://github.com/joblib/joblib/pull/1093 + +- Bump vendored loky to 2.9.0 and cloudpickle to 1.6.0. In particular + this fixes a problem to add compat for Python 3.9. + +Release 0.16.0 +-------------- + +- Fix a problem in the constructors of Parallel backends classes that + inherit from the `AutoBatchingMixin` that prevented the dask backend to + properly batch short tasks. + https://github.com/joblib/joblib/pull/1062 + +- Fix a problem in the way the joblib dask backend batches calls that would + badly interact with the dask callable pickling cache and lead to wrong + results or errors. + https://github.com/joblib/joblib/pull/1055 + +- Prevent a dask.distributed bug from surfacing in joblib's dask backend + during nested Parallel calls (due to joblib's auto-scattering feature) + https://github.com/joblib/joblib/pull/1061 + +- Workaround for a race condition after Parallel calls with the dask backend + that would cause low level warnings from asyncio coroutines: + https://github.com/joblib/joblib/pull/1078 + +Release 0.15.1 +-------------- + +- Make joblib work on Python 3 installation that do not ship with the lzma + package in their standard library. + +Release 0.15.0 +-------------- + +- Drop support for Python 2 and Python 3.5. All objects in + ``joblib.my_exceptions`` and ``joblib.format_stack`` are now deprecated and + will be removed in joblib 0.16. Note that no deprecation warning will be + raised for these objects Python < 3.7. + https://github.com/joblib/joblib/pull/1018 + +- Fix many bugs related to the temporary files and folder generated when + automatically memory mapping large numpy arrays for efficient inter-process + communication. In particular, this would cause `PermissionError` exceptions + to be raised under Windows and large leaked files in `/dev/shm` under Linux + in case of crash. + https://github.com/joblib/joblib/pull/966 + +- Make the dask backend collect results as soon as they complete + leading to a performance improvement: + https://github.com/joblib/joblib/pull/1025 + +- Fix the number of jobs reported by ``effective_n_jobs`` when ``n_jobs=None`` + called in a parallel backend context. + https://github.com/joblib/joblib/pull/985 + +- Upgraded vendored cloupickle to 1.4.1 and loky to 2.8.0. This allows for + Parallel calls of dynamically defined functions with type annotations + in particular. + + +Release 0.14.1 +-------------- + +- Configure the loky workers' environment to mitigate oversubsription with + nested multi-threaded code in the following case: + + - allow for a suitable number of threads for numba (``NUMBA_NUM_THREADS``); + + - enable Interprocess Communication for scheduler coordination when the + nested code uses Threading Building Blocks (TBB) (``ENABLE_IPC=1``) + + https://github.com/joblib/joblib/pull/951 + +- Fix a regression where the loky backend was not reusing previously + spawned workers. + https://github.com/joblib/joblib/pull/968 + +- Revert https://github.com/joblib/joblib/pull/847 to avoid using + `pkg_resources` that introduced a performance regression under Windows: + https://github.com/joblib/joblib/issues/965 + +Release 0.14.0 +-------------- + +- Improved the load balancing between workers to avoid stranglers caused by an + excessively large batch size when the task duration is varying significantly + (because of the combined use of ``joblib.Parallel`` and ``joblib.Memory`` + with a partially warmed cache for instance). + https://github.com/joblib/joblib/pull/899 + +- Add official support for Python 3.8: fixed protocol number in `Hasher` + and updated tests. + +- Fix a deadlock when using the dask backend (when scattering large numpy + arrays). + https://github.com/joblib/joblib/pull/914 + +- Warn users that they should never use `joblib.load` with files from + untrusted sources. Fix security related API change introduced in numpy + 1.6.3 that would prevent using joblib with recent numpy versions. + https://github.com/joblib/joblib/pull/879 + +- Upgrade to cloudpickle 1.1.1 that add supports for the upcoming + Python 3.8 release among other things. + https://github.com/joblib/joblib/pull/878 + +- Fix semaphore availability checker to avoid spawning resource trackers + on module import. + https://github.com/joblib/joblib/pull/893 + +- Fix the oversubscription protection to only protect against nested + `Parallel` calls. This allows `joblib` to be run in background threads. + https://github.com/joblib/joblib/pull/934 + +- Fix `ValueError` (negative dimensions) when pickling large numpy arrays on + Windows. + https://github.com/joblib/joblib/pull/920 + +- Upgrade to loky 2.6.0 that add supports for the setting environment variables + in child before loading any module. + https://github.com/joblib/joblib/pull/940 + +- Fix the oversubscription protection for native libraries using threadpools + (OpenBLAS, MKL, Blis and OpenMP runtimes). + The maximal number of threads is can now be set in children using the + ``inner_max_num_threads`` in ``parallel_backend``. It defaults to + ``cpu_count() // n_jobs``. + https://github.com/joblib/joblib/pull/940 + + +Release 0.13.2 +-------------- + +Pierre Glaser + + Upgrade to cloudpickle 0.8.0 + + Add a non-regression test related to joblib issues #836 and #833, reporting + that cloudpickle versions between 0.5.4 and 0.7 introduced a bug where + global variables changes in a parent process between two calls to + joblib.Parallel would not be propagated into the workers + + +Release 0.13.1 +-------------- + +Pierre Glaser + + Memory now accepts pathlib.Path objects as ``location`` parameter. + Also, a warning is raised if the returned backend is None while + ``location`` is not None. + +Olivier Grisel + + Make ``Parallel`` raise an informative ``RuntimeError`` when the + active parallel backend has zero worker. + + Make the ``DaskDistributedBackend`` wait for workers before trying to + schedule work. This is useful in particular when the workers are + provisionned dynamically but provisionning is not immediate (for + instance using Kubernetes, Yarn or an HPC job queue). + + +Release 0.13.0 +-------------- + +Thomas Moreau + + Include loky 2.4.2 with default serialization with ``cloudpickle``. + This can be tweaked with the environment variable ``LOKY_PICKLER``. + +Thomas Moreau + + Fix nested backend in SequentialBackend to avoid changing the default + backend to Sequential. (#792) + +Thomas Moreau, Olivier Grisel + + Fix nested_backend behavior to avoid setting the default number of + workers to -1 when the backend is not dask. (#784) + +Release 0.12.5 +-------------- + +Thomas Moreau, Olivier Grisel + + Include loky 2.3.1 with better error reporting when a worker is + abruptly terminated. Also fixes spurious debug output. + + +Pierre Glaser + + Include cloudpickle 0.5.6. Fix a bug with the handling of global + variables by locally defined functions. + + +Release 0.12.4 +-------------- + +Thomas Moreau, Pierre Glaser, Olivier Grisel + + Include loky 2.3.0 with many bugfixes, notably w.r.t. when setting + non-default multiprocessing contexts. Also include improvement on + memory management of long running worker processes and fixed issues + when using the loky backend under PyPy. + + +Maxime Weyl + + Raises a more explicit exception when a corrupted MemorizedResult is loaded. + +Maxime Weyl + + Loading a corrupted cached file with mmap mode enabled would + recompute the results and return them without memory mapping. + + +Release 0.12.3 +-------------- + +Thomas Moreau + + Fix joblib import setting the global start_method for multiprocessing. + +Alexandre Abadie + + Fix MemorizedResult not picklable (#747). + +Loïc Estève + + Fix Memory, MemorizedFunc and MemorizedResult round-trip pickling + + unpickling (#746). + +James Collins + + Fixed a regression in Memory when positional arguments are called as + kwargs several times with different values (#751). + +Thomas Moreau and Olivier Grisel + + Integration of loky 2.2.2 that fixes issues with the selection of the + default start method and improve the reporting when calling functions + with arguments that raise an exception when unpickling. + + +Maxime Weyl + + Prevent MemorizedFunc.call_and_shelve from loading cached results to + RAM when not necessary. Results in big performance improvements + + +Release 0.12.2 +-------------- + +Olivier Grisel + + Integrate loky 2.2.0 to fix regression with unpicklable arguments and + functions reported by users (#723, #643). + + Loky 2.2.0 also provides a protection against memory leaks long running + applications when psutil is installed (reported as #721). + + Joblib now includes the code for the dask backend which has been updated + to properly handle nested parallelism and data scattering at the same + time (#722). + +Alexandre Abadie and Olivier Grisel + + Restored some private API attribute and arguments + (`MemorizedResult.argument_hash` and `BatchedCalls.__init__`'s + `pickle_cache`) for backward compat. (#716, #732). + + +Joris Van den Bossche + + Fix a deprecation warning message (for `Memory`'s `cachedir`) (#720). + + +Release 0.12.1 +-------------- + +Thomas Moreau + + Make sure that any exception triggered when serializing jobs in the queue + will be wrapped as a PicklingError as in past versions of joblib. + +Noam Hershtig + + Fix kwonlydefaults key error in filter_args (#715) + + +Release 0.12 +------------ + +Thomas Moreau + + Implement the ``'loky'`` backend with @ogrisel. This backend relies on + a robust implementation of ``concurrent.futures.ProcessPoolExecutor`` + with spawned processes that can be reused across the ``Parallel`` + calls. This fixes the bad integration with third paty libraries relying on + thread pools, described in https://pythonhosted.org/joblib/parallel.html#bad-interaction-of-multiprocessing-and-third-party-libraries + + Limit the number of threads used in worker processes by C-libraries that + relies on threadpools. This functionality works for MKL, OpenBLAS, OpenMP + and Accelerated. + +Elizabeth Sander + + Prevent numpy arrays with the same shape and data from hashing to + the same memmap, to prevent jobs with preallocated arrays from + writing over each other. + +Olivier Grisel + + Reduce overhead of automatic memmap by removing the need to hash the + array. + + Make ``Memory.cache`` robust to ``PermissionError (errno 13)`` under + Windows when run in combination with ``Parallel``. + + The automatic array memory mapping feature of ``Parallel`` does no longer + use ``/dev/shm`` if it is too small (less than 2 GB). In particular in + docker containers ``/dev/shm`` is only 64 MB by default which would cause + frequent failures when running joblib in Docker containers. + + Make it possible to hint for thread-based parallelism with + ``prefer='threads'`` or enforce shared-memory semantics with + ``require='sharedmem'``. + + Rely on the built-in exception nesting system of Python 3 to preserve + traceback information when an exception is raised on a remote worker + process. This avoid verbose and redundant exception reports under + Python 3. + + Preserve exception type information when doing nested Parallel calls + instead of mapping the exception to the generic ``JoblibException`` type. + + +Alexandre Abadie + + Introduce the concept of 'store' and refactor the ``Memory`` internal + storage implementation to make it accept extra store backends for caching + results. ``backend`` and ``backend_options`` are the new options added to + ``Memory`` to specify and configure a store backend. + + Add the ``register_store_backend`` function to extend the store backend + used by default with Memory. This default store backend is named 'local' + and corresponds to the local filesystem. + + The store backend API is experimental and thus is subject to change in the + future without deprecation. + + The ``cachedir`` parameter of ``Memory`` is now marked as deprecated, use + ``location`` instead. + + Add support for LZ4 compression if ``lz4`` package is installed. + + Add ``register_compressor`` function for extending available compressors. + + Allow passing a string to ``compress`` parameter in ``dump`` function. This + string should correspond to the compressor used (e.g. zlib, gzip, lz4, + etc). The default compression level is used in this case. + +Matthew Rocklin + + Allow ``parallel_backend`` to be used globally instead of only as a context + manager. + Support lazy registration of external parallel backends + +Release 0.11 +------------ + +Alexandre Abadie + + Remove support for python 2.6 + +Alexandre Abadie + + Remove deprecated `format_signature`, `format_call` and `load_output` + functions from Memory API. + +Loïc Estève + + Add initial implementation of LRU cache cleaning. You can specify + the size limit of a ``Memory`` object via the ``bytes_limit`` + parameter and then need to clean explicitly the cache via the + ``Memory.reduce_size`` method. + +Olivier Grisel + + Make the multiprocessing backend work even when the name of the main + thread is not the Python default. Thanks to Roman Yurchak for the + suggestion. + +Karan Desai + + pytest is used to run the tests instead of nosetests. + ``python setup.py test`` or ``python setup.py nosetests`` do not work + anymore, run ``pytest joblib`` instead. + +Loïc Estève + + An instance of ``joblib.ParallelBackendBase`` can be passed into + the ``parallel`` argument in ``joblib.Parallel``. + + +Loïc Estève + + Fix handling of memmap objects with offsets greater than + mmap.ALLOCATIONGRANULARITY in ``joblib.Parallel``. See + https://github.com/joblib/joblib/issues/451 for more details. + +Loïc Estève + + Fix performance regression in ``joblib.Parallel`` with + n_jobs=1. See https://github.com/joblib/joblib/issues/483 for more + details. + +Loïc Estève + + Fix race condition when a function cached with + ``joblib.Memory.cache`` was used inside a ``joblib.Parallel``. See + https://github.com/joblib/joblib/issues/490 for more details. + +Release 0.10.3 +-------------- + +Loïc Estève + + Fix tests when multiprocessing is disabled via the + JOBLIB_MULTIPROCESSING environment variable. + +harishmk + + Remove warnings in nested Parallel objects when the inner Parallel + has n_jobs=1. See https://github.com/joblib/joblib/pull/406 for + more details. + +Release 0.10.2 +-------------- + +Loïc Estève + + FIX a bug in stack formatting when the error happens in a compiled + extension. See https://github.com/joblib/joblib/pull/382 for more + details. + +Vincent Latrouite + + FIX a bug in the constructor of BinaryZlibFile that would throw an + exception when passing unicode filename (Python 2 only). + See https://github.com/joblib/joblib/pull/384 for more details. + +Olivier Grisel + + Expose :class:`joblib.parallel.ParallelBackendBase` and + :class:`joblib.parallel.AutoBatchingMixin` in the public API to + make them officially re-usable by backend implementers. + + +Release 0.10.0 +-------------- + +Alexandre Abadie + + ENH: joblib.dump/load now accept file-like objects besides filenames. + https://github.com/joblib/joblib/pull/351 for more details. + +Niels Zeilemaker and Olivier Grisel + + Refactored joblib.Parallel to enable the registration of custom + computational backends. + https://github.com/joblib/joblib/pull/306 + Note the API to register custom backends is considered experimental + and subject to change without deprecation. + +Alexandre Abadie + + Joblib pickle format change: joblib.dump always create a single pickle file + and joblib.dump/joblib.save never do any memory copy when writing/reading + pickle files. Reading pickle files generated with joblib versions prior + to 0.10 will be supported for a limited amount of time, we advise to + regenerate them from scratch when convenient. + joblib.dump and joblib.load also support pickle files compressed using + various strategies: zlib, gzip, bz2, lzma and xz. Note that lzma and xz are + only available with python >= 3.3. + https://github.com/joblib/joblib/pull/260 for more details. + +Antony Lee + + ENH: joblib.dump/load now accept pathlib.Path objects as filenames. + https://github.com/joblib/joblib/pull/316 for more details. + +Olivier Grisel + + Workaround for "WindowsError: [Error 5] Access is denied" when trying to + terminate a multiprocessing pool under Windows: + https://github.com/joblib/joblib/issues/354 + + +Release 0.9.4 +------------- + +Olivier Grisel + + FIX a race condition that could cause a joblib.Parallel to hang + when collecting the result of a job that triggers an exception. + https://github.com/joblib/joblib/pull/296 + +Olivier Grisel + + FIX a bug that caused joblib.Parallel to wrongly reuse previously + memmapped arrays instead of creating new temporary files. + https://github.com/joblib/joblib/pull/294 for more details. + +Loïc Estève + + FIX for raising non inheritable exceptions in a Parallel call. See + https://github.com/joblib/joblib/issues/269 for more details. + +Alexandre Abadie + + FIX joblib.hash error with mixed types sets and dicts containing mixed + types keys when using Python 3. + see https://github.com/joblib/joblib/issues/254 + +Loïc Estève + + FIX joblib.dump/load for big numpy arrays with dtype=object. See + https://github.com/joblib/joblib/issues/220 for more details. + +Loïc Estève + + FIX joblib.Parallel hanging when used with an exhausted + iterator. See https://github.com/joblib/joblib/issues/292 for more + details. + +Release 0.9.3 +------------- + +Olivier Grisel + + Revert back to the ``fork`` start method (instead of + ``forkserver``) as the latter was found to cause crashes in + interactive Python sessions. + +Release 0.9.2 +------------- + +Loïc Estève + + Joblib hashing now uses the default pickle protocol (2 for Python + 2 and 3 for Python 3). This makes it very unlikely to get the same + hash for a given object under Python 2 and Python 3. + + In particular, for Python 3 users, this means that the output of + joblib.hash changes when switching from joblib 0.8.4 to 0.9.2 . We + strive to ensure that the output of joblib.hash does not change + needlessly in future versions of joblib but this is not officially + guaranteed. + +Loïc Estève + + Joblib pickles generated with Python 2 can not be loaded with + Python 3 and the same applies for joblib pickles generated with + Python 3 and loaded with Python 2. + + During the beta period 0.9.0b2 to 0.9.0b4, we experimented with + a joblib serialization that aimed to make pickles serialized with + Python 3 loadable under Python 2. Unfortunately this serialization + strategy proved to be too fragile as far as the long-term + maintenance was concerned (For example see + https://github.com/joblib/joblib/pull/243). That means that joblib + pickles generated with joblib 0.9.0bN can not be loaded under + joblib 0.9.2. Joblib beta testers, who are the only ones likely to + be affected by this, are advised to delete their joblib cache when + they upgrade from 0.9.0bN to 0.9.2. + +Arthur Mensch + + Fixed a bug with ``joblib.hash`` that used to return unstable values for + strings and numpy.dtype instances depending on interning states. + +Olivier Grisel + + Make joblib use the 'forkserver' start method by default under Python 3.4+ + to avoid causing crash with 3rd party libraries (such as Apple vecLib / + Accelerate or the GCC OpenMP runtime) that use an internal thread pool that + is not reinitialized when a ``fork`` system call happens. + +Olivier Grisel + + New context manager based API (``with`` block) to re-use + the same pool of workers across consecutive parallel calls. + +Vlad Niculae and Olivier Grisel + + Automated batching of fast tasks into longer running jobs to + hide multiprocessing dispatching overhead when possible. + +Olivier Grisel + + FIX make it possible to call ``joblib.load(filename, mmap_mode='r')`` + on pickled objects that include a mix of arrays of both + memory memmapable dtypes and object dtype. + + +Release 0.8.4 +------------- + +2014-11-20 +Olivier Grisel + + OPTIM use the C-optimized pickler under Python 3 + + This makes it possible to efficiently process parallel jobs that deal with + numerous Python objects such as large dictionaries. + + +Release 0.8.3 +------------- + +2014-08-19 +Olivier Grisel + + FIX disable memmapping for object arrays + +2014-08-07 +Lars Buitinck + + MAINT NumPy 1.10-safe version comparisons + + +2014-07-11 +Olivier Grisel + + FIX #146: Heisen test failure caused by thread-unsafe Python lists + + This fix uses a queue.Queue datastructure in the failing test. This + datastructure is thread-safe thanks to an internal Lock. This Lock instance + not picklable hence cause the picklability check of delayed to check fail. + + When using the threading backend, picklability is no longer required, hence + this PRs give the user the ability to disable it on a case by case basis. + + +Release 0.8.2 +------------- + +2014-06-30 +Olivier Grisel + + BUG: use mmap_mode='r' by default in Parallel and MemmappingPool + + The former default of mmap_mode='c' (copy-on-write) caused + problematic use of the paging file under Windows. + +2014-06-27 +Olivier Grisel + + BUG: fix usage of the /dev/shm folder under Linux + + +Release 0.8.1 +------------- + +2014-05-29 +Gael Varoquaux + + BUG: fix crash with high verbosity + + +Release 0.8.0 +------------- + +2014-05-14 +Olivier Grisel + + Fix a bug in exception reporting under Python 3 + +2014-05-10 +Olivier Grisel + + Fixed a potential segfault when passing non-contiguous memmap + instances. + +2014-04-22 +Gael Varoquaux + + ENH: Make memory robust to modification of source files while the + interpreter is running. Should lead to less spurious cache flushes + and recomputations. + + +2014-02-24 +Philippe Gervais + + New ``Memory.call_and_shelve`` API to handle memoized results by + reference instead of by value. + + +Release 0.8.0a3 +--------------- + +2014-01-10 +Olivier Grisel & Gael Varoquaux + + FIX #105: Race condition in task iterable consumption when + pre_dispatch != 'all' that could cause crash with error messages "Pools + seems closed" and "ValueError: generator already executing". + +2014-01-12 +Olivier Grisel + + FIX #72: joblib cannot persist "output_dir" keyword argument. + + +Release 0.8.0a2 +--------------- + +2013-12-23 +Olivier Grisel + + ENH: set default value of Parallel's max_nbytes to 100MB + + Motivation: avoid introducing disk latency on medium sized + parallel workload where memory usage is not an issue. + + FIX: properly handle the JOBLIB_MULTIPROCESSING env variable + + FIX: timeout test failures under windows + + +Release 0.8.0a +-------------- + +2013-12-19 +Olivier Grisel + + FIX: support the new Python 3.4 multiprocessing API + + +2013-12-05 +Olivier Grisel + + ENH: make Memory respect mmap_mode at first call too + + ENH: add a threading based backend to Parallel + + This is low overhead alternative backend to the default multiprocessing + backend that is suitable when calling compiled extensions that release + the GIL. + + +Author: Dan Stahlke +Date: 2013-11-08 + + FIX: use safe_repr to print arg vals in trace + + This fixes a problem in which extremely long (and slow) stack traces would + be produced when function parameters are large numpy arrays. + + +2013-09-10 +Olivier Grisel + + ENH: limit memory copy with Parallel by leveraging numpy.memmap when + possible + + +Release 0.7.1 +--------------- + +2013-07-25 +Gael Varoquaux + + MISC: capture meaningless argument (n_jobs=0) in Parallel + +2013-07-09 +Lars Buitinck + + ENH Handles tuples, sets and Python 3's dict_keys type the same as + lists. in pre_dispatch + +2013-05-23 +Martin Luessi + + ENH: fix function caching for IPython + +Release 0.7.0 +--------------- + +**This release drops support for Python 2.5 in favor of support for +Python 3.0** + +2013-02-13 +Gael Varoquaux + + BUG: fix nasty hash collisions + +2012-11-19 +Gael Varoquaux + + ENH: Parallel: Turn of pre-dispatch for already expanded lists + + +Gael Varoquaux +2012-11-19 + + ENH: detect recursive sub-process spawning, as when people do not + protect the __main__ in scripts under Windows, and raise a useful + error. + + +Gael Varoquaux +2012-11-16 + + ENH: Full python 3 support + +Release 0.6.5 +--------------- + +2012-09-15 +Yannick Schwartz + + BUG: make sure that sets and dictionaries give reproducible hashes + + +2012-07-18 +Marek Rudnicki + + BUG: make sure that object-dtype numpy array hash correctly + +2012-07-12 +GaelVaroquaux + + BUG: Bad default n_jobs for Parallel + +Release 0.6.4 +--------------- + +2012-05-07 +Vlad Niculae + + ENH: controlled randomness in tests and doctest fix + +2012-02-21 +GaelVaroquaux + + ENH: add verbosity in memory + +2012-02-21 +GaelVaroquaux + + BUG: non-reproducible hashing: order of kwargs + + The ordering of a dictionary is random. As a result the function hashing + was not reproducible. Pretty hard to test + +Release 0.6.3 +--------------- + +2012-02-14 +GaelVaroquaux + + BUG: fix joblib Memory pickling + +2012-02-11 +GaelVaroquaux + + BUG: fix hasher with Python 3 + +2012-02-09 +GaelVaroquaux + + API: filter_args: `*args, **kwargs -> args, kwargs` + +Release 0.6.2 +--------------- + +2012-02-06 +Gael Varoquaux + + BUG: make sure Memory pickles even if cachedir=None + +Release 0.6.1 +--------------- + +Bugfix release because of a merge error in release 0.6.0 + +Release 0.6.0 +--------------- + +**Beta 3** + +2012-01-11 +Gael Varoquaux + + BUG: ensure compatibility with old numpy + + DOC: update installation instructions + + BUG: file semantic to work under Windows + +2012-01-10 +Yaroslav Halchenko + + BUG: a fix toward 2.5 compatibility + +**Beta 2** + +2012-01-07 +Gael Varoquaux + + ENH: hash: bugware to be able to hash objects defined interactively + in IPython + +2012-01-07 +Gael Varoquaux + + ENH: Parallel: warn and not fail for nested loops + + ENH: Parallel: n_jobs=-2 now uses all CPUs but one + +2012-01-01 +Juan Manuel Caicedo Carvajal and Gael Varoquaux + + ENH: add verbosity levels in Parallel + +Release 0.5.7 +--------------- + +2011-12-28 +Gael varoquaux + + API: zipped -> compress + +2011-12-26 +Gael varoquaux + + ENH: Add a zipped option to Memory + + API: Memory no longer accepts save_npy + +2011-12-22 +Kenneth C. Arnold and Gael varoquaux + + BUG: fix numpy_pickle for array subclasses + +2011-12-21 +Gael varoquaux + + ENH: add zip-based pickling + +2011-12-19 +Fabian Pedregosa + + Py3k: compatibility fixes. + This makes run fine the tests test_disk and test_parallel + +Release 0.5.6 +--------------- + +2011-12-11 +Lars Buitinck + + ENH: Replace os.path.exists before makedirs with exception check + New disk.mkdirp will fail with other errnos than EEXIST. + +2011-12-10 +Bala Subrahmanyam Varanasi + + MISC: pep8 compliant + + +Release 0.5.5 +--------------- + +2011-19-10 +Fabian Pedregosa + + ENH: Make joblib installable under Python 3.X + +Release 0.5.4 +--------------- + +2011-09-29 +Jon Olav Vik + + BUG: Make mangling path to filename work on Windows + +2011-09-25 +Olivier Grisel + + FIX: doctest heisenfailure on execution time + +2011-08-24 +Ralf Gommers + + STY: PEP8 cleanup. + + +Release 0.5.3 +--------------- + +2011-06-25 +Gael varoquaux + + API: All the useful symbols in the __init__ + + +Release 0.5.2 +--------------- + +2011-06-25 +Gael varoquaux + + ENH: Add cpu_count + +2011-06-06 +Gael varoquaux + + ENH: Make sure memory hash in a reproducible way + + +Release 0.5.1 +--------------- + +2011-04-12 +Gael varoquaux + + TEST: Better testing of parallel and pre_dispatch + +Yaroslav Halchenko +2011-04-12 + + DOC: quick pass over docs -- trailing spaces/spelling + +Yaroslav Halchenko +2011-04-11 + + ENH: JOBLIB_MULTIPROCESSING env var to disable multiprocessing from the + environment + +Alexandre Gramfort +2011-04-08 + + ENH : adding log message to know how long it takes to load from disk the + cache + + +Release 0.5.0 +--------------- + +2011-04-01 +Gael varoquaux + + BUG: pickling MemoizeFunc does not store timestamp + +2011-03-31 +Nicolas Pinto + + TEST: expose hashing bug with cached method + +2011-03-26...2011-03-27 +Pietro Berkes + + BUG: fix error management in rm_subdirs + BUG: fix for race condition during tests in mem.clear() + +Gael varoquaux +2011-03-22...2011-03-26 + + TEST: Improve test coverage and robustness + +Gael varoquaux +2011-03-19 + + BUG: hashing functions with only \*var \**kwargs + +Gael varoquaux +2011-02-01... 2011-03-22 + + BUG: Many fixes to capture interprocess race condition when mem.cache + is used by several processes on the same cache. + +Fabian Pedregosa +2011-02-28 + + First work on Py3K compatibility + +Gael varoquaux +2011-02-27 + + ENH: pre_dispatch in parallel: lazy generation of jobs in parallel + for to avoid drowning memory. + +GaelVaroquaux +2011-02-24 + + ENH: Add the option of overloading the arguments of the mother + 'Memory' object in the cache method that is doing the decoration. + +Gael varoquaux +2010-11-21 + + ENH: Add a verbosity level for more verbosity + +Release 0.4.6 +---------------- + +Gael varoquaux +2010-11-15 + + ENH: Deal with interruption in parallel + +Gael varoquaux +2010-11-13 + + BUG: Exceptions raised by Parallel when n_job=1 are no longer captured. + +Gael varoquaux +2010-11-13 + + BUG: Capture wrong arguments properly (better error message) + + +Release 0.4.5 +---------------- + +Pietro Berkes +2010-09-04 + + BUG: Fix Windows peculiarities with path separators and file names + BUG: Fix more windows locking bugs + +Gael varoquaux +2010-09-03 + + ENH: Make sure that exceptions raised in Parallel also inherit from + the original exception class + ENH: Add a shadow set of exceptions + +Fabian Pedregosa +2010-09-01 + + ENH: Clean up the code for parallel. Thanks to Fabian Pedregosa for + the patch. + + +Release 0.4.4 +---------------- + +Gael varoquaux +2010-08-23 + + BUG: Fix Parallel on computers with only one CPU, for n_jobs=-1. + +Gael varoquaux +2010-08-02 + + BUG: Fix setup.py for extra setuptools args. + +Gael varoquaux +2010-07-29 + + MISC: Silence tests (and hopefully Yaroslav :P) + +Release 0.4.3 +---------------- + +Gael Varoquaux +2010-07-22 + + BUG: Fix hashing for function with a side effect modifying their input + argument. Thanks to Pietro Berkes for reporting the bug and proving the + patch. + +Release 0.4.2 +---------------- + +Gael Varoquaux +2010-07-16 + + BUG: Make sure that joblib still works with Python2.5. => release 0.4.2 + +Release 0.4.1 +---------------- diff --git a/testbed/joblib__joblib/LICENSE.txt b/testbed/joblib__joblib/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..910537bd33412dd9b70c4d07cedd41b519be7fb5 --- /dev/null +++ b/testbed/joblib__joblib/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2008-2021, The joblib developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/testbed/joblib__joblib/MANIFEST.in b/testbed/joblib__joblib/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..cdb084df4f6300fc1a85e70f7f16b76afdd9dcf3 --- /dev/null +++ b/testbed/joblib__joblib/MANIFEST.in @@ -0,0 +1,6 @@ +include *.txt *.py +recursive-include joblib *.rst *.py +graft doc +graft doc/_static +graft doc/_templates +global-exclude *~ *.swp diff --git a/testbed/joblib__joblib/Makefile b/testbed/joblib__joblib/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..29d3d79d8390bb903325d2e73d3963235a383bfb --- /dev/null +++ b/testbed/joblib__joblib/Makefile @@ -0,0 +1,20 @@ +.PHONY: all test test-no-multiprocessing test-doc doc doc-clean + +all: test + +test: + pytest joblib --timeout 30 -vl + +test-no-multiprocessing: + export JOBLIB_MULTIPROCESSING=0 && pytest joblib + +test-doc: + pytest $(shell find doc -name '*.rst' | sort) + +# generate html documentation using sphinx +doc: + make -C doc + +# clean documentation +doc-clean: + make -C doc clean diff --git a/testbed/joblib__joblib/README.rst b/testbed/joblib__joblib/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..975ae0f9f8c92396700ff89b1aa68a27c0fba428 --- /dev/null +++ b/testbed/joblib__joblib/README.rst @@ -0,0 +1,136 @@ +|PyPi| |Azure| |ReadTheDocs| |Codecov| + +.. |PyPi| image:: https://badge.fury.io/py/joblib.svg + :target: https://badge.fury.io/py/joblib + :alt: Joblib version + +.. |Azure| image:: https://dev.azure.com/joblib/joblib/_apis/build/status/joblib.joblib?branchName=master + :target: https://dev.azure.com/joblib/joblib/_build?definitionId=3&_a=summary&branchFilter=40 + :alt: Azure CI status + +.. |ReadTheDocs| image:: https://readthedocs.org/projects/joblib/badge/?version=latest + :target: https://joblib.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +.. |Codecov| image:: https://codecov.io/gh/joblib/joblib/branch/master/graph/badge.svg + :target: https://codecov.io/gh/joblib/joblib + :alt: Codecov coverage + + +The homepage of joblib with user documentation is located on: + +https://joblib.readthedocs.io + +Getting the latest code +======================= + +To get the latest code using git, simply type:: + + git clone https://github.com/joblib/joblib.git + +If you don't have git installed, you can download a zip +of the latest code: https://github.com/joblib/joblib/archive/refs/heads/master.zip + +Installing +========== + +You can use `pip` to install joblib:: + + pip install joblib + +from any directory or:: + + python setup.py install + +from the source directory. + +Dependencies +============ + +- Joblib has no mandatory dependencies besides Python (supported versions are + 3.8+). +- Joblib has an optional dependency on Numpy (at least version 1.6.1) for array + manipulation. +- Joblib includes its own vendored copy of + `loky `_ for process management. +- Joblib can efficiently dump and load numpy arrays but does not require numpy + to be installed. +- Joblib has an optional dependency on + `python-lz4 `_ as a faster alternative to + zlib and gzip for compressed serialization. +- Joblib has an optional dependency on psutil to mitigate memory leaks in + parallel worker processes. +- Some examples require external dependencies such as pandas. See the + instructions in the `Building the docs`_ section for details. + +Workflow to contribute +====================== + +To contribute to joblib, first create an account on `github +`_. Once this is done, fork the `joblib repository +`_ to have your own repository, +clone it using 'git clone' on the computers where you want to work. Make +your changes in your clone, push them to your github account, test them +on several computers, and when you are happy with them, send a pull +request to the main repository. + +Running the test suite +====================== + +To run the test suite, you need the pytest (version >= 3) and coverage modules. +Run the test suite using:: + + pytest joblib + +from the root of the project. + +Building the docs +================= + +To build the docs you need to have sphinx (>=1.4) and some dependencies +installed:: + + pip install -U -r .readthedocs-requirements.txt + +The docs can then be built with the following command:: + + make doc + +The html docs are located in the ``doc/_build/html`` directory. + + +Making a source tarball +======================= + +To create a source tarball, eg for packaging or distributing, run the +following command:: + + python setup.py sdist + +The tarball will be created in the `dist` directory. This command will +compile the docs, and the resulting tarball can be installed with +no extra dependencies than the Python standard library. You will need +setuptool and sphinx. + +Making a release and uploading it to PyPI +========================================= + +This command is only run by project manager, to make a release, and +upload in to PyPI:: + + python setup.py sdist bdist_wheel + twine upload dist/* + + +Note that the documentation should automatically get updated at each git +push. If that is not the case, try building th doc locally and resolve +any doc build error (in particular when running the examples). + +Updating the changelog +====================== + +Changes are listed in the CHANGES.rst file. They must be manually updated +but, the following git command may be used to generate the lines:: + + git log --abbrev-commit --date=short --no-merges --sparse + diff --git a/testbed/joblib__joblib/TODO.rst b/testbed/joblib__joblib/TODO.rst new file mode 100644 index 0000000000000000000000000000000000000000..0028cc37bd8fac09be8d44294634cc3044a6438d --- /dev/null +++ b/testbed/joblib__joblib/TODO.rst @@ -0,0 +1,51 @@ +Tasks at hand on joblib, in increasing order of difficulty. + +* Add a changelog! + +* In parallel: need to deal with return arguments that don't pickle. + +* Improve test coverage and documentation + +* Store a repr of the arguments for each call in the corresponding + cachedir + +* Try to use Mike McKerns's Dill pickling module in Parallel: + Implementation idea: + * Create a new function that is wrapped and takes Dillo pickles as + inputs as output, feed this one to multiprocessing + * pickle everything using Dill in the Parallel object. + http://dev.danse.us/trac/pathos/browser/dill + +* Make a sensible error message when wrong keyword arguments are given, + currently we have:: + + from joblib import Memory + mem = Memory(cachedir='cache') + + def f(a=0, b=2): + return a, b + + g = mem.cache(f) + g(c=2) + + /home/varoquau/dev/joblib/joblib/func_inspect.pyc in filter_args(func, + ignore_lst, *args, **kwargs), line 168 + + TypeError: Ignore list for diffusion_reorder() contains and + unexpected keyword argument 'cachedir' + +* add a 'depends' keyword argument to memory.cache, to be able to + specify that a function depends on other functions, and thus that the + cache should be cleared. + +* add a 'argument_hash' keyword argument to Memory.cache, to be able to + replace the hashing logic of memory for the input arguments. It should + accept as an input the dictionary of arguments, as returned in + func_inspect, and return a string. + +* add a sqlite db for provenance tracking. Store computation time and usage + timestamps, to be able to do 'garbage-collection-like' cleaning of + unused results, based on a cost function balancing computation cost and + frequency of use. + + diff --git a/testbed/joblib__joblib/azure-pipelines.yml b/testbed/joblib__joblib/azure-pipelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..936fabd929bc0019024286726be7038dd7cca79f --- /dev/null +++ b/testbed/joblib__joblib/azure-pipelines.yml @@ -0,0 +1,178 @@ + +# Python package +# Create and test a Python package on multiple Python versions. +# Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/python + +schedules: +- cron: "0 9 * * *" + displayName: Daily build + branches: + include: + - master + +trigger: +- master + +jobs: +- job: linting + displayName: Linting + pool: + vmImage: ubuntu-latest + steps: + - bash: echo "##vso[task.prependpath]$CONDA/bin" + displayName: Add conda to PATH + - bash: sudo chown -R $USER $CONDA + displayName: Take ownership of conda installation + - bash: conda create --name flake8_env --yes flake8 + displayName: Install flake8 + - bash: | + if [[ $BUILD_SOURCEVERSIONMESSAGE =~ \[lint\ skip\] ]]; then + # skip linting + echo "Skipping linting" + exit 0 + else + source activate flake8_env + flake8 + fi + displayName: Run linting + +- job: testing + displayName: Testing + strategy: + matrix: + linux_pypy38_v7311: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "pypy3.8" + PYPY_VERSION: "7.3.11" + LOKY_MAX_CPU_COUNT: "2" + + linux_pypy38_v736: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "pypy3.8" + PYPY_VERSION: "7.3.6" + LOKY_MAX_CPU_COUNT: "2" + + linux_pypy310_v7313: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "pypy3.10" + PYPY_VERSION: "7.3.13" + LOKY_MAX_CPU_COUNT: "2" + + linux_py39_sklearn_tests: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.9" + # SKIP_TESTS: "true" + SKLEARN_TESTS: "true" + linux_py310_distributed: + # To be updated regularly to use the most recent versions of the + # dependencies. + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.10" + EXTRA_CONDA_PACKAGES: "numpy=1.23 distributed=2023.10.1" + linux_py38_distributed: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.8" + EXTRA_CONDA_PACKAGES: "numpy=1.18.5 distributed=2021.5.0" + linux_py311_cython: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.11" + EXTRA_CONDA_PACKAGES: "numpy=1.24.1" + CYTHON: "true" + linux_py38_no_multiprocessing_no_lzma: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.8" + EXTRA_CONDA_PACKAGES: "numpy=1.16" + JOBLIB_MULTIPROCESSING: "0" + NO_LZMA: "1" + linux_py38_no_numpy: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.8" + linux_py38_default_backend_threading: + imageName: 'ubuntu-latest' + PYTHON_VERSION: "3.8" + JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND: "threading" + + windows_py310: + imageName: "windows-latest" + PYTHON_VERSION: "3.10" + EXTRA_CONDA_PACKAGES: "numpy=1.23" + + macos_py310: + imageName: "macos-latest" + PYTHON_VERSION: "3.10" + EXTRA_CONDA_PACKAGES: "numpy=1.23" + macos_py38_no_numpy: + imageName: "macos-latest" + PYTHON_VERSION: "3.8" + + variables: + JUNITXML: 'test-data.xml' + COVERAGE: "true" + + pool: + vmImage: $(imageName) + + steps: + + - bash: echo "##vso[task.prependpath]C:/Program Files/Git/bin" + displayName: 'Override Git bash shell for Windows' + condition: eq(variables['Agent.OS'], 'Windows_NT') + + - powershell: Write-Host "##vso[task.prependpath]$env:CONDA\Scripts" + displayName: Add conda to PATH + condition: eq(variables['Agent.OS'], 'Windows_NT') + + - bash: | + echo "##vso[task.prependpath]$CONDA/bin" + sudo chown -R $USER $CONDA + displayName: Add conda to PATH + condition: ne(variables['Agent.OS'], 'Windows_NT') + + - bash: bash continuous_integration/install.sh + displayName: 'Install joblib and its dependencies' + + - bash: bash continuous_integration/run_tests.sh + displayName: 'Run the tests' + + - task: PublishTestResults@2 + inputs: + testResultsFiles: '$(JUNITXML)' + displayName: 'Publish Test Results' + condition: and(succeededOrFailed(), ne(variables['SKIP_TESTS'], 'true')) + + - task: PublishPipelineArtifact@1 + inputs: + targetPath: .coverage + displayName: 'Create coverage artifact data' + condition: and(succeeded(), ne(variables['SKIP_TESTS'], 'true'), eq(variables['COVERAGE'], 'true')) + +- job: coverage + displayName: Coverage + dependsOn: testing + + pool: + vmImage: ubuntu-latest + + steps: + - bash: echo "##vso[task.prependpath]$CONDA/bin" + displayName: Add conda to PATH + - bash: sudo chown -R $USER $CONDA + displayName: Take ownership of conda installation + - bash: conda create --name coverage_env --yes coverage + displayName: Install coverage + + - task: DownloadPipelineArtifact@2 + inputs: + targetPath: ./ + displayName: 'Gather coverage data' + + - bash: | + source activate coverage_env + coverage combine **/.coverage + coverage xml + displayName: 'Consolidate coverage data' + + - bash: curl -s https://codecov.io/bash | bash + displayName: 'Upload to codecov' + condition: succeeded() diff --git a/testbed/joblib__joblib/benchmarks/bench_auto_batching.py b/testbed/joblib__joblib/benchmarks/bench_auto_batching.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb53c0583441a976fe660593d159a09566734c0 --- /dev/null +++ b/testbed/joblib__joblib/benchmarks/bench_auto_batching.py @@ -0,0 +1,111 @@ +"""Benchmark batching="auto" on high number of fast tasks + +The goal of this script is to study the behavior of the batch_size='auto' +and in particular the impact of the default value of the +joblib.parallel.MIN_IDEAL_BATCH_DURATION constant. + +""" +# Author: Olivier Grisel +# License: BSD 3 clause + +import numpy as np +import time +import tempfile +from pprint import pprint +from joblib import Parallel, delayed +from joblib._parallel_backends import AutoBatchingMixin + + +def sleep_noop(duration, input_data, output_data_size): + """Noop function to emulate real computation. + + Simulate CPU time with by sleeping duration. + + Induce overhead by accepting (and ignoring) any amount of data as input + and allocating a requested amount of data. + + """ + time.sleep(duration) + if output_data_size: + return np.ones(output_data_size, dtype=np.byte) + + +def bench_short_tasks(task_times, n_jobs=2, batch_size="auto", + pre_dispatch="2*n_jobs", verbose=True, + input_data_size=0, output_data_size=0, backend=None, + memmap_input=False): + + with tempfile.NamedTemporaryFile() as temp_file: + if input_data_size: + # Generate some input data with the required size + if memmap_input: + temp_file.close() + input_data = np.memmap(temp_file.name, shape=input_data_size, + dtype=np.byte, mode='w+') + input_data[:] = 1 + else: + input_data = np.ones(input_data_size, dtype=np.byte) + else: + input_data = None + + t0 = time.time() + p = Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch, + batch_size=batch_size, backend=backend) + p(delayed(sleep_noop)(max(t, 0), input_data, output_data_size) + for t in task_times) + duration = time.time() - t0 + effective_batch_size = getattr(p._backend, '_effective_batch_size', + p.batch_size) + print('Completed {} tasks in {:3f}s, final batch_size={}\n'.format( + len(task_times), duration, effective_batch_size)) + return duration, effective_batch_size + + +if __name__ == "__main__": + bench_parameters = dict( + # batch_size=200, # batch_size='auto' by default + # memmap_input=True, # if True manually memmap input out of timing + # backend='threading', # backend='multiprocessing' by default + # pre_dispatch='n_jobs', # pre_dispatch="2*n_jobs" by default + input_data_size=int(2e7), # input data size in bytes + output_data_size=int(1e5), # output data size in bytes + n_jobs=2, + verbose=10, + ) + print("Common benchmark parameters:") + pprint(bench_parameters) + + AutoBatchingMixin.MIN_IDEAL_BATCH_DURATION = 0.2 + AutoBatchingMixin.MAX_IDEAL_BATCH_DURATION = 2 + + # First pair of benchmarks to check that the auto-batching strategy is + # stable (do not change the batch size too often) in the presence of large + # variance while still be comparable to the equivalent load without + # variance + + print('# high variance, no trend') + # censored gaussian distribution + high_variance = np.random.normal(loc=0.000001, scale=0.001, size=5000) + high_variance[high_variance < 0] = 0 + + bench_short_tasks(high_variance, **bench_parameters) + print('# low variance, no trend') + low_variance = np.empty_like(high_variance) + low_variance[:] = np.mean(high_variance) + bench_short_tasks(low_variance, **bench_parameters) + + # Second pair of benchmarks: one has a cycling task duration pattern that + # the auto batching feature should be able to roughly track. We use an even + # power of cos to get only positive task durations with a majority close to + # zero (only data transfer overhead). The shuffle variant should not + # oscillate too much and still approximately have the same total run time. + + print('# cyclic trend') + slow_time = 0.1 + positive_wave = np.cos(np.linspace(1, 4 * np.pi, 300)) ** 8 + cyclic = positive_wave * slow_time + bench_short_tasks(cyclic, **bench_parameters) + + print("shuffling of the previous benchmark: same mean and variance") + np.random.shuffle(cyclic) + bench_short_tasks(cyclic, **bench_parameters) diff --git a/testbed/joblib__joblib/benchmarks/bench_compression.py b/testbed/joblib__joblib/benchmarks/bench_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..61909079f1cf258c44bec746d52d191e800f2efd --- /dev/null +++ b/testbed/joblib__joblib/benchmarks/bench_compression.py @@ -0,0 +1,248 @@ +"""Script comparing different pickling strategies.""" + +from joblib.numpy_pickle import NumpyPickler, NumpyUnpickler +from joblib.numpy_pickle_utils import BinaryZlibFile, BinaryGzipFile +from pickle import _Pickler, _Unpickler, Pickler, Unpickler +import numpy as np +import bz2 +import lzma +import time +import io +import sys +import os +from collections import OrderedDict + + +def fileobj(obj, fname, mode, kwargs): + """Create a file object.""" + return obj(fname, mode, **kwargs) + + +def bufferize(f, buf): + """Bufferize a fileobject using buf.""" + if buf is None: + return f + else: + if (buf.__name__ == io.BufferedWriter.__name__ or + buf.__name__ == io.BufferedReader.__name__): + return buf(f, buffer_size=10 * 1024 ** 2) + return buf(f) + + +def _load(unpickler, fname, f): + if unpickler.__name__ == NumpyUnpickler.__name__: + p = unpickler(fname, f) + else: + p = unpickler(f) + + return p.load() + + +def print_line(obj, strategy, buffer, pickler, dump, load, disk_used): + """Nice printing function.""" + print('% 20s | %6s | % 14s | % 7s | % 5.1f | % 5.1f | % 5s' % ( + obj, strategy, buffer, pickler, dump, load, disk_used)) + + +class PickleBufferedWriter(): + """Protect the underlying fileobj against numerous calls to write + This is achieved by internally keeping a list of small chunks and + only flushing to the backing fileobj if passed a large chunk or + after a threshold on the number of small chunks. + """ + + def __init__(self, fileobj, + max_buffer_size=10 * 1024 ** 2): + self._fileobj = fileobj + self._chunks = chunks = [] + + # As the `write` method is called many times by the pickler, + # attribute look ups on the self's __dict__ are too expensive + # hence we define a closure here with all the regularly + # accessed parameters + def _write(data): + chunks.append(data) + if len(chunks) > max_buffer_size: + self.flush() + self.write = _write + + def flush(self): + self._fileobj.write(b''.join(self._chunks[:])) + del self._chunks[:] + + def close(self): + self.flush() + self._fileobj.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + + +class PickleBufferedReader(): + """Protect the underlying fileobj against numerous calls to write + This is achieved by internally keeping a list of small chunks and + only flushing to the backing fileobj if passed a large chunk or + after a threshold on the number of small chunks. + """ + + def __init__(self, fileobj, + max_buffer_size=10 * 1024 ** 2): + self._fileobj = fileobj + self._buffer = bytearray(max_buffer_size) + self.max_buffer_size = max_buffer_size + self._position = 0 + + def read(self, n=None): + data = b'' + if n is None: + data = self._fileobj.read() + else: + while len(data) < n: + if self._position == 0: + self._buffer = self._fileobj.read(self.max_buffer_size) + elif self._position == self.max_buffer_size: + self._position = 0 + continue + next_position = min(self.max_buffer_size, + self._position + n - len(data)) + data += self._buffer[self._position:next_position] + self._position = next_position + return data + + def readline(self): + line = [] + while True: + c = self.read(1) + line.append(c) + if c == b'\n': + break + return b''.join(line) + + def close(self): + self._fileobj.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + + +def run_bench(): + print('% 20s | %10s | % 12s | % 8s | % 9s | % 9s | % 5s' % ( + 'Object', 'Compression', 'Buffer', 'Pickler/Unpickler', + 'dump time (s)', 'load time (s)', 'Disk used (MB)')) + print("--- | --- | --- | --- | --- | --- | ---") + + for oname, obj in objects.items(): + # Looping over the objects (array, dict, etc) + if isinstance(obj, np.ndarray): + osize = obj.nbytes / 1e6 + else: + osize = sys.getsizeof(obj) / 1e6 + + for cname, f in compressors.items(): + fobj = f[0] + fname = f[1] + fmode = f[2] + fopts = f[3] + # Looping other defined compressors + for bname, buf in bufs.items(): + writebuf = buf[0] + readbuf = buf[1] + # Looping other picklers + for pname, p in picklers.items(): + pickler = p[0] + unpickler = p[1] + t0 = time.time() + # Now pickling the object in the file + if (writebuf is not None and + writebuf.__name__ == io.BytesIO.__name__): + b = writebuf() + p = pickler(b) + p.dump(obj) + with fileobj(fobj, fname, fmode, fopts) as f: + f.write(b.getvalue()) + else: + with bufferize(fileobj(fobj, fname, fmode, fopts), + writebuf) as f: + p = pickler(f) + p.dump(obj) + dtime = time.time() - t0 + t0 = time.time() + # Now loading the object from the file + obj_r = None + if (readbuf is not None and + readbuf.__name__ == io.BytesIO.__name__): + b = readbuf() + with fileobj(fobj, fname, 'rb', {}) as f: + b.write(f.read()) + b.seek(0) + obj_r = _load(unpickler, fname, b) + else: + with bufferize(fileobj(fobj, fname, 'rb', {}), + readbuf) as f: + obj_r = _load(unpickler, fname, f) + ltime = time.time() - t0 + if isinstance(obj, np.ndarray): + assert (obj == obj_r).all() + else: + assert obj == obj_r + print_line("{} ({:.1f}MB)".format(oname, osize), + cname, + bname, + pname, + dtime, + ltime, + "{:.2f}".format(os.path.getsize(fname) / 1e6)) + + +# Defining objects used in this bench +DICT_SIZE = int(1e6) +ARRAY_SIZE = int(1e7) + +arr = np.random.normal(size=(ARRAY_SIZE)) +arr[::2] = 1 + +# Objects used for testing +objects = OrderedDict([ + ("dict", dict((i, str(i)) for i in range(DICT_SIZE))), + ("list", [i for i in range(DICT_SIZE)]), + ("array semi-random", arr), + ("array random", np.random.normal(size=(ARRAY_SIZE))), + ("array ones", np.ones((ARRAY_SIZE))), ]) + +#  We test 3 different picklers +picklers = OrderedDict([ + # Python implementation of Pickler/Unpickler + ("Pickle", (_Pickler, _Unpickler)), + # C implementation of Pickler/Unpickler + ("cPickle", (Pickler, Unpickler)), + # Joblib Pickler/Unpickler designed for numpy arrays. + ("Joblib", (NumpyPickler, NumpyUnpickler)), ]) + +# The list of supported compressors used for testing +compressors = OrderedDict([ + ("No", (open, '/tmp/test_raw', 'wb', {})), + ("Zlib", (BinaryZlibFile, '/tmp/test_zlib', 'wb', {'compresslevel': 3})), + ("Gzip", (BinaryGzipFile, '/tmp/test_gzip', 'wb', {'compresslevel': 3})), + ("Bz2", (bz2.BZ2File, '/tmp/test_bz2', 'wb', {'compresslevel': 3})), + ("Xz", (lzma.LZMAFile, '/tmp/test_xz', 'wb', + {'preset': 3, 'check': lzma.CHECK_NONE})), + ("Lzma", (lzma.LZMAFile, '/tmp/test_lzma', 'wb', + {'preset': 3, 'format': lzma.FORMAT_ALONE})), ]) + +# Test 3 buffering strategies +bufs = OrderedDict([ + ("None", (None, None)), + ("io.BytesIO", (io.BytesIO, io.BytesIO)), + ("io.Buffered", (io.BufferedWriter, io.BufferedReader)), + ("PickleBuffered", (PickleBufferedWriter, PickleBufferedReader)), ]) + +if __name__ == "__main__": + run_bench() diff --git a/testbed/joblib__joblib/benchmarks/bench_grid_search_scaling.py b/testbed/joblib__joblib/benchmarks/bench_grid_search_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..3dad542bb2fe701e3d5e6533ea56dec173c54624 --- /dev/null +++ b/testbed/joblib__joblib/benchmarks/bench_grid_search_scaling.py @@ -0,0 +1,97 @@ +"""Benchmark a small scale scikit-learn GridSearch and the scaling with n_jobs. + +This benchmark requires ``scikit-learn`` to be installed. + +The goal of this script is to make sure the scaling does not worsen with time. +In particular, it can be used to compare 2 joblib versions by first running +the benchmark with the option `-n name1`, then changing the joblib version and +running the script with option `-c name1`. This option can be used multiple +times to build a comparison with more than 2 version. +""" +from time import time + +import matplotlib.pyplot as plt +import joblib +import numpy as np + +from sklearn.svm import SVC +from sklearn import datasets +from sklearn.model_selection import GridSearchCV + + +def get_file_name(name): + return f"bench_gs_scaling_{name}.npy" + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser( + description="") + parser.add_argument( + "--n-rep", "-r", type=int, default=5, + help="Number of repetition to average on." + ) + parser.add_argument( + "--name", "-n", type=str, default="", + help="Name to save the results with. This can be used to compare " + "different branches with '-c'." + ) + parser.add_argument( + "--compare", "-c", action="append", + help="Loads the results from a benchmark saved previously with a name " + "given as the present argument value. This allows comparing the " + "results across different versions of joblib." + ) + args = parser.parse_args() + + # Generate a synthetic dataset for classification. + rng = np.random.RandomState(0) + X, y = datasets.make_classification(n_samples=1000, random_state=rng) + + # + gammas = [1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7] + Cs = [1, 10, 100, 1e3, 1e4, 1e5] + param_grid = {"gamma": gammas, "C": Cs} + + clf = SVC(random_state=rng) + + # Warm up run to avoid the first run overhead of starting the executor. + GridSearchCV(estimator=clf, param_grid=param_grid, n_jobs=-1).fit(X, y) + + # We run the n_jobs in decreasing order to avoid the issue joblib/loky#396 + # that make the queue size too small when increasing an executor size. + res = [] + for n_jobs in range(joblib.cpu_count(), 0, -2): + T = [] + for _ in range(args.n_rep): + tic = time() + gs = GridSearchCV( + estimator=clf, param_grid=param_grid, n_jobs=n_jobs + ) + gs.fit(X, y) + T += [time() - tic] + res += [(n_jobs, *np.quantile(T, [0.5, 0.2, 0.8]))] + res = np.array(res).T + + if args.name: + fname = get_file_name(args.name) + np.save(fname, res) + + label = args.name or "current" + plt.fill_between(res[0], res[2], res[3], alpha=0.3, color="C0") + plt.plot(res[0], res[1], c="C0", lw=2, label=label) + + if args.compare: + for i, name_c in enumerate(args.compare): + fname_compare = get_file_name(name_c) + res_c = np.load(fname_compare) + plt.fill_between( + res_c[0], res_c[2], res_c[3], alpha=0.3, color=f"C{i+1}" + ) + plt.plot(res_c[0], res_c[1], c=f"C{i+1}", lw=2, label=name_c) + + plt.xlabel("n_jobs") + plt.ylabel("Time [s]") + plt.ylim(0, None) + plt.legend() + plt.show() diff --git a/testbed/joblib__joblib/benchmarks/bench_pickle.py b/testbed/joblib__joblib/benchmarks/bench_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..671d57d57cc1361e40956f6cd5c6c3e484401a10 --- /dev/null +++ b/testbed/joblib__joblib/benchmarks/bench_pickle.py @@ -0,0 +1,467 @@ +""" +Benching joblib pickle I/O. + +Warning: this is slow, and the benches are easily offset by other disk +activity. +""" +import os +import time +import shutil +import numpy as np +import joblib +import gc + +from joblib.disk import disk_used + +try: + from memory_profiler import memory_usage +except ImportError: + memory_usage = None + + +def clear_out(): + """Clear output directory.""" + if os.path.exists('out'): + shutil.rmtree('out') + os.mkdir('out') + + +def kill_disk_cache(): + """Clear disk cache to avoid side effects.""" + if os.name == 'posix' and os.uname()[0] == 'Linux': + try: + os.system('sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"') + except IOError as e: + if e.errno == 13: + print('Please run me as root') + else: + raise + else: + # Write ~100M to the disk + open('tmp', 'wb').write(np.random.random(2e7)) + + +def delete_obj(obj): + """Force destruction of an object.""" + if obj is not None: + del obj + gc.collect() + + +def memory_used(func, *args, **kwargs): + """Compute memory usage of func.""" + if memory_usage is None: + return np.nan + + gc.collect() + mem_use = memory_usage((func, args, kwargs), interval=.001) + + return max(mem_use) - min(mem_use) + + +def timeit(func, *args, **kwargs): + """Compute the mean execution time of func based on 7 measures.""" + times = [] + tries = kwargs['tries'] + kwargs.pop('tries') + if tries > 1: + tries += 2 + + for _ in range(tries): + kill_disk_cache() + t0 = time.time() + out = func(*args, **kwargs) + if 1: + # Just time the function + t1 = time.time() + times.append(t1 - t0) + else: + # Compute a hash of the output, to estimate the time + # necessary to access the elements: this is a better + # estimate of the time to load with me mmapping. + joblib.hash(out) + t1 = time.time() + joblib.hash(out) + t2 = time.time() + times.append(t2 - t0 - 2 * (t2 - t1)) + times.sort() + return np.mean(times[1:-1]) if tries > 1 else t1 - t0, out + + +def generate_rand_dict(size, + with_arrays=False, + with_string=False, + array_shape=(10, 10)): + """Generate dictionary with random values from list of keys.""" + ret = {} + rnd = np.random.RandomState(0) + randoms = rnd.random_sample((size)) + for key, random in zip(range(size), randoms): + if with_arrays: + ret[str(key)] = rnd.random_sample(array_shape) + elif with_string: + ret[str(key)] = str(random) + else: + ret[str(key)] = int(random) + return ret + + +def generate_rand_list(size, + with_arrays=False, + with_string=False, + array_shape=(10, 10)): + """Generate list with random values from list of keys.""" + ret = [] + rnd = np.random.RandomState(0) + for random in rnd.random_sample((size)): + if with_arrays: + ret.append(rnd.random_sample(array_shape)) + elif with_string: + ret.append(str(random)) + else: + ret.append(int(random)) + return ret + + +def print_line(dataset, strategy, + write_time, read_time, + mem_write, mem_read, + disk_used): + """Nice printing function.""" + print('% 15s, %12s, % 6.3f, % 7.4f, % 9.1f, % 9.1f, % 5.1f' % ( + dataset, strategy, + write_time, read_time, + mem_write, mem_read, disk_used)) + + +def print_bench_summary(args): + """Nice bench summary function.""" + summary = """Benchmark summary: + - Global values: + . Joblib version: {} + . Number of tries to compute mean execution time: {} + . Compression levels : {} + . Compression algorithm: {} + . Memory map mode : {} + . Bench nifti data : {} + . Bench big array : {} + . Bench 2 big arrays : {} + . Bench big dictionary: {} + . Bench array+dict : {} +""".format(joblib.__version__, + args.tries, + ", ".join(map(str, args.compress)), + "None" if not args.compress else args.compressor, + args.mmap, + args.nifti, + args.array, + args.arrays, + args.dict, + args.combo) + + if args.array: + shape = tuple(args.shape) + size = round(np.multiply.reduce(shape) * 8 / 1024 ** 2, 1) + summary += """ + - Big array: + . shape: {} + . size in memory: {} MB +""".format(str(shape), size) + + if args.dict: + summary += """ + - Big dictionary: + . number of keys: {} + . value type: {} +""".format(args.size, 'np.ndarray' + if args.valuearray else 'str' + if args.valuestring else 'int') + if args.valuearray: + summary += """ . arrays shape: {} +""".format(str(tuple(args.valuearrayshape))) + + if args.list: + summary += """ + - Big list: + . number of elements: {} + . value type: {} +""".format(args.size, 'np.ndarray' + if args.valuearray else 'str' + if args.valuestring else 'int') + if args.valuearray: + summary += """ . arrays shape: {} +""".format(str(tuple(args.valuearrayshape))) + + print(summary) + + +def bench_compress(dataset, name='', + compress=('zlib', 0), cache_size=0, tries=5): + """Bench joblib dump and load functions, compress modes.""" + # generate output compression strategy string before joblib compatibility + # check as it may override the compress variable with a non tuple type. + compress_str = "Raw" if compress[1] == 0 else "{} {}".format(*compress) + + # joblib versions prior to 0.10 doesn't support tuple in compress argument + # so only the second element of the tuple is used for those versions + # and the compression strategy is ignored. + if (isinstance(compress, tuple) and + tuple(map(int, joblib.__version__.split('.')[:2])) < (0, 10)): + compress = compress[1] + + time_write = time_read = du = mem_read = mem_write = [] + clear_out() + time_write, obj = timeit(joblib.dump, dataset, 'out/test.pkl', + tries=tries, + compress=compress, cache_size=cache_size) + del obj + gc.collect() + mem_write = memory_used(joblib.dump, dataset, 'out/test.pkl', + compress=compress, cache_size=cache_size) + delete_obj(dataset) + du = disk_used('out') / 1024. + time_read, obj = timeit(joblib.load, 'out/test.pkl', tries=tries) + delete_obj(obj) + mem_read = memory_used(joblib.load, 'out/test.pkl') + print_line(name, compress_str, time_write, time_read, + mem_write, mem_read, du) + + +def bench_mmap(dataset, name='', cache_size=0, mmap_mode='r', tries=5): + """Bench joblib dump and load functions, memmap modes.""" + time_write = time_read = du = [] + clear_out() + time_write, _ = timeit(joblib.dump, dataset, 'out/test.pkl', + tries=tries, + cache_size=cache_size) + mem_write = memory_used(joblib.dump, dataset, 'out/test.pkl', + cache_size=cache_size) + + delete_obj(dataset) + + time_read, obj = timeit(joblib.load, 'out/test.pkl', + tries=tries, + mmap_mode=mmap_mode) + delete_obj(obj) + mem_read = memory_used(joblib.load, 'out/test.pkl', mmap_mode=mmap_mode) + du = disk_used('out') / 1024. + print_line(name, 'mmap %s' % mmap_mode, + time_write, time_read, mem_write, mem_read, du) + + +def run_bench(func, obj, name, **kwargs): + """Run the benchmark function.""" + func(obj, name, **kwargs) + + +def run(args): + """Run the full bench suite.""" + if args.summary: + print_bench_summary(args) + + if (not args.nifti and not args.array and not args.arrays and + not args.dict and not args.list and not args.combo): + print("Nothing to bench. Exiting") + return + + compress_levels = args.compress + compress_method = args.compressor + mmap_mode = args.mmap + + container_size = args.size + a1_shape = tuple(args.shape) + a2_shape = (10000000, ) + + print('% 15s, %12s, % 6s, % 7s, % 9s, % 9s, % 5s' % ( + 'Dataset', 'strategy', 'write', 'read', + 'mem_write', 'mem_read', 'disk')) + + if args.nifti: + # Nifti images + try: + import nibabel + except ImportError: + print("nibabel is not installed skipping nifti file benchmark.") + else: + def load_nii(filename): + img = nibabel.load(filename) + return img.get_data(), img.get_affine() + + for name, nifti_file in ( + ('MNI', + '/usr/share/fsl/data/atlases' + '/MNI/MNI-prob-1mm.nii.gz'), + ('Juelich', + '/usr/share/fsl/data/atlases' + '/Juelich/Juelich-prob-2mm.nii.gz'), ): + for c_order in (True, False): + name_d = '% 5s(%s)' % (name, 'C' if c_order else 'F') + for compress_level in compress_levels: + d = load_nii(nifti_file) + + if c_order: + d = (np.ascontiguousarray(d[0]), d[1]) + + run_bench(bench_compress, d, name_d, + compress=(compress_method, compress_level), + tries=args.tries) + del d + if not args.nommap: + d = load_nii(nifti_file) + if c_order: + d = (np.ascontiguousarray(d[0]), d[1]) + + run_bench(bench_mmap, d, name_d, + mmap_mode=mmap_mode, tries=args.tries) + del d + + # Generate random seed + rnd = np.random.RandomState(0) + + if args.array: + # numpy array + name = '% 5s' % 'Big array' + for compress_level in compress_levels: + a1 = rnd.random_sample(a1_shape) + run_bench(bench_compress, a1, name, + compress=(compress_method, compress_level), + tries=args.tries) + del a1 + if not args.nommap: + a1 = rnd.random_sample(a1_shape) + run_bench(bench_mmap, a1, name, mmap_mode=mmap_mode, + tries=args.tries) + del a1 + + if args.arrays: + # Complex object with 2 big arrays + name = '% 5s' % '2 big arrays' + for compress_level in compress_levels: + obj = [rnd.random_sample(a1_shape), rnd.random_sample(a2_shape)] + run_bench(bench_compress, obj, name, + compress=(compress_method, compress_level), + tries=args.tries) + del obj + if not args.nommap: + obj = [rnd.random_sample(a1_shape), rnd.random_sample(a2_shape)] + run_bench(bench_mmap, obj, name, mmap_mode=mmap_mode, + tries=args.tries) + del obj + + if args.dict: + # Big dictionary + name = '% 5s' % 'Big dict' + array_shape = tuple(args.valuearrayshape) + for compress_level in compress_levels: + big_dict = generate_rand_dict(container_size, + with_arrays=args.valuearray, + with_string=args.valuestring, + array_shape=array_shape) + run_bench(bench_compress, big_dict, name, + compress=(compress_method, compress_level), + tries=args.tries) + del big_dict + if not args.nommap: + big_dict = generate_rand_dict(container_size, + with_arrays=args.valuearray, + with_string=args.valuestring, + array_shape=array_shape) + run_bench(bench_mmap, big_dict, name, mmap_mode=mmap_mode, + tries=args.tries) + del big_dict + + if args.list: + # Big dictionary + name = '% 5s' % 'Big list' + array_shape = tuple(args.valuearrayshape) + for compress_level in compress_levels: + big_list = generate_rand_list(container_size, + with_arrays=args.valuearray, + with_string=args.valuestring, + array_shape=array_shape) + run_bench(bench_compress, big_list, name, + compress=(compress_method, compress_level), + tries=args.tries) + del big_list + if not args.nommap: + big_list = generate_rand_list(container_size, + with_arrays=args.valuearray, + with_string=args.valuestring, + array_shape=array_shape) + run_bench(bench_mmap, big_list, name, mmap_mode=mmap_mode, + tries=args.tries) + del big_list + + if args.combo: + # 2 big arrays with one big dict + name = '% 5s' % 'Dict/arrays' + array_shape = tuple(args.valuearrayshape) + for compress_level in compress_levels: + obj = [rnd.random_sample(a1_shape), + generate_rand_dict(container_size, + with_arrays=args.valuearray, + with_string=args.valuestring, + array_shape=array_shape), + rnd.random_sample(a2_shape)] + run_bench(bench_compress, obj, name, + compress=(compress_method, compress_level), + tries=args.tries) + del obj + if not args.nommap: + obj = [rnd.random_sample(a1_shape), + generate_rand_dict(container_size, + with_arrays=args.valuearray, + with_string=args.valuestring, + array_shape=array_shape), + rnd.random_sample(a2_shape)] + run_bench(bench_mmap, obj, name, + mmap_mode=mmap_mode, + tries=args.tries) + del obj + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser(description="Joblib benchmark script") + parser.add_argument('--compress', nargs='+', type=int, default=(0, 3), + help="List of compress levels.") + parser.add_argument('--compressor', type=str, default='zlib', + choices=['zlib', 'gzip', 'bz2', 'xz', 'lzma'], + help="Compression algorithm.") + parser.add_argument('--mmap', type=str, default='r', + choices=['r', 'r+', 'w+'], + help="Memory map mode.") + parser.add_argument('--tries', type=int, default=5, + help="Number of tries to compute execution time" + "mean on.") + parser.add_argument('--shape', nargs='+', type=int, default=(10000, 10000), + help="Big array shape.") + parser.add_argument("-m", "--nommap", action="store_true", + help="Don't bench memmap") + parser.add_argument('--size', type=int, default=10000, + help="Big dictionary size.") + parser.add_argument('--valuearray', action="store_true", + help="Use numpy arrays type in containers " + "(list, dict)") + parser.add_argument('--valuearrayshape', nargs='+', type=int, + default=(10, 10), + help="Shape of arrays in big containers.") + parser.add_argument('--valuestring', action="store_true", + help="Use string type in containers (list, dict).") + parser.add_argument("-n", "--nifti", action="store_true", + help="Benchmark Nifti data") + parser.add_argument("-a", "--array", action="store_true", + help="Benchmark single big numpy array") + parser.add_argument("-A", "--arrays", action="store_true", + help="Benchmark list of big numpy arrays") + parser.add_argument("-d", "--dict", action="store_true", + help="Benchmark big dictionary.") + parser.add_argument("-l", "--list", action="store_true", + help="Benchmark big list.") + parser.add_argument("-c", "--combo", action="store_true", + help="Benchmark big dictionary + list of " + "big numpy arrays.") + parser.add_argument("-s", "--summary", action="store_true", + help="Show bench summary.") + + run(parser.parse_args()) diff --git a/testbed/joblib__joblib/benchmarks/bench_sequential_fast_tasks.py b/testbed/joblib__joblib/benchmarks/bench_sequential_fast_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..9b667fd2950b002dbade4f3aa59bc1b868955b37 --- /dev/null +++ b/testbed/joblib__joblib/benchmarks/bench_sequential_fast_tasks.py @@ -0,0 +1,107 @@ +"""Benchmark n_jobs=1 on high number of fast tasks + +The goal of this script is to study the overhead incurred when calling small +tasks with `n_jobs=1` compared to just running a simple list comprehension. + +""" +# Author: Thomas Moreau +# License: BSD 3 clause + +import time + +import numpy as np +import pandas as pd + +import matplotlib.pyplot as plt +from matplotlib.colors import LogNorm +from matplotlib.cm import ScalarMappable + + +from joblib import Parallel, delayed + + +# Style for plots +LINE_STYLES = {'iter': '--', 'parallel': '-', 'loop': ':'} +COLORS = {'none': 'indianred'} +CMAP = plt.colormaps['viridis'] + +# Generate functions that are more and more complex, to see +# the relative impact depending on the task complexity +funcs = [("none", lambda x: None, None)] +n_size = 3 +for i, n in enumerate(np.logspace(0, 2, n_size, dtype=int)): + n = max(1, n) + label = f'mat({n:3d}, {n:3d})' + A = np.random.randn(n, n) + funcs.append((label, lambda A: A @ A, A)) + COLORS[label] = CMAP(i / (n_size - 1)) + +# For each function and for different number of repetition, +# time the Parallel call. +results = [] +for f_name, func, arg in funcs: + print('Benchmarking:', f_name) + f_delayed = delayed(func) + for N in np.logspace(1, 4, 4, dtype=int): + print('# tasks:', N) + for _ in range(10): + + t_start = time.perf_counter() + list(func(arg) for _ in range(N)) + runtime = time.perf_counter() - t_start + results.append(dict( + method="iter", N=N, func=f_name, runtime=runtime / N + )) + + t_start = time.perf_counter() + Parallel(n_jobs=1)(f_delayed(arg) for _ in range(N)) + runtime = time.perf_counter() - t_start + results.append(dict( + method="parallel", N=N, func=f_name, runtime=runtime / N + )) + +# Use a DataFrame to manipulate the results. +df = pd.DataFrame(results) + +# Compute median runtime for each set of parameters +curve = df.groupby(["method", "N", "func"])["runtime"].median().reset_index() + +# Print the overhead incurred for each task (estimated as the median of the +# time difference per task). +for k, grp in curve.groupby("func"): + + c_iter = grp.query('method == "iter"').set_index("N") + c_parallel = grp.query('method == "parallel"').set_index("N") + overhead_percent = (c_parallel["runtime"] / c_iter["runtime"]).median() - 1 + overhead_time = (c_parallel["runtime"] - c_iter["runtime"]) / c_iter.index + print( + f"For func {k}, overhead_time is {overhead_time.median()/1e-6:.2f}us, " + f"increasing runtime by {overhead_percent * 100:.2f}%" + ) + +# Plot the scaling curves. +fig, ax = plt.subplots() +for key, grp in curve.groupby(["method", "func"]): + ax.loglog( + grp["N"], + grp["runtime"], + label=key, + ls=LINE_STYLES[key[0]], + color=COLORS[key[1]], + ) + +ax.set_xlabel("# Tasks") +ax.set_ylabel("Runtime per task") +ax.legend( + (plt.Line2D([], [], ls=ls, c="k") for ls in LINE_STYLES.values()), + LINE_STYLES, + bbox_to_anchor=(0.3, 1, 0.3, 0.1), + loc='center', + ncol=3, +) +plt.colorbar( + ScalarMappable(norm=LogNorm(1, 200), cmap=plt.cm.viridis), + label="Matrix size" +) + +plt.show() diff --git a/testbed/joblib__joblib/conftest.py b/testbed/joblib__joblib/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..53413deec1cfb2de0954e5a372859cdcc30c5889 --- /dev/null +++ b/testbed/joblib__joblib/conftest.py @@ -0,0 +1,86 @@ +import os + +import logging +import faulthandler + +import pytest +from _pytest.doctest import DoctestItem + +from joblib.parallel import mp +from joblib.backports import LooseVersion +try: + import lz4 +except ImportError: + lz4 = None +try: + from distributed.utils_test import loop, loop_in_thread +except ImportError: + loop = None + loop_in_thread = None + + +def pytest_collection_modifyitems(config, items): + skip_doctests = True + + # We do not want to run the doctests if multiprocessing is disabled + # e.g. via the JOBLIB_MULTIPROCESSING env variable + if mp is not None: + try: + # numpy changed the str/repr formatting of numpy arrays in 1.14. + # We want to run doctests only for numpy >= 1.14. + import numpy as np + if LooseVersion(np.__version__) >= LooseVersion('1.14'): + skip_doctests = False + except ImportError: + pass + + if skip_doctests: + skip_marker = pytest.mark.skip( + reason='doctests are only run for numpy >= 1.14') + + for item in items: + if isinstance(item, DoctestItem): + item.add_marker(skip_marker) + + if lz4 is None: + for item in items: + if item.name == 'persistence.rst': + item.add_marker(pytest.mark.skip(reason='lz4 is missing')) + + +def pytest_configure(config): + """Setup multiprocessing logging for the tests""" + if mp is not None: + log = mp.util.log_to_stderr(logging.DEBUG) + log.handlers[0].setFormatter(logging.Formatter( + '[%(levelname)s:%(processName)s:%(threadName)s] %(message)s')) + + # Some CI runs failed with hanging processes that were not terminated + # with the timeout. To make sure we always get a proper trace, set a large + # enough dump_traceback_later to kill the process with a report. + faulthandler.dump_traceback_later(30 * 60, exit=True) + + DEFAULT_BACKEND = os.environ.get( + "JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND", None + ) + if DEFAULT_BACKEND is not None: + print( + f"Setting joblib parallel default backend to {DEFAULT_BACKEND} " + "from JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND environment variable" + ) + from joblib import parallel + parallel.DEFAULT_BACKEND = DEFAULT_BACKEND + + +def pytest_unconfigure(config): + + # Setup a global traceback printer callback to debug deadlocks that + # would happen once pytest has completed: for instance in atexit + # finalizers. At this point the stdout/stderr capture of pytest + # should be disabled. Note that we cancel the global dump_traceback_later + # to waiting for too long. + faulthandler.cancel_dump_traceback_later() + + # Note that we also use a shorter timeout for the per-test callback + # configured via the pytest-timeout extension. + faulthandler.dump_traceback_later(60, exit=True) diff --git a/testbed/joblib__joblib/continuous_integration/install.sh b/testbed/joblib__joblib/continuous_integration/install.sh new file mode 100644 index 0000000000000000000000000000000000000000..c6fed28836f047988a9267727fd742f2adedf79d --- /dev/null +++ b/testbed/joblib__joblib/continuous_integration/install.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# This script is meant to be called by the "install" step defined in +# .travis.yml. See http://docs.travis-ci.com/ for more details. +# The behavior of the script is controlled by environment variabled defined +# in the .travis.yml in the top level folder of the project. +# +# This script is adapted from a similar script from the scikit-learn repository. +# +# License: 3-clause BSD + +set -e + +create_new_conda_env() { + conda update --yes conda conda-libmamba-solver + conda config --set solver libmamba + TO_INSTALL="python=$PYTHON_VERSION pip pytest $EXTRA_CONDA_PACKAGES" + conda create -n testenv --yes -c conda-forge $TO_INSTALL + source activate testenv +} + +create_new_pypy3_env() { + PYPY_FOLDER="$PYTHON_VERSION-v$PYPY_VERSION-linux64" + wget https://downloads.python.org/pypy/$PYPY_FOLDER.tar.bz2 + tar xvf $PYPY_FOLDER.tar.bz2 + $PYPY_FOLDER/bin/pypy3 -m venv pypy3 + source pypy3/bin/activate + pip install -U pip 'pytest' +} + +if [[ "$PYTHON_VERSION" == pypy3* ]]; then + create_new_pypy3_env +else + create_new_conda_env +fi + +# Install pytest timeout to fasten failure in deadlocking tests +PIP_INSTALL_PACKAGES="pytest-timeout threadpoolctl" + +if [ -n "$NUMPY_VERSION" ]; then + # We want to ensure no memory copies are performed only when numpy is + # installed. This also ensures that we don't keep a strong dependency on + # memory_profiler. We also want to ensure that joblib can be used with and + # without lz4 compressor package installed. + PIP_INSTALL_PACKAGES="$PIP_INSTALL_PACKAGES memory_profiler" + if [ "$NO_LZ4" != "true" ]; then + PIP_INSTALL_PACKAGES="$PIP_INSTALL_PACKAGES lz4" + fi +fi + +if [[ "$COVERAGE" == "true" ]]; then + PIP_INSTALL_PACKAGES="$PIP_INSTALL_PACKAGES coverage pytest-cov" +fi + +pip install $PIP_INSTALL_PACKAGES + +if [[ "$NO_LZMA" == "1" ]]; then + # Delete the LZMA module from the standard lib to make sure joblib has no + # hard dependency on it: + LZMA_PATH=`python -c "import lzma; print(lzma.__file__)"` + echo "Deleting $LZMA_PATH..." + rm $LZMA_PATH +fi + +if [[ "$CYTHON" == "true" ]]; then + pip install cython + cd joblib/test/_openmp_test_helper + python setup.py build_ext -i + cd ../../.. +fi + +pip install -v . diff --git a/testbed/joblib__joblib/continuous_integration/run_tests.sh b/testbed/joblib__joblib/continuous_integration/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..396bbe2940d3db20f1bef7dedb5f2ab4200dd989 --- /dev/null +++ b/testbed/joblib__joblib/continuous_integration/run_tests.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +set -e + +echo "Activating test environment:" +if [[ "$PYTHON_VERSION" == pypy3* ]]; then + source pypy3/bin/activate +else + source activate testenv +fi +which python +python -V +python -c "import multiprocessing as mp; print('multiprocessing.cpu_count():', mp.cpu_count())" +python -c "import joblib; print('joblib.cpu_count():', joblib.cpu_count())" + +if [[ "$SKIP_TESTS" != "true" ]]; then + if [ "$COVERAGE" == "true" ]; then + # Enable coverage-related options. --cov-append is needed to combine + # the test run and the test-doc run coverage. + export PYTEST_ADDOPTS="--cov=joblib --cov-append" + fi + + pytest joblib -vl --timeout=120 --junitxml="${JUNITXML}" + make test-doc +fi + +if [[ "$SKLEARN_TESTS" == "true" ]]; then + # Install the nightly build of scikit-learn and test against the installed + # development version of joblib. + # TODO: unpin pip once either https://github.com/pypa/pip/issues/10825 + # accepts invalid HTML or Anaconda is fixed. + conda install -y -c conda-forge cython pillow numpy scipy "pip<22" + pip install --pre --extra-index https://pypi.anaconda.org/scipy-wheels-nightly/simple scikit-learn + python -c "import sklearn; print('Testing scikit-learn', sklearn.__version__)" + + # Move to a dedicated folder to avoid being polluted by joblib specific conftest.py + # and disable the doctest plugin to avoid issues with doctests in scikit-learn + # docstrings that require setting print_changed_only=True temporarily. + NEW_TEST_DIR=$(mktemp -d) + cd $NEW_TEST_DIR + + pytest -vl --maxfail=5 -p no:doctest \ + -k "not test_import_is_deprecated" \ + -k "not test_check_memory" \ + --pyargs sklearn + + # Justification for skipping some tests: + # + # test_import_is_deprecated: Don't worry about deprecated imports: this is + # tested for real in upstream scikit-learn and this is not joblib's + # responsibility. Let's skip this test to avoid false positives in joblib's + # CI. + # + # test_check_memory: scikit-learn test need to be updated to avoid using + # cachedir: https://github.com/scikit-learn/scikit-learn/pull/22365 +fi diff --git a/testbed/joblib__joblib/doc/Makefile b/testbed/joblib__joblib/doc/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..547f3f2d768efce9e308087eb8319fad8345892d --- /dev/null +++ b/testbed/joblib__joblib/doc/Makefile @@ -0,0 +1,20 @@ +# You can set these variables from the command lines +SPHINXOPTS ?= -j $(shell nproc) -nWT --keep-going +SPHINXBUILD ?= sphinx-build + +.PHONY: all html clean + +all: html + +# generate html documentation with warning as errors +html: + $(SPHINXBUILD) $(SPHINXOPTS) -b html . ./_build/html/ + +# remove generated sphinx gallery examples and sphinx documentation +clean: + rm -rf auto_examples && rm -rf generated && rm -rf _build + +view: + @python -c "import webbrowser; webbrowser.open_new_tab('file://$(PWD)/_build/html/index.html')" + +show: view diff --git a/testbed/joblib__joblib/doc/__init__.py b/testbed/joblib__joblib/doc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f5869d6a673b563e9392c6506635fe9bbf0370 --- /dev/null +++ b/testbed/joblib__joblib/doc/__init__.py @@ -0,0 +1,4 @@ +""" +This is a phony __init__.py file, so that pytest finds the doctests in this +directory. +""" diff --git a/testbed/joblib__joblib/doc/_static/custom.css b/testbed/joblib__joblib/doc/_static/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..e0cb807737911970787c318ad3e03c3069f6a638 --- /dev/null +++ b/testbed/joblib__joblib/doc/_static/custom.css @@ -0,0 +1,73 @@ +/* Avoid white space above the logo */ +div.document { + margin-top: 0px; +} +div.body { + padding-top: 30px; +} + + +/* Main page title */ +div.body h1 { + text-align: center; + font-size: 270%; + color: #643200; +} + +/* Secondary sections title */ +div.body h2 { + color: #643200; +} + +/* Third sections title */ + +div.sphinxsidebar h3 { + font-size: xx-large; +} + +/* Python examples code block */ +div.highlight pre { + background-color: #f5f5f5; + font-size: 80%; + padding-left: 10px; + padding-right: 10px; +} + +/* restyle table */ +div.body table.docutils tr{ + background: #ccc; /* fallback if nth-child is not supported */ +} +div.body table.docutils tr:nth-child(odd){ + background: #f8f4ee; +} +div.body table.docutils tr:nth-child(even){ + background: #fff; +} +div.body table.docutils td{ + border: none; +} + +/* Move the ads down in read the docs */ +div.sphinxsidebarwrapper ul:last-of-type { + margin-top: -10px; + margin-bottom: 100px; +} + +/* But don't apply this to nested ul */ +div.sphinxsidebarwrapper ul ul:last-of-type { + margin-top: 0px; + margin-bottom: 20px; +} + +/* Sidebar subtitle */ +p.caption { + font-size: x-large; + font-weight: 400; +} + +div.body p.caption { + color: #643200; + font-size: 180%; + font-family: Georgia, serif; + font-weight: normal; +} \ No newline at end of file diff --git a/testbed/joblib__joblib/doc/_static/joblib_logo.svg b/testbed/joblib__joblib/doc/_static/joblib_logo.svg new file mode 100644 index 0000000000000000000000000000000000000000..7d7565860c1f52be935bbe335874479a03f07745 --- /dev/null +++ b/testbed/joblib__joblib/doc/_static/joblib_logo.svg @@ -0,0 +1,101 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + diff --git a/testbed/joblib__joblib/doc/_templates/class.rst b/testbed/joblib__joblib/doc/_templates/class.rst new file mode 100644 index 0000000000000000000000000000000000000000..ec25aadd0c56dbdbd6872a480d0913c18aea42cc --- /dev/null +++ b/testbed/joblib__joblib/doc/_templates/class.rst @@ -0,0 +1,11 @@ +{{ fullname | escape | underline }} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + :members: + +.. _sphx_glr_backreferences_{{ fullname }}: + +.. minigallery:: {{ fullname }} + :add-heading: diff --git a/testbed/joblib__joblib/doc/_templates/function.rst b/testbed/joblib__joblib/doc/_templates/function.rst new file mode 100644 index 0000000000000000000000000000000000000000..f4b11eda770e4606376a354d09a24093a2e35a19 --- /dev/null +++ b/testbed/joblib__joblib/doc/_templates/function.rst @@ -0,0 +1,12 @@ +:mod:`{{module}}`.{{objname}} +{{ underline }}==================== + +.. currentmodule:: {{ module }} + +.. autofunction:: {{ objname }} + +.. include:: {{module}}.{{objname}}.examples + +.. raw:: html + +
diff --git a/testbed/joblib__joblib/doc/_templates/layout.html b/testbed/joblib__joblib/doc/_templates/layout.html new file mode 100644 index 0000000000000000000000000000000000000000..ad502bcac182cd42a052ee7565ef51f0c8fb8e73 --- /dev/null +++ b/testbed/joblib__joblib/doc/_templates/layout.html @@ -0,0 +1,22 @@ +{% extends '!layout.html' %} + +{%- if pagename == 'index' %} + {% set title = 'Joblib: running Python functions as pipeline jobs' %} +{%- endif %} + +{%- block sidebarsourcelink %} +{% endblock %} + +{%- block sidebarsearch %} +
+{{ super() }} +
+
+

Mailing list

+ joblib@librelist.com +

+ Send an email to subscribe

+
+
+{% endblock %} + diff --git a/testbed/joblib__joblib/doc/_templates/navigation.html b/testbed/joblib__joblib/doc/_templates/navigation.html new file mode 100644 index 0000000000000000000000000000000000000000..760dcc91ec4b9b21f9345485758127090ffee313 --- /dev/null +++ b/testbed/joblib__joblib/doc/_templates/navigation.html @@ -0,0 +1,10 @@ +

{{ _('Navigation') }}

+{{ toctree(includehidden=theme_sidebar_includehidden, collapse=theme_sidebar_collapse) }} +{% if theme_extra_nav_links %} +
+
    + {% for text, uri in theme_extra_nav_links.items() %} +
  • {{ text }}
  • + {% endfor %} +
+{% endif %} diff --git a/testbed/joblib__joblib/doc/conf.py b/testbed/joblib__joblib/doc/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..4b99e8db9162d7c359712b62154b188a0accca70 --- /dev/null +++ b/testbed/joblib__joblib/doc/conf.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# +# joblib documentation build configuration file, created by +# sphinx-quickstart on Thu Oct 23 16:36:51 2008. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# The contents of this file are pickled, so don't put values in the +# namespace that aren't pickleable (module imports are okay, +# they're removed automatically). +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +import joblib + +# If your extensions are in another directory, add it here. If the directory +# is relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +# sys.path.append(os.path.abspath('.')) + +# General configuration +# --------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. + +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.imgmath', 'numpydoc', + 'sphinx.ext.autosummary', 'sphinx.ext.coverage', + 'sphinx.ext.intersphinx', 'sphinx_gallery.gen_gallery'] + +autosummary_generate = True + +# intersphinx configuration +intersphinx_mapping = { + 'python': ('https://docs.python.org/{.major}'.format( + sys.version_info), None), + 'numpy': ('https://numpy.org/doc/stable/', None), + 'scipy': ('https://docs.scipy.org/doc/scipy', None), + 'distributed': ('https://distributed.dask.org/en/latest/', None), +} + +# sphinx-gallery configuration +sphinx_gallery_conf = { + 'default_thumb_file': '_static/joblib_logo_examples.png', + 'doc_module': 'joblib', + 'filename_pattern': '', + 'ignore_pattern': 'utils.py', + 'backreferences_dir': os.path.join('generated'), + 'reference_url': { + 'joblib': None} +} + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +# source_encoding = 'utf-8' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'joblib' +copyright = '2008-2021, Joblib developers' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = joblib.__version__ +# The full version, including alpha/beta/rc tags. +release = version + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of documents that shouldn't be included in the build. +# unused_docs = [] + +# List of directories, relative to source directory, that shouldn't be searched +# for source files. +exclude_trees = [] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# Avoid '+DOCTEST...' comments in the docs +trim_doctest_flags = True + +# Options for HTML output +# ----------------------- + +# The style sheet to use for HTML and HTML Help pages. A file of that name +# must exist either in Sphinx' static/ path, or in one of the custom paths +# given in html_static_path. +# html_style = 'default.css' + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +html_favicon = '_static/favicon.ico' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +html_sidebars = { + '**': [ + 'about.html', + 'navigation.html', + ] +} + + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_use_modindex = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, the reST sources are included in the HTML build as _sources/. +# html_copy_source = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = '' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'joblibdoc' + + +# Options for LaTeX output +# ------------------------ + +# The paper size ('letter' or 'a4'). +# latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +# latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, +# document class [howto/manual]). +latex_documents = [ + ('index', 'joblib.tex', 'joblib Documentation', + 'Gael Varoquaux', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# Additional stuff for the LaTeX preamble. +# latex_preamble = '' + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_use_modindex = True + +html_theme = 'alabaster' + +html_theme_options = { + 'logo': 'joblib_logo.svg', + 'github_repo': 'joblib/joblib', + 'github_button': 'true', + 'link': '#aa560c', + 'show_powered_by': 'false', + # "relbarbgcolor": "#333", + # "sidebarlinkcolor": "#e15617", + # "sidebarbgcolor": "#000", + # "sidebartextcolor": "#333", + # "footerbgcolor": "#111", + # "linkcolor": "#aa560c", + # "headtextcolor": "#643200", + # "codebgcolor": "#f5efe7", +} + + +############################################################################## +# Hack to copy the CHANGES.rst file +import shutil +try: + shutil.copyfile('../CHANGES.rst', 'CHANGES.rst') + shutil.copyfile('../README.rst', 'README.rst') +except IOError: + pass + # This fails during the testing, as the code is ran in a different + # directory + +numpydoc_show_class_members = False + +suppress_warnings = ['image.nonlocal_uri'] diff --git a/testbed/joblib__joblib/doc/conftest.py b/testbed/joblib__joblib/doc/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..db334633c6e74df088858458fc3cfc4c12bd71c9 --- /dev/null +++ b/testbed/joblib__joblib/doc/conftest.py @@ -0,0 +1,21 @@ +import faulthandler + +from joblib.parallel import mp +from joblib.test.common import np +from joblib.testing import skipif, fixture + + +@fixture(scope='module') +@skipif(np is None or mp is None, 'Numpy or Multiprocessing not available') +def parallel_numpy_fixture(request): + """Fixture to skip memmapping test if numpy or multiprocessing is not + installed""" + def setup(module): + faulthandler.dump_traceback_later(timeout=300, exit=True) + + def teardown(): + faulthandler.cancel_dump_traceback_later() + request.addfinalizer(teardown) + + return parallel_numpy_fixture + return setup diff --git a/testbed/joblib__joblib/doc/developing.rst b/testbed/joblib__joblib/doc/developing.rst new file mode 100644 index 0000000000000000000000000000000000000000..bab02e627bd53ef7573c45d5fe735be116f617e6 --- /dev/null +++ b/testbed/joblib__joblib/doc/developing.rst @@ -0,0 +1,9 @@ + +=============== +Development +=============== + +.. include:: README.rst + +.. include:: CHANGES.rst + diff --git a/testbed/joblib__joblib/doc/index.rst b/testbed/joblib__joblib/doc/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..d14d5a4359aa58067ed8da63b752a7fd7207e220 --- /dev/null +++ b/testbed/joblib__joblib/doc/index.rst @@ -0,0 +1,79 @@ +.. raw:: html + + + + +Joblib: running Python functions as pipeline jobs +================================================= + +Introduction +------------ + + +.. automodule:: joblib + + .. toctree:: + :maxdepth: 2 + :caption: User manual + + why.rst + installing.rst + memory.rst + parallel.rst + persistence.rst + auto_examples/index + developing.rst + +.. currentmodule:: joblib + +Module reference +---------------- + +.. autosummary:: + :toctree: generated/ + :template: class.rst + :caption: Module reference + + Memory + Parallel + parallel_config + +.. autosummary:: + :toctree: generated/ + :template: function.rst + + dump + load + hash + register_compressor + +Deprecated functionalities +-------------------------- + +.. autosummary:: + :toctree: generated/ + :template: class.rst + :caption: Deprecated functionalities + + parallel_backend \ No newline at end of file diff --git a/testbed/joblib__joblib/doc/installing.rst b/testbed/joblib__joblib/doc/installing.rst new file mode 100644 index 0000000000000000000000000000000000000000..1bca6961056391a4ffadf4196cfcc688c3c3b2e0 --- /dev/null +++ b/testbed/joblib__joblib/doc/installing.rst @@ -0,0 +1,63 @@ +Installing joblib +=================== + +Using `pip` +------------ + +You can use `pip` to install joblib: + +* For installing for all users, you need to run:: + + pip install joblib + + You may need to run the above command as administrator + + On a unix environment, it is better to install outside of the hierarchy + managed by the system:: + + pip install --prefix /usr/local joblib + +* Installing only for a specific user is easy if you use Python 2.7 or + above:: + + pip install --user joblib + +Using distributions +-------------------- + +Joblib is packaged for several linux distribution: archlinux, debian, +ubuntu, altlinux, and fedora. For minimum administration overhead, using the +package manager is the recommended installation strategy on these +systems. + +The manual way +--------------- + +To install joblib first download the latest tarball (follow the link on +the bottom of https://pypi.org/project/joblib/) and expand it. + +Installing in a local environment +.................................. + +If you don't need to install for all users, we strongly suggest that you +create a local environment and install `joblib` in it. One of the pros of +this method is that you never have to become administrator, and thus all +the changes are local to your account and easy to clean up. +Simply move to the directory created by expanding the `joblib` tarball +and run the following command:: + + python setup.py install --user + +Installing for all users +........................ + +If you have administrator rights and want to install for all users, all +you need to do is to go in directory created by expanding the `joblib` +tarball and run the following line:: + + python setup.py install + +If you are under Unix, we suggest that you install in '/usr/local' in +order not to interfere with your system:: + + python setup.py install --prefix /usr/local diff --git a/testbed/joblib__joblib/doc/memory.rst b/testbed/joblib__joblib/doc/memory.rst new file mode 100644 index 0000000000000000000000000000000000000000..37a889ea2ef594cb82cb0fdb48f2c5f597fa0e74 --- /dev/null +++ b/testbed/joblib__joblib/doc/memory.rst @@ -0,0 +1,513 @@ +.. + For doctests: + + >>> from joblib.testing import warnings_to_stdout + >>> warnings_to_stdout() + +.. _memory: + +=========================================== +On demand recomputing: the `Memory` class +=========================================== + +.. currentmodule:: joblib.memory + +Use case +-------- + +The :class:`~joblib.Memory` class defines a context for lazy evaluation of +function, by putting the results in a store, by default using a disk, and not +re-running the function twice for the same arguments. + +It works by explicitly saving the output to a file and it is designed to +work with non-hashable and potentially large input and output data types +such as numpy arrays. + +A simple example: +~~~~~~~~~~~~~~~~~ + + First, define the cache directory:: + + >>> cachedir = 'your_cache_location_directory' + + Then, instantiate a memory context that uses this cache directory:: + + >>> from joblib import Memory + >>> memory = Memory(cachedir, verbose=0) + + After these initial steps, just decorate a function to cache its output in + this context:: + + >>> @memory.cache + ... def f(x): + ... print('Running f(%s)' % x) + ... return x + + Calling this function twice with the same argument does not execute it the + second time, the output is just reloaded from a pickle file in the cache + directory:: + + >>> print(f(1)) + Running f(1) + 1 + >>> print(f(1)) + 1 + + However, calling the function with a different parameter executes it and + recomputes the output:: + + >>> print(f(2)) + Running f(2) + 2 + +Comparison with `memoize` +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The `memoize` decorator (https://code.activestate.com/recipes/52201/) +caches in memory all the inputs and outputs of a function call. It can +thus avoid running twice the same function, with a very small +overhead. However, it compares input objects with those in cache on each +call. As a result, for big objects there is a huge overhead. Moreover +this approach does not work with numpy arrays, or other objects subject +to non-significant fluctuations. Finally, using `memoize` with large +objects will consume all the memory, where with `Memory`, objects are +persisted to disk, using a persister optimized for speed and memory +usage (:func:`joblib.dump`). + +In short, `memoize` is best suited for functions with "small" input and +output objects, whereas `Memory` is best suited for functions with complex +input and output objects, and aggressive persistence to disk. + + +Using with `numpy` +------------------ + +The original motivation behind the `Memory` context was to have a +memoize-like pattern on numpy arrays. `Memory` uses fast cryptographic +hashing of the input arguments to check if they have been computed. + +An example +~~~~~~~~~~ + + Define two functions: the first with a number as an argument, + outputting an array, used by the second one. Both functions are decorated + with :meth:`Memory.cache `:: + + >>> import numpy as np + + >>> @memory.cache + ... def g(x): + ... print('A long-running calculation, with parameter %s' % x) + ... return np.hamming(x) + + >>> @memory.cache + ... def h(x): + ... print('A second long-running calculation, using g(x)') + ... return np.vander(x) + + If the function `h` is called with the array created by the same call to `g`, + `h` is not re-run:: + + >>> a = g(3) + A long-running calculation, with parameter 3 + >>> a + array([0.08, 1. , 0.08]) + >>> g(3) + array([0.08, 1. , 0.08]) + >>> b = h(a) + A second long-running calculation, using g(x) + >>> b2 = h(a) + >>> b2 + array([[0.0064, 0.08 , 1. ], + [1. , 1. , 1. ], + [0.0064, 0.08 , 1. ]]) + >>> np.allclose(b, b2) + True + + +Using memmapping +~~~~~~~~~~~~~~~~ + +Memmapping (memory mapping) speeds up cache looking when reloading large numpy +arrays:: + + >>> cachedir2 = 'your_cachedir2_location' + >>> memory2 = Memory(cachedir2, mmap_mode='r') + >>> square = memory2.cache(np.square) + >>> a = np.vander(np.arange(3)).astype(float) + >>> square(a) + ________________________________________________________________________________ + [Memory] Calling square... + square(array([[0., 0., 1.], + [1., 1., 1.], + [4., 2., 1.]])) + ___________________________________________________________square - ...min + memmap([[ 0., 0., 1.], + [ 1., 1., 1.], + [16., 4., 1.]]) + +.. note:: + + Notice the debug mode used in the above example. It is useful for + tracing of what is being reexecuted, and where the time is spent. + +If the `square` function is called with the same input argument, its +return value is loaded from the disk using memmapping:: + + >>> res = square(a) + >>> print(repr(res)) + memmap([[ 0., 0., 1.], + [ 1., 1., 1.], + [16., 4., 1.]]) + +.. + + The memmap file must be closed to avoid file locking on Windows; closing + numpy.memmap objects is done with del, which flushes changes to the disk + + >>> del res + +.. note:: + + If the memory mapping mode used was 'r', as in the above example, the + array will be read only, and will be impossible to modified in place. + + On the other hand, using 'r+' or 'w+' will enable modification of the + array, but will propagate these modification to the disk, which will + corrupt the cache. If you want modification of the array in memory, we + suggest you use the 'c' mode: copy on write. + + +Shelving: using references to cached values +------------------------------------------- + +In some cases, it can be useful to get a reference to the cached +result, instead of having the result itself. A typical example of this +is when a lot of large numpy arrays must be dispatched across several +workers: instead of sending the data themselves over the network, send +a reference to the joblib cache, and let the workers read the data +from a network filesystem, potentially taking advantage of some +system-level caching too. + +Getting a reference to the cache can be done using the +`call_and_shelve` method on the wrapped function:: + + >>> result = g.call_and_shelve(4) + A long-running calculation, with parameter 4 + >>> result #doctest: +ELLIPSIS + MemorizedResult(location="...", func="...g...", args_id="...") + +Once computed, the output of `g` is stored on disk, and deleted from +memory. Reading the associated value can then be performed with the +`get` method:: + + >>> result.get() + array([0.08, 0.77, 0.77, 0.08]) + +The cache for this particular value can be cleared using the `clear` +method. Its invocation causes the stored value to be erased from disk. +Any subsequent call to `get` will cause a `KeyError` exception to be +raised:: + + >>> result.clear() + >>> result.get() #doctest: +SKIP + Traceback (most recent call last): + ... + KeyError: 'Non-existing cache value (may have been cleared).\nFile ... does not exist' + +A `MemorizedResult` instance contains all that is necessary to read +the cached value. It can be pickled for transmission or storage, and +the printed representation can even be copy-pasted to a different +python interpreter. + +.. topic:: Shelving when cache is disabled + + In the case where caching is disabled (e.g. + `Memory(None)`), the `call_and_shelve` method returns a + `NotMemorizedResult` instance, that stores the full function + output, instead of just a reference (since there is nothing to + point to). All the above remains valid though, except for the + copy-pasting feature. + + +Gotchas +------- + +* **Across sessions, function cache is identified by the function's name**. + Thus assigning the same name to different functions, their cache will + override each-others (e.g. there are 'name collisions'), and unwanted re-run + will happen:: + + >>> @memory.cache + ... def func(x): + ... print('Running func(%s)' % x) + + >>> func2 = func + + >>> @memory.cache + ... def func(x): + ... print('Running a different func(%s)' % x) + + As long as the same session is used, there are no collisions (in joblib + 0.8 and above), although joblib does warn you that you are doing something + dangerous:: + + >>> func(1) + Running a different func(1) + + >>> # FIXME: The next line should create a JolibCollisionWarning but does not + >>> # memory.rst:0: JobLibCollisionWarning: Possible name collisions between functions 'func' (:...) and 'func' (:...) + >>> func2(1) #doctest: +ELLIPSIS + Running func(1) + + >>> func(1) # No recomputation so far + >>> func2(1) # No recomputation so far + + .. + Empty the in-memory cache to simulate exiting and reloading the + interpreter + + >>> import joblib.memory + >>> joblib.memory._FUNCTION_HASHES.clear() + + But suppose the interpreter is exited and then restarted, the cache will not + be identified properly, and the functions will be rerun:: + + >>> # FIXME: The next line will should create a JoblibCollisionWarning but does not. Also it is skipped because it does not produce any output + >>> # memory.rst:0: JobLibCollisionWarning: Possible name collisions between functions 'func' (:...) and 'func' (:...) + >>> func(1) #doctest: +ELLIPSIS +SKIP + Running a different func(1) + >>> func2(1) #doctest: +ELLIPSIS +SKIP + Running func(1) + + As long as the same session is used, there are no needless + recomputation:: + + >>> func(1) # No recomputation now + >>> func2(1) # No recomputation now + +* **lambda functions** + + Beware that with Python 2.7 lambda functions cannot be separated out:: + + >>> def my_print(x): + ... print(x) + + >>> f = memory.cache(lambda : my_print(1)) + >>> g = memory.cache(lambda : my_print(2)) + + >>> f() + 1 + >>> f() + >>> g() # doctest: +SKIP + memory.rst:0: JobLibCollisionWarning: Cannot detect name collisions for function '' + 2 + >>> g() # doctest: +SKIP + >>> f() # doctest: +SKIP + 1 + +* **memory cannot be used on some complex objects**, e.g. a callable + object with a `__call__` method. + + However, it works on numpy ufuncs:: + + >>> sin = memory.cache(np.sin) + >>> print(sin(0)) + 0.0 + +* **caching methods: memory is designed for pure functions and it is + not recommended to use it for methods**. If one wants to use cache + inside a class the recommended pattern is to cache a pure function + and use the cached function inside your class, i.e. something like + this:: + + @memory.cache + def compute_func(arg1, arg2, arg3): + # long computation + return result + + + class Foo(object): + def __init__(self, args): + self.data = None + + def compute(self): + self.data = compute_func(self.arg1, self.arg2, 40) + + + Using ``Memory`` for methods is not recommended and has some caveats + that make it very fragile from a maintenance point of view because + it is very easy to forget about these caveats when a software + evolves. If this cannot be avoided (we would be interested about + your use case by the way), here are a few known caveats: + + 1. a method cannot be decorated at class definition, + because when the class is instantiated, the first argument (self) is + *bound*, and no longer accessible to the `Memory` object. The + following code won't work:: + + class Foo(object): + + @memory.cache # WRONG + def method(self, args): + pass + + The right way to do this is to decorate at instantiation time:: + + class Foo(object): + + def __init__(self, args): + self.method = memory.cache(self.method) + + def method(self, ...): + pass + + 2. The cached method will have ``self`` as one of its + arguments. That means that the result will be recomputed if + anything with ``self`` changes. For example if ``self.attr`` has + changed calling ``self.method`` will recompute the result even if + ``self.method`` does not use ``self.attr`` in its body. Another + example is changing ``self`` inside the body of + ``self.method``. The consequence is that ``self.method`` will + create cache that will not be reused in subsequent calls. To + alleviate these problems and if you *know* that the result of + ``self.method`` does not depend on ``self`` you can use + ``self.method = memory.cache(self.method, ignore=['self'])``. + +* **joblib cache entries may be invalidated after environment updates**. + Values returned by :func:`joblib.hash` are not guaranteed to stay + constant across ``joblib`` versions. This means that **all** entries of a + :class:`Memory` cache can get invalidated when upgrading ``joblib``. + Invalidation can also happen when upgrading a third party library (such as + ``numpy``): in such a case, only the cached function calls with parameters + that are constructs (or contain references to constructs) defined in the + upgraded library should potentially be invalidated after the upgrade. + + +Ignoring some arguments +----------------------- + +It may be useful not to recalculate a function when certain arguments +change, for instance a debug flag. :class:`Memory` provides the ``ignore`` +list:: + + >>> @memory.cache(ignore=['debug']) + ... def my_func(x, debug=True): + ... print('Called with x = %s' % x) + >>> my_func(0) + Called with x = 0 + >>> my_func(0, debug=False) + >>> my_func(0, debug=True) + >>> # my_func was not reevaluated + + +Custom cache validation +----------------------- + +In some cases, external factors can invalidate the cached results and +one wants to have more control on whether to reuse a result or not. + +This is for instance the case if the results depends on database records +that change over time: a small delay in the updates might be tolerable +but after a while, the results might be invalid. + +One can have a finer control on the cache validity specifying a function +via ``cache_validation_callback`` in :meth:`~joblib.Memory.cache`. For +instance, one can only cache results that take more than 1s to be computed. + + >>> import time + >>> def cache_validation_cb(metadata): + ... # Only retrieve cached results for calls that take more than 1s + ... return metadata['duration'] > 1 + + >>> @memory.cache(cache_validation_callback=cache_validation_cb) + ... def my_func(delay=0): + ... time.sleep(delay) + ... print(f'Called with {delay}s delay') + + >>> my_func() + Called with 0s delay + >>> my_func(1.1) + Called with 1.1s delay + >>> my_func(1.1) # This result is retrieved from cache + >>> my_func() # This one is not and the call is repeated + Called with 0s delay + +``cache_validation_cb`` will be called with a single argument containing +the metadata of the cached call as a dictionary containing the following +keys: + + - ``duration``: the duration of the function call, + - ``time``: the timestamp when the cache called has been recorded + - ``input_args``: a dictionary of keywords arguments for the cached function call. + +Note a validity duration for cached results can be defined via +:func:`joblib.expires_after` by providing similar with arguments similar to the +ones of a ``datetime.timedelta``: + + >>> from joblib import expires_after + >>> @memory.cache(cache_validation_callback=expires_after(seconds=0.5)) + ... def my_func(): + ... print(f'Function run') + >>> my_func() + Function run + >>> my_func() + >>> time.sleep(0.5) + >>> my_func() + Function run + + +.. _memory_reference: + +Reference documentation of the :class:`~joblib.Memory` class +------------------------------------------------------------ + +.. autoclass:: joblib.Memory + :members: __init__, cache, eval, clear, reduce_size, format + :no-inherited-members: + :noindex: + +Useful methods of decorated functions +------------------------------------- + +Functions decorated by :meth:`Memory.cache ` are +:class:`MemorizedFunc` +objects that, in addition of behaving like normal functions, expose +methods useful for cache exploration and management. For example, you can +use :meth:`func.check_call_in_cache ` to +check if a cache hit will occur for a decorated ``func`` given a set of inputs +without actually needing to call the function itself:: + + >>> @memory.cache + ... def func(x): + ... print('Running func(%s)' % x) + ... return x + >>> type(func) + + >>> func(1) + Running func(1) + 1 + >>> func.check_call_in_cache(1) # cache hit + True + >>> func.check_call_in_cache(2) # cache miss + False + +.. autoclass:: MemorizedFunc + :members: __init__, call, clear, check_call_in_cache + + +.. + Let us not forget to clean our cache dir once we are finished:: + + >>> import shutil + >>> try: + ... shutil.rmtree(cachedir) + ... shutil.rmtree(cachedir2) + ... except OSError: + ... pass # this can sometimes fail under Windows + + +Helper Reference +~~~~~~~~~~~~~~~~ + +.. autofunction:: joblib.expires_after diff --git a/testbed/joblib__joblib/doc/parallel.rst b/testbed/joblib__joblib/doc/parallel.rst new file mode 100644 index 0000000000000000000000000000000000000000..d288fad8c6754209aeeefa045e211e773fbf9026 --- /dev/null +++ b/testbed/joblib__joblib/doc/parallel.rst @@ -0,0 +1,421 @@ + +.. _parallel: + +================================= +Embarrassingly parallel for loops +================================= + +Common usage +============ + +Joblib provides a simple helper class to write parallel for loops using +multiprocessing. The core idea is to write the code to be executed as a +generator expression, and convert it to parallel computing:: + + >>> from math import sqrt + >>> [sqrt(i ** 2) for i in range(10)] + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + +can be spread over 2 CPUs using the following:: + + >>> from math import sqrt + >>> from joblib import Parallel, delayed + >>> Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10)) + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + +The output can be a generator that yields the results as soon as they're +available, even if the subsequent tasks aren't completed yet. The order +of the outputs always matches the order the inputs have been submitted with:: + + >>> from math import sqrt + >>> from joblib import Parallel, delayed + >>> parallel = Parallel(n_jobs=2, return_as="generator") + >>> output_generator = parallel(delayed(sqrt)(i ** 2) for i in range(10)) + >>> print(type(output_generator)) + + >>> print(next(output_generator)) + 0.0 + >>> print(next(output_generator)) + 1.0 + >>> print(list(output_generator)) + [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + +This generator enables reducing the memory footprint of +:class:`joblib.Parallel` calls in case the results can benefit from on-the-fly +aggregation, as illustrated in +:ref:`sphx_glr_auto_examples_parallel_generator.py`. + +Future releases are planned to also support returning a generator that yields +the results in the order of completion rather than the order of submission, by +using ``return_as="unordered_generator"`` instead of ``return_as="generator"``. +In this case the order of the outputs will depend on the concurrency of workers +and will not be guaranteed to be deterministic, meaning the results can be +yielded with a different order every time the code is executed. + +Thread-based parallelism vs process-based parallelism +===================================================== + +By default :class:`joblib.Parallel` uses the ``'loky'`` backend module to start +separate Python worker processes to execute tasks concurrently on +separate CPUs. This is a reasonable default for generic Python programs +but can induce a significant overhead as the input and output data need +to be serialized in a queue for communication with the worker processes (see +:ref:`serialization_and_processes`). + +When you know that the function you are calling is based on a compiled +extension that releases the Python Global Interpreter Lock (GIL) during +most of its computation then it is more efficient to use threads instead +of Python processes as concurrent workers. For instance this is the case +if you write the CPU intensive part of your code inside a `with nogil`_ +block of a Cython function. + +.. _`with nogil`: https://docs.cython.org/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil + +To hint that your code can efficiently use threads, just pass +``prefer="threads"`` as parameter of the :class:`joblib.Parallel` constructor. +In this case joblib will automatically use the ``"threading"`` backend +instead of the default ``"loky"`` backend: + + >>> Parallel(n_jobs=2, prefer="threads")( + ... delayed(sqrt)(i ** 2) for i in range(10)) + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + +The :func:`~joblib.parallel_config` context manager helps selecting +a specific backend implementation or setting the default number of jobs: + + >>> from joblib import parallel_config + >>> with parallel_config(backend='threading', n_jobs=2): + ... Parallel()(delayed(sqrt)(i ** 2) for i in range(10)) + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + +The latter is especially useful when calling a library that uses +:class:`joblib.Parallel` internally without exposing backend selection as +part of its public API. + +Note that the ``prefer="threads"`` option was introduced in joblib 0.12. +In prior versions, the same effect could be achieved by hardcoding a +specific backend implementation such as ``backend="threading"`` in the +call to :class:`joblib.Parallel` but this is now considered a bad pattern +(when done in a library) as it does not make it possible to override that +choice with the :func:`~joblib.parallel_config` context manager. + + +.. topic:: The loky backend may not always be available + + Some rare systems do not support multiprocessing (for instance + Pyodide). In this case the loky backend is not available and the + default backend falls back to threading. + +In addition to the builtin joblib backends, there are several cluster-specific +backends you can use: + +* `Dask `_ backend for Dask clusters + (see :ref:`sphx_glr_auto_examples_parallel_distributed_backend_simple.py` for an example), +* `Ray `_ backend for Ray clusters, +* `Joblib Apache Spark Backend `_ + to distribute joblib tasks on a Spark cluster. + +.. _serialization_and_processes: + +Serialization & Processes +========================= + +To share function definition across multiple python processes, it is necessary to rely on a serialization protocol. The standard protocol in python is :mod:`pickle` but its default implementation in the standard library has several limitations. For instance, it cannot serialize functions which are defined interactively or in the :code:`__main__` module. + +To avoid this limitation, the ``loky`` backend now relies on |cloudpickle| to serialize python objects. |cloudpickle| is an alternative implementation of the pickle protocol which allows the serialization of a greater number of objects, in particular interactively defined functions. So for most usages, the loky ``backend`` should work seamlessly. + + +The main drawback of |cloudpickle| is that it can be slower than the :mod:`pickle` module in the standard library. In particular, it is critical for large python dictionaries or lists, where the serialization time can be up to 100 times slower. There is two ways to alter the serialization process for the ``joblib`` to temper this issue: + +- If you are on an UNIX system, you can switch back to the old ``multiprocessing`` backend. With this backend, interactively defined functions can be shared with the worker processes using the fast :mod:`pickle`. The main issue with this solution is that using ``fork`` to start the process breaks the standard POSIX and can have weird interaction with third party libraries such as ``numpy`` and ``openblas``. + +- If you wish to use the ``loky`` backend with a different serialization library, you can set the ``LOKY_PICKLER=mod_pickle`` environment variable to use the ``mod_pickle`` as the serialization library for ``loky``. The module ``mod_pickle`` passed as an argument should be importable as ``import mod_pickle`` and should contain a ``Pickler`` object, which will be used to serialize to objects. It can be set to ``LOKY_PICKLER=pickle`` to use the pickling module from stdlib. The main drawback with ``LOKY_PICKLER=pickle`` is that interactively defined functions will not be serializable anymore. To cope with this, you can use this solution together with the :func:`joblib.wrap_non_picklable_objects` wrapper, which can be used as a decorator to locally enable using |cloudpickle| for specific objects. This way, you can have fast pickling of all python objects and locally enable slow pickling for interactive functions. An example is given in loky_wrapper_. + +.. |cloudpickle| raw:: html + + cloudpickle + +.. _loky_wrapper: auto_examples/serialization_and_wrappers.html + + +Shared-memory semantics +======================= + +The default backend of joblib will run each function call in isolated +Python processes, therefore they cannot mutate a common Python object +defined in the main program. + +However if the parallel function really needs to rely on the shared +memory semantics of threads, it should be made explicit with +``require='sharedmem'``, for instance: + + >>> shared_set = set() + >>> def collect(x): + ... shared_set.add(x) + ... + >>> Parallel(n_jobs=2, require='sharedmem')( + ... delayed(collect)(i) for i in range(5)) + [None, None, None, None, None] + >>> sorted(shared_set) + [0, 1, 2, 3, 4] + +Keep in mind that relying a on the shared-memory semantics is probably +suboptimal from a performance point of view as concurrent access to a +shared Python object will suffer from lock contention. + +Reusing a pool of workers +========================= + +Some algorithms require to make several consecutive calls to a parallel +function interleaved with processing of the intermediate results. Calling +:class:`joblib.Parallel` several times in a loop is sub-optimal because it will +create and destroy a pool of workers (threads or processes) several times which +can cause a significant overhead. + +For this case it is more efficient to use the context manager API of the +:class:`joblib.Parallel` class to re-use the same pool of workers for several +calls to the :class:`joblib.Parallel` object:: + + >>> with Parallel(n_jobs=2) as parallel: + ... accumulator = 0. + ... n_iter = 0 + ... while accumulator < 1000: + ... results = parallel(delayed(sqrt)(accumulator + i ** 2) + ... for i in range(5)) + ... accumulator += sum(results) # synchronization barrier + ... n_iter += 1 + ... + >>> (accumulator, n_iter) # doctest: +ELLIPSIS + (1136.596..., 14) + +Note that the ``'loky'`` backend now used by default for process-based +parallelism automatically tries to maintain and reuse a pool of workers +by it-self even for calls without the context manager. + +.. include:: parallel_numpy.rst + + +Avoiding over-subscription of CPU resources +============================================ + +The computation parallelism relies on the usage of multiple CPUs to perform the +operation simultaneously. When using more processes than the number of CPU on +a machine, the performance of each process is degraded as there is less +computational power available for each process. Moreover, when many processes +are running, the time taken by the OS scheduler to switch between them can +further hinder the performance of the computation. It is generally better to +avoid using significantly more processes or threads than the number of CPUs on +a machine. + +Some third-party libraries -- *e.g.* the BLAS runtime used by ``numpy`` -- +internally manage a thread-pool to perform their computations. The default +behavior is generally to use a number of threads equals to the number of CPUs +available. When these libraries are used with :class:`joblib.Parallel`, each +worker will spawn its own thread-pools, resulting in a massive over-subscription +of resources that can slow down the computation compared to a sequential +one. To cope with this problem, joblib tells supported third-party libraries +to use a limited number of threads in workers managed by the ``'loky'`` +backend: by default each worker process will have environment variables set to +allow a maximum of ``cpu_count() // n_jobs`` so that the total number of +threads used by all the workers does not exceed the number of CPUs of the +host. + +This behavior can be overridden by setting the proper environment variables to +the desired number of threads. This override is supported for the following +libraries: + + - OpenMP with the environment variable ``'OMP_NUM_THREADS'``, + - OpenBLAS with the ``'OPENBLAS_NUM_THREADS'``, + - MKL with the environment variable ``'MKL_NUM_THREADS'``, + - Accelerated with the environment variable ``'VECLIB_MAXIMUM_THREADS'``, + - Numexpr with the environment variable ``'NUMEXPR_NUM_THREADS'``. + +Since joblib 0.14, it is also possible to programmatically override the default +number of threads using the ``inner_max_num_threads`` argument of the +:func:`~joblib.parallel_config` function as follows: + +.. code-block:: python + + from joblib import Parallel, delayed, parallel_config + + with parallel_config(backend="loky", inner_max_num_threads=2): + results = Parallel(n_jobs=4)(delayed(func)(x, y) for x, y in data) + +In this example, 4 Python worker processes will be allowed to use 2 threads +each, meaning that this program will be able to use up to 8 CPUs concurrently. + + +Custom backend API +================== + +.. versionadded:: 0.10 + +User can provide their own implementation of a parallel processing +backend in addition to the ``'loky'``, ``'threading'``, +``'multiprocessing'`` backends provided by default. A backend is +registered with the :func:`joblib.register_parallel_backend` function by +passing a name and a backend factory. + +The backend factory can be any callable that returns an instance of +``ParallelBackendBase``. Please refer to the `default backends source code`_ as +a reference if you want to implement your own custom backend. + +.. _`default backends source code`: https://github.com/joblib/joblib/blob/master/joblib/_parallel_backends.py + +Note that it is possible to register a backend class that has some mandatory +constructor parameters such as the network address and connection credentials +for a remote cluster computing service:: + + class MyCustomBackend(ParallelBackendBase): + + def __init__(self, endpoint, api_key): + self.endpoint = endpoint + self.api_key = api_key + + ... + # Do something with self.endpoint and self.api_key somewhere in + # one of the method of the class + + register_parallel_backend('custom', MyCustomBackend) + +The connection parameters can then be passed to the +:func:`~joblib.parallel_config` context manager:: + + with parallel_config(backend='custom', endpoint='http://compute', + api_key='42'): + Parallel()(delayed(some_function)(i) for i in range(10)) + +Using the context manager can be helpful when using a third-party library that +uses :class:`joblib.Parallel` internally while not exposing the ``backend`` +argument in its own API. + + +A problem exists that external packages that register new parallel backends +must now be imported explicitly for their backends to be identified by joblib:: + + >>> import joblib + >>> with joblib.parallel_config(backend='custom'): # doctest: +SKIP + ... ... # this fails + KeyError: 'custom' + + # Import library to register external backend + >>> import my_custom_backend_library # doctest: +SKIP + >>> with joblib.parallel_config(backend='custom'): # doctest: +SKIP + ... ... # this works + +This can be confusing for users. To resolve this, external packages can +safely register their backends directly within the joblib codebase by creating +a small function that registers their backend, and including this function +within the ``joblib.parallel.EXTERNAL_PACKAGES`` dictionary:: + + def _register_custom(): + try: + import my_custom_library + except ImportError: + raise ImportError("an informative error message") + + EXTERNAL_BACKENDS['custom'] = _register_custom + +This is subject to community review, but can reduce the confusion for users +when relying on side effects of external package imports. + + +Old multiprocessing backend +=========================== + +Prior to version 0.12, joblib used the ``'multiprocessing'`` backend as +default backend instead of ``'loky'``. + +This backend creates an instance of `multiprocessing.Pool` that forks +the Python interpreter in multiple processes to execute each of the +items of the list. The `delayed` function is a simple trick to be able +to create a tuple `(function, args, kwargs)` with a function-call +syntax. + +.. warning:: + + Under Windows, the use of ``multiprocessing.Pool`` requires to + protect the main loop of code to avoid recursive spawning of + subprocesses when using :class:`joblib.Parallel`. In other words, you + should be writing code like this when using the ``'multiprocessing'`` + backend: + + .. code-block:: python + + import .... + + def function1(...): + ... + + def function2(...): + ... + + ... + if __name__ == '__main__': + # do stuff with imports and functions defined about + ... + + **No** code should *run* outside of the ``"if __name__ == + '__main__'"`` blocks, only imports and definitions. + + The ``'loky'`` backend used by default in joblib 0.12 and later does + not impose this anymore. + + +Bad interaction of multiprocessing and third-party libraries +============================================================ + +Using the ``'multiprocessing'`` backend can cause a crash when using +third party libraries that manage their own native thread-pool if the +library is first used in the main process and subsequently called again +in a worker process (inside the :class:`joblib.Parallel` call). + +Joblib version 0.12 and later are no longer subject to this problem +thanks to the use of `loky `_ as the +new default backend for process-based parallelism. + +Prior to Python 3.4 the ``'multiprocessing'`` backend of joblib can only +use the ``fork`` strategy to create worker processes under non-Windows +systems. This can cause some third-party libraries to crash or freeze. +Such libraries include Apple vecLib / Accelerate (used by NumPy under +OSX), some old version of OpenBLAS (prior to 0.2.10) or the OpenMP +runtime implementation from GCC which is used internally by third-party +libraries such as XGBoost, spaCy, OpenCV... + +The best way to avoid this problem is to use the ``'loky'`` backend +instead of the ``multiprocessing`` backend. Prior to joblib 0.12, it is +also possible to get :class:`joblib.Parallel` configured to use the +``'forkserver'`` start method on Python 3.4 and later. The start method +has to be configured by setting the ``JOBLIB_START_METHOD`` environment +variable to ``'forkserver'`` instead of the default ``'fork'`` start +method. However the user should be aware that using the ``'forkserver'`` +method prevents :class:`joblib.Parallel` to call function interactively +defined in a shell session. + +You can read more on this topic in the `multiprocessing documentation +`_. + +Under Windows the ``fork`` system call does not exist at all so this problem +does not exist (but multiprocessing has more overhead). + + +`Parallel` reference documentation +================================== + +.. autoclass:: joblib.Parallel + :members: dispatch_next, dispatch_one_batch, format, print_progress + :no-inherited-members: + :noindex: + +.. autofunction:: joblib.delayed + +.. autofunction:: joblib.parallel_config + :noindex: + +.. autofunction:: joblib.wrap_non_picklable_objects + +.. autofunction:: joblib.register_parallel_backend + +.. autoclass:: joblib.parallel.ParallelBackendBase + +.. autoclass:: joblib.parallel.AutoBatchingMixin \ No newline at end of file diff --git a/testbed/joblib__joblib/doc/parallel_numpy.rst b/testbed/joblib__joblib/doc/parallel_numpy.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c449906abab874a9d01c931d6bd340ac358d666 --- /dev/null +++ b/testbed/joblib__joblib/doc/parallel_numpy.rst @@ -0,0 +1,172 @@ +.. + For doctests: + + >>> import sys + >>> setup = getfixture('parallel_numpy_fixture') + >>> fixture = setup(sys.modules[__name__]) + +Working with numerical data in shared memory (memmapping) +========================================================= + +By default the workers of the pool are real Python processes forked using the +``multiprocessing`` module of the Python standard library when ``n_jobs != 1``. +The arguments passed as input to the ``Parallel`` call are serialized and +reallocated in the memory of each worker process. + +This can be problematic for large arguments as they will be reallocated +``n_jobs`` times by the workers. + +As this problem can often occur in scientific computing with ``numpy`` +based datastructures, :class:`joblib.Parallel` provides a special +handling for large arrays to automatically dump them on the filesystem +and pass a reference to the worker to open them as memory map +on that file using the ``numpy.memmap`` subclass of ``numpy.ndarray``. +This makes it possible to share a segment of data between all the +worker processes. + +.. note:: + + The following only applies with the ``"loky"` and + ``'multiprocessing'`` process-backends. If your code can release the + GIL, then using a thread-based backend by passing + ``prefer='threads'`` is even more efficient because it makes it + possible to avoid the communication overhead of process-based + parallelism. + + Scientific Python libraries such as numpy, scipy, pandas and + scikit-learn often release the GIL in performance critical code paths. + It is therefore advised to always measure the speed of thread-based + parallelism and use it when the scalability is not limited by the GIL. + + +Automated array to memmap conversion +------------------------------------ + +The automated array to memmap conversion is triggered by a configurable +threshold on the size of the array:: + + >>> import numpy as np + >>> from joblib import Parallel, delayed + >>> def is_memmap(obj): + ... return isinstance(obj, np.memmap) + + >>> Parallel(n_jobs=2, max_nbytes=1e6)( + ... delayed(is_memmap)(np.ones(int(i))) + ... for i in [1e2, 1e4, 1e6]) + [False, False, True] + +By default the data is dumped to the ``/dev/shm`` shared-memory partition if it +exists and is writable (typically the case under Linux). Otherwise the +operating system's temporary folder is used. The location of the temporary data +files can be customized by passing a ``temp_folder`` argument to the +``Parallel`` constructor. + +Passing ``max_nbytes=None`` makes it possible to disable the automated array to +memmap conversion. + + +Manual management of memmapped input data +----------------------------------------- + +For even finer tuning of the memory usage it is also possible to +dump the array as a memmap directly from the parent process to +free the memory before forking the worker processes. For instance +let's allocate a large array in the memory of the parent process:: + + >>> large_array = np.ones(int(1e6)) + +Dump it to a local file for memmapping:: + + >>> import tempfile + >>> import os + >>> from joblib import load, dump + + >>> temp_folder = tempfile.mkdtemp() + >>> filename = os.path.join(temp_folder, 'joblib_test.mmap') + >>> if os.path.exists(filename): os.unlink(filename) + >>> _ = dump(large_array, filename) + >>> large_memmap = load(filename, mmap_mode='r+') + +The ``large_memmap`` variable is pointing to a ``numpy.memmap`` +instance:: + + >>> large_memmap.__class__.__name__, large_array.nbytes, large_array.shape + ('memmap', 8000000, (1000000,)) + + >>> np.allclose(large_array, large_memmap) + True + +The original array can be freed from the main process memory:: + + >>> del large_array + >>> import gc + >>> _ = gc.collect() + +It is possible to slice ``large_memmap`` into a smaller memmap:: + + >>> small_memmap = large_memmap[2:5] + >>> small_memmap.__class__.__name__, small_memmap.nbytes, small_memmap.shape + ('memmap', 24, (3,)) + +Finally a ``np.ndarray`` view backed on that same memory mapped file can be +used:: + + >>> small_array = np.asarray(small_memmap) + >>> small_array.__class__.__name__, small_array.nbytes, small_array.shape + ('ndarray', 24, (3,)) + +All those three datastructures point to the same memory buffer and +this same buffer will also be reused directly by the worker processes +of a ``Parallel`` call:: + + >>> Parallel(n_jobs=2, max_nbytes=None)( + ... delayed(is_memmap)(a) + ... for a in [large_memmap, small_memmap, small_array]) + [True, True, True] + +Note that here ``max_nbytes=None`` is used to disable the auto-dumping +feature of ``Parallel``. ``small_array`` is still in shared memory in the +worker processes because it was already backed by shared memory in the +parent process. +The pickling machinery of ``Parallel`` multiprocessing queues are +able to detect this situation and optimize it on the fly to limit +the number of memory copies. + + +Writing parallel computation results in shared memory +----------------------------------------------------- + +If data are opened using the ``w+`` or ``r+`` mode in the main program, the +worker will get ``r+`` mode access. Thus the worker will be able to write +its results directly to the original data, alleviating the need of the +serialization to send back the results to the parent process. + +Here is an example script on parallel processing with preallocated +``numpy.memmap`` datastructures +:ref:`sphx_glr_auto_examples_parallel_memmap.py`. + +.. warning:: + + Having concurrent workers write on overlapping shared memory data segments, + for instance by using inplace operators and assignments on a `numpy.memmap` + instance, can lead to data corruption as numpy does not offer atomic + operations. The previous example does not risk that issue as each task is + updating an exclusive segment of the shared result array. + + Some C/C++ compilers offer lock-free atomic primitives such as add-and-fetch + or compare-and-swap that could be exposed to Python via CFFI_ for instance. + However providing numpy-aware atomic constructs is outside of the scope + of the joblib project. + + +.. _CFFI: https://cffi.readthedocs.org + + +A final note: don't forget to clean up any temporary folder when you are done +with the computation:: + + >>> import shutil + >>> try: + ... shutil.rmtree(temp_folder) + ... except OSError: + ... pass # this can sometimes fail under Windows diff --git a/testbed/joblib__joblib/doc/persistence.rst b/testbed/joblib__joblib/doc/persistence.rst new file mode 100644 index 0000000000000000000000000000000000000000..d881d8311a364e13ac25b8bcb63de9dc6ec59a2b --- /dev/null +++ b/testbed/joblib__joblib/doc/persistence.rst @@ -0,0 +1,194 @@ +.. _persistence: + +=========== +Persistence +=========== + +.. currentmodule:: joblib.numpy_pickle + +Use case +======== + +:func:`joblib.dump` and :func:`joblib.load` provide a replacement for +pickle to work efficiently on arbitrary Python objects containing large data, +in particular large numpy arrays. + +.. warning:: + + :func:`joblib.dump` and :func:`joblib.load` are based on the Python pickle + serialization model, which means that arbitrary Python code can be executed + when loading a serialized object with :func:`joblib.load`. + + :func:`joblib.load` should therefore never be used to load objects from an + untrusted source or otherwise you will introduce a security vulnerability in + your program. + +.. note:: + + As of Python 3.8 and numpy 1.16, pickle protocol 5 introduced in + `PEP 574 `_ supports efficient + serialization and de-serialization for large data buffers natively using + the standard library:: + + pickle.dump(large_object, fileobj, protocol=5) + + +A simple example +================ + +First create a temporary directory:: + + >>> from tempfile import mkdtemp + >>> savedir = mkdtemp() + >>> import os + >>> filename = os.path.join(savedir, 'test.joblib') + +Then create an object to be persisted:: + + >>> import numpy as np + >>> to_persist = [('a', [1, 2, 3]), ('b', np.arange(10))] + +which is saved into `filename`:: + + >>> import joblib + >>> joblib.dump(to_persist, filename) # doctest: +ELLIPSIS + ['...test.joblib'] + +The object can then be reloaded from the file:: + + >>> joblib.load(filename) + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + + +Persistence in file objects +=========================== + +Instead of filenames, :func:`joblib.dump` and :func:`joblib.load` functions +also accept file objects: + + >>> with open(filename, 'wb') as fo: # doctest: +ELLIPSIS + ... joblib.dump(to_persist, fo) + >>> with open(filename, 'rb') as fo: # doctest: +ELLIPSIS + ... joblib.load(fo) + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + + +Compressed joblib pickles +========================= + +Setting the `compress` argument to `True` in :func:`joblib.dump` will allow to +save space on disk: + + >>> joblib.dump(to_persist, filename + '.compressed', compress=True) # doctest: +ELLIPSIS + ['...test.joblib.compressed'] + +If the filename extension corresponds to one of the supported compression +methods, the compressor will be used automatically: + + >>> joblib.dump(to_persist, filename + '.z') # doctest: +ELLIPSIS + ['...test.joblib.z'] + +By default, :func:`joblib.dump` uses the zlib compression method as it gives +the best tradeoff between speed and disk space. The other supported compression +methods are 'gzip', 'bz2', 'lzma' and 'xz': + + >>> # Dumping in a gzip compressed file using a compress level of 3. + >>> joblib.dump(to_persist, filename + '.gz', compress=('gzip', 3)) # doctest: +ELLIPSIS + ['...test.joblib.gz'] + >>> joblib.load(filename + '.gz') + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + >>> joblib.dump(to_persist, filename + '.bz2', compress=('bz2', 3)) # doctest: +ELLIPSIS + ['...test.joblib.bz2'] + >>> joblib.load(filename + '.bz2') + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + +The ``compress`` parameter of the :func:`joblib.dump` function also accepts a +string corresponding to the name of the compressor used. When using this, the +default compression level is used by the compressor: + + >>> joblib.dump(to_persist, filename + '.gz', compress='gzip') # doctest: +ELLIPSIS + ['...test.joblib.gz'] + +.. note:: + + Lzma and Xz compression methods are only available for python versions >= 3.3. + +Compressor files provided by the python standard library can also be used to +compress pickle, e.g ``gzip.GzipFile``, ``bz2.BZ2File``, ``lzma.LZMAFile``: + + >>> # Dumping in a gzip.GzipFile object using a compression level of 3. + >>> import gzip + >>> with gzip.GzipFile(filename + '.gz', 'wb', compresslevel=3) as fo: # doctest: +ELLIPSIS + ... joblib.dump(to_persist, fo) + >>> with gzip.GzipFile(filename + '.gz', 'rb') as fo: # doctest: +ELLIPSIS + ... joblib.load(fo) + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + +If the ``lz4`` package is installed, this compression method is automatically +available with the dump function. + + >>> joblib.dump(to_persist, filename + '.lz4') # doctest: +ELLIPSIS + ['...test.joblib.lz4'] + >>> joblib.load(filename + '.lz4') + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + +.. note:: + + LZ4 compression is only available with python major versions >= 3 + +More details can be found in the :func:`joblib.dump` and +:func:`joblib.load` documentation. + +Registering extra compressors +----------------------------- + +Joblib provides :func:`joblib.register_compressor` in order to extend the list +of default compressors available. +To fit with Joblib internal implementation and features, such as +:func:`joblib.load` and :class:`joblib.Memory`, the registered compressor +should implement the Python file object interface. + +Compatibility across python versions +------------------------------------ + +Compatibility of joblib pickles across python versions is not fully +supported. Note that, for a very restricted set of objects, this may appear to +work when saving a pickle with python 2 and loading it with python 3 but +relying on it is strongly discouraged. + +If you are switching between python versions, you will need to save a +different joblib pickle for each python version. + +Here are a few examples or exceptions: + + - Saving joblib pickle with python 2, trying to load it with python 3:: + + Traceback (most recent call last): + File "/home/lesteve/dev/joblib/joblib/numpy_pickle.py", line 453, in load + obj = unpickler.load() + File "/home/lesteve/miniconda3/lib/python3.4/pickle.py", line 1038, in load + dispatch[key[0]](self) + File "/home/lesteve/miniconda3/lib/python3.4/pickle.py", line 1176, in load_binstring + self.append(self._decode_string(data)) + File "/home/lesteve/miniconda3/lib/python3.4/pickle.py", line 1158, in _decode_string + return value.decode(self.encoding, self.errors) + UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 1024: ordinal not in range(128) + + Traceback (most recent call last): + File "", line 1, in + File "/home/lesteve/dev/joblib/joblib/numpy_pickle.py", line 462, in load + raise new_exc + ValueError: You may be trying to read with python 3 a joblib pickle generated with python 2. This is not feature supported by joblib. + + + - Saving joblib pickle with python 3, trying to load it with python 2:: + + Traceback (most recent call last): + File "", line 1, in + File "joblib/numpy_pickle.py", line 453, in load + obj = unpickler.load() + File "/home/lesteve/miniconda3/envs/py27/lib/python2.7/pickle.py", line 858, in load + dispatch[key](self) + File "/home/lesteve/miniconda3/envs/py27/lib/python2.7/pickle.py", line 886, in load_proto + raise ValueError, "unsupported pickle protocol: %d" % proto + ValueError: unsupported pickle protocol: 3 diff --git a/testbed/joblib__joblib/doc/why.rst b/testbed/joblib__joblib/doc/why.rst new file mode 100644 index 0000000000000000000000000000000000000000..7d9fd098d225b556c898c78722415c9b7877701e --- /dev/null +++ b/testbed/joblib__joblib/doc/why.rst @@ -0,0 +1,59 @@ + +Why joblib: project goals +========================= + +Benefits of pipelines +--------------------- + +Pipeline processing systems can provide a set of useful features: + +Data-flow programming for performance +..................................... + +* **On-demand computing:** in pipeline systems such as labView or VTK, + calculations are performed as needed by the outputs and only when + inputs change. + +* **Transparent parallelization:** a pipeline topology can be inspected + to deduce which operations can be run in parallel (it is equivalent to + purely functional programming). + +Provenance tracking to understand the code +.......................................... + +* **Tracking of data and computations:** This enables the reproducibility of a + computational experiment. + +* **Inspecting data flow:** Inspecting intermediate results helps + debugging and understanding. + +.. topic:: But pipeline frameworks can get in the way + :class: warning + + Joblib's philosophy is to keep the underlying algorithm code unchanged, + avoiding framework-style modifications. + +Joblib's approach +----------------- + +Functions are the simplest abstraction used by everyone. Pipeline +jobs (or tasks) in Joblib are made of decorated functions. + +Tracking of parameters in a meaningful way requires specification of +data model. Joblib gives up on that and uses hashing for performance and +robustness. + +Design choices +-------------- + +* No dependencies other than Python + +* Robust, well-tested code, at the cost of functionality + +* Fast and suitable for scientific computing on big dataset without + changing the original code + +* Only local imports: **embed joblib in your code by copying it** + + + diff --git a/testbed/joblib__joblib/examples/README.txt b/testbed/joblib__joblib/examples/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..15c1efd69e973da78d9353e1d99dcc70ec3ce529 --- /dev/null +++ b/testbed/joblib__joblib/examples/README.txt @@ -0,0 +1,9 @@ +.. _general_examples: + +Examples +======== + +General examples +---------------- + +General-purpose and introductory examples for joblib. diff --git a/testbed/joblib__joblib/examples/compressors_comparison.py b/testbed/joblib__joblib/examples/compressors_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..be32fb6a6e8734f971429af9e11c576ae463974e --- /dev/null +++ b/testbed/joblib__joblib/examples/compressors_comparison.py @@ -0,0 +1,230 @@ +""" +=============================== +Improving I/O using compressors +=============================== + +This example compares the compressors available in Joblib. In the example, +Zlib, LZMA and LZ4 compression only are used but Joblib also supports BZ2 and +GZip compression methods. +For each compared compression method, this example dumps and reloads a +dataset fetched from an online machine-learning database. This gives 3 +information: the size on disk of the compressed data, the time spent to dump +and the time spent to reload the data from disk. +""" + +import os +import os.path +import time + +############################################################################### +# Get some data from real-world use cases +# --------------------------------------- +# +# First fetch the benchmark dataset from an online machine-learning database +# and load it in a pandas dataframe. + +import pandas as pd + +url = "https://github.com/joblib/dataset/raw/main/kddcup.data.gz" +names = ("duration, protocol_type, service, flag, src_bytes, " + "dst_bytes, land, wrong_fragment, urgent, hot, " + "num_failed_logins, logged_in, num_compromised, " + "root_shell, su_attempted, num_root, " + "num_file_creations, ").split(', ') + +data = pd.read_csv(url, names=names, nrows=1e6) + +############################################################################### +# Dump and load the dataset without compression +# --------------------------------------------- +# +# This gives reference values for later comparison. + +from joblib import dump, load + +pickle_file = './pickle_data.joblib' + +############################################################################### +# Start by measuring the time spent for dumping the raw data: +start = time.time() +with open(pickle_file, 'wb') as f: + dump(data, f) +raw_dump_duration = time.time() - start +print("Raw dump duration: %0.3fs" % raw_dump_duration) + +############################################################################### +# Then measure the size of the raw dumped data on disk: +raw_file_size = os.stat(pickle_file).st_size / 1e6 +print("Raw dump file size: %0.3fMB" % raw_file_size) + +############################################################################### +# Finally measure the time spent for loading the raw data: +start = time.time() +with open(pickle_file, 'rb') as f: + load(f) +raw_load_duration = time.time() - start +print("Raw load duration: %0.3fs" % raw_load_duration) + +############################################################################### +# Dump and load the dataset using the Zlib compression method +# ----------------------------------------------------------- +# +# The compression level is using the default value, 3, which is, in general, a +# good compromise between compression and speed. + +############################################################################### +# Start by measuring the time spent for dumping of the zlib data: + +start = time.time() +with open(pickle_file, 'wb') as f: + dump(data, f, compress='zlib') +zlib_dump_duration = time.time() - start +print("Zlib dump duration: %0.3fs" % zlib_dump_duration) + +############################################################################### +# Then measure the size of the zlib dump data on disk: + +zlib_file_size = os.stat(pickle_file).st_size / 1e6 +print("Zlib file size: %0.3fMB" % zlib_file_size) + +############################################################################### +# Finally measure the time spent for loading the compressed dataset: + +start = time.time() +with open(pickle_file, 'rb') as f: + load(f) +zlib_load_duration = time.time() - start +print("Zlib load duration: %0.3fs" % zlib_load_duration) + +############################################################################### +# .. note:: The compression format is detected automatically by Joblib. +# The compression format is identified by the standard magic number present +# at the beginning of the file. Joblib uses this information to determine +# the compression method used. +# This is the case for all compression methods supported by Joblib. + +############################################################################### +# Dump and load the dataset using the LZMA compression method +# ----------------------------------------------------------- +# +# LZMA compression method has a very good compression rate but at the cost +# of being very slow. +# In this example, a light compression level, e.g. 3, is used to speed up a +# bit the dump/load cycle. + +############################################################################### +# Start by measuring the time spent for dumping the lzma data: + +start = time.time() +with open(pickle_file, 'wb') as f: + dump(data, f, compress=('lzma', 3)) +lzma_dump_duration = time.time() - start +print("LZMA dump duration: %0.3fs" % lzma_dump_duration) + +############################################################################### +# Then measure the size of the lzma dump data on disk: + +lzma_file_size = os.stat(pickle_file).st_size / 1e6 +print("LZMA file size: %0.3fMB" % lzma_file_size) + +############################################################################### +# Finally measure the time spent for loading the lzma data: + +start = time.time() +with open(pickle_file, 'rb') as f: + load(f) +lzma_load_duration = time.time() - start +print("LZMA load duration: %0.3fs" % lzma_load_duration) + +############################################################################### +# Dump and load the dataset using the LZ4 compression method +# ---------------------------------------------------------- +# +# LZ4 compression method is known to be one of the fastest available +# compression method but with a compression rate a bit lower than Zlib. In +# most of the cases, this method is a good choice. + +############################################################################### +# .. note:: In order to use LZ4 compression with Joblib, the +# `lz4 `_ package must be installed +# on the system. + +############################################################################### +# Start by measuring the time spent for dumping the lz4 data: + +start = time.time() +with open(pickle_file, 'wb') as f: + dump(data, f, compress='lz4') +lz4_dump_duration = time.time() - start +print("LZ4 dump duration: %0.3fs" % lz4_dump_duration) + +############################################################################### +# Then measure the size of the lz4 dump data on disk: + +lz4_file_size = os.stat(pickle_file).st_size / 1e6 +print("LZ4 file size: %0.3fMB" % lz4_file_size) + +############################################################################### +# Finally measure the time spent for loading the lz4 data: + +start = time.time() +with open(pickle_file, 'rb') as f: + load(f) +lz4_load_duration = time.time() - start +print("LZ4 load duration: %0.3fs" % lz4_load_duration) + +############################################################################### +# Comparing the results +# --------------------- + +import numpy as np +import matplotlib.pyplot as plt + +N = 4 +load_durations = (raw_load_duration, lz4_load_duration, zlib_load_duration, + lzma_load_duration) +dump_durations = (raw_dump_duration, lz4_dump_duration, zlib_dump_duration, + lzma_dump_duration) +file_sizes = (raw_file_size, lz4_file_size, zlib_file_size, lzma_file_size) +ind = np.arange(N) +width = 0.5 + +plt.figure(1, figsize=(5, 4)) +p1 = plt.bar(ind, dump_durations, width) +p2 = plt.bar(ind, load_durations, width, bottom=dump_durations) +plt.ylabel('Time in seconds') +plt.title('Dump and load durations') +plt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA')) +plt.yticks(np.arange(0, lzma_load_duration + lzma_dump_duration)) +plt.legend((p1[0], p2[0]), ('Dump duration', 'Load duration')) + +############################################################################### +# Compared with other compressors, LZ4 is clearly the fastest, especially for +# dumping compressed data on disk. In this particular case, it can even be +# faster than the raw dump. +# Also note that dump and load durations depend on the I/O speed of the +# underlying storage: for example, with SSD hard drives the LZ4 compression +# will be slightly slower than raw dump/load, whereas with spinning hard disk +# drives (HDD) or remote storage (NFS), LZ4 is faster in general. +# +# LZMA and Zlib, even if always slower for dumping data, are quite fast when +# re-loading compressed data from disk. + +plt.figure(2, figsize=(5, 4)) +plt.bar(ind, file_sizes, width, log=True) +plt.ylabel('File size in MB') +plt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA')) + +############################################################################### +# Compressed data obviously takes a lot less space on disk than raw data. LZMA +# is the best compression method in terms of compression rate. Zlib also has a +# better compression rate than LZ4. + +plt.show() + +############################################################################### +# Clear the pickle file +# --------------------- + +import os +os.remove(pickle_file) diff --git a/testbed/joblib__joblib/examples/memory_basic_usage.py b/testbed/joblib__joblib/examples/memory_basic_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..c5cc33dd51b512efa165c429df19b1d0dd202de4 --- /dev/null +++ b/testbed/joblib__joblib/examples/memory_basic_usage.py @@ -0,0 +1,137 @@ +""" +======================== +How to use joblib.Memory +======================== + +This example illustrates the usage of :class:`joblib.Memory` with both +functions and methods. + +""" + +############################################################################### +# Without :class:`joblib.Memory` +############################################################################### +# +# ``costly_compute`` emulates a computationally expensive process which later +# will benefit from caching using :class:`joblib.Memory`. + +import time +import numpy as np + + +def costly_compute(data, column_index=0): + """Simulate an expensive computation""" + time.sleep(5) + return data[column_index] + + +############################################################################### +# Be sure to set the random seed to generate deterministic data. Indeed, if the +# data is not deterministic, the :class:`joblib.Memory` instance will not be +# able to reuse the cache from one run to another. + +rng = np.random.RandomState(42) +data = rng.randn(int(1e5), 10) +start = time.time() +data_trans = costly_compute(data) +end = time.time() + +print('\nThe function took {:.2f} s to compute.'.format(end - start)) +print('\nThe transformed data are:\n {}'.format(data_trans)) + +############################################################################### +# Caching the result of a function to avoid recomputing +############################################################################### +# +# If we need to call our function several time with the same input data, it is +# beneficial to avoid recomputing the same results over and over since it is +# expensive. :class:`joblib.Memory` enables to cache results from a function +# into a specific location. + +from joblib import Memory +location = './cachedir' +memory = Memory(location, verbose=0) + + +def costly_compute_cached(data, column_index=0): + """Simulate an expensive computation""" + time.sleep(5) + return data[column_index] + + +costly_compute_cached = memory.cache(costly_compute_cached) +start = time.time() +data_trans = costly_compute_cached(data) +end = time.time() + +print('\nThe function took {:.2f} s to compute.'.format(end - start)) +print('\nThe transformed data are:\n {}'.format(data_trans)) + +############################################################################### +# At the first call, the results will be cached. Therefore, the computation +# time corresponds to the time to compute the results plus the time to dump the +# results into the disk. + +start = time.time() +data_trans = costly_compute_cached(data) +end = time.time() + +print('\nThe function took {:.2f} s to compute.'.format(end - start)) +print('\nThe transformed data are:\n {}'.format(data_trans)) + +############################################################################### +# At the second call, the computation time is largely reduced since the results +# are obtained by loading the data previously dumped to the disk instead of +# recomputing the results. + +############################################################################### +# Using :class:`joblib.Memory` with a method +############################################################################### +# +# :class:`joblib.Memory` is designed to work with functions with no side +# effects. When dealing with class, the computationally expensive part of a +# method has to be moved to a function and decorated in the class method. + + +def _costly_compute_cached(data, column): + time.sleep(5) + return data[column] + + +class Algorithm(object): + """A class which is using the previous function.""" + + def __init__(self, column=0): + self.column = column + + def transform(self, data): + costly_compute = memory.cache(_costly_compute_cached) + return costly_compute(data, self.column) + + +transformer = Algorithm() +start = time.time() +data_trans = transformer.transform(data) +end = time.time() + +print('\nThe function took {:.2f} s to compute.'.format(end - start)) +print('\nThe transformed data are:\n {}'.format(data_trans)) + +############################################################################### + +start = time.time() +data_trans = transformer.transform(data) +end = time.time() + +print('\nThe function took {:.2f} s to compute.'.format(end - start)) +print('\nThe transformed data are:\n {}'.format(data_trans)) + +############################################################################### +# As expected, the second call to the ``transform`` method load the results +# which have been cached. + +############################################################################### +# Clean up cache directory +############################################################################### + +memory.clear(warn=False) diff --git a/testbed/joblib__joblib/examples/nested_parallel_memory.py b/testbed/joblib__joblib/examples/nested_parallel_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..8724cb7d42d23bf59c1766de32e5a61e6167441d --- /dev/null +++ b/testbed/joblib__joblib/examples/nested_parallel_memory.py @@ -0,0 +1,140 @@ +""" +================================================== +Checkpoint using joblib.Memory and joblib.Parallel +================================================== + +This example illustrates how to cache intermediate computing results using +:class:`joblib.Memory` within :class:`joblib.Parallel`. + +""" + +############################################################################### +# Embed caching within parallel processing +############################################################################### +# +# It is possible to cache a computationally expensive function executed during +# a parallel process. ``costly_compute`` emulates such time consuming function. + +import time + + +def costly_compute(data, column): + """Emulate a costly function by sleeping and returning a column.""" + time.sleep(2) + return data[column] + + +def data_processing_mean(data, column): + """Compute the mean of a column.""" + return costly_compute(data, column).mean() + + +############################################################################### +# Create some data. The random seed is fixed to generate deterministic data +# across Python session. Note that this is not necessary for this specific +# example since the memory cache is cleared at the end of the session. + +import numpy as np +rng = np.random.RandomState(42) +data = rng.randn(int(1e4), 4) + +############################################################################### +# It is first possible to make the processing without caching or parallel +# processing. + +start = time.time() +results = [data_processing_mean(data, col) for col in range(data.shape[1])] +stop = time.time() + +print('\nSequential processing') +print('Elapsed time for the entire processing: {:.2f} s' + .format(stop - start)) + +############################################################################### +# ``costly_compute`` is expensive to compute and it is used as an intermediate +# step in ``data_processing_mean``. Therefore, it is interesting to store the +# intermediate results from ``costly_compute`` using :class:`joblib.Memory`. + +from joblib import Memory + +location = './cachedir' +memory = Memory(location, verbose=0) +costly_compute_cached = memory.cache(costly_compute) + + +############################################################################### +# Now, we define ``data_processing_mean_using_cache`` which benefits from the +# cache by calling ``costly_compute_cached`` + +def data_processing_mean_using_cache(data, column): + """Compute the mean of a column.""" + return costly_compute_cached(data, column).mean() + + +############################################################################### +# Then, we execute the same processing in parallel and caching the intermediate +# results. + +from joblib import Parallel, delayed + +start = time.time() +results = Parallel(n_jobs=2)( + delayed(data_processing_mean_using_cache)(data, col) + for col in range(data.shape[1])) +stop = time.time() + +print('\nFirst round - caching the data') +print('Elapsed time for the entire processing: {:.2f} s' + .format(stop - start)) + +############################################################################### +# By using 2 workers, the parallel processing gives a x2 speed-up compared to +# the sequential case. By executing again the same process, the intermediate +# results obtained by calling ``costly_compute_cached`` will be loaded from the +# cache instead of executing the function. + +start = time.time() +results = Parallel(n_jobs=2)( + delayed(data_processing_mean_using_cache)(data, col) + for col in range(data.shape[1])) +stop = time.time() + +print('\nSecond round - reloading from the cache') +print('Elapsed time for the entire processing: {:.2f} s' + .format(stop - start)) + +############################################################################### +# Reuse intermediate checkpoints +############################################################################### +# +# Having cached the intermediate results of the ``costly_compute_cached`` +# function, they are reusable by calling the function. We define a new +# processing which will take the maximum of the array returned by +# ``costly_compute_cached`` instead of previously the mean. + + +def data_processing_max_using_cache(data, column): + """Compute the max of a column.""" + return costly_compute_cached(data, column).max() + + +start = time.time() +results = Parallel(n_jobs=2)( + delayed(data_processing_max_using_cache)(data, col) + for col in range(data.shape[1])) +stop = time.time() + +print('\nReusing intermediate checkpoints') +print('Elapsed time for the entire processing: {:.2f} s' + .format(stop - start)) + +############################################################################### +# The processing time only corresponds to the execution of the ``max`` +# function. The internal call to ``costly_compute_cached`` is reloading the +# results from the cache. + +############################################################################### +# Clean-up the cache folder +############################################################################### + +memory.clear(warn=False) diff --git a/testbed/joblib__joblib/examples/parallel/README.txt b/testbed/joblib__joblib/examples/parallel/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ddb228f40c7eaf29464f038ac4fd1f66184521e --- /dev/null +++ b/testbed/joblib__joblib/examples/parallel/README.txt @@ -0,0 +1,6 @@ +.. _parallel_examples: + +Parallel examples +----------------- + +Examples demoing more advanced parallel patterns. diff --git a/testbed/joblib__joblib/examples/parallel/distributed_backend_simple.py b/testbed/joblib__joblib/examples/parallel/distributed_backend_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..6ccd06dd30f8e43711cb5d834b358d419229d492 --- /dev/null +++ b/testbed/joblib__joblib/examples/parallel/distributed_backend_simple.py @@ -0,0 +1,57 @@ +""" +Using Dask for single-machine parallel computing +================================================ + +This example shows the simplest usage of the +`Dask `_ +backend on your local machine. + +This is useful for prototyping a solution, to later be run on a truly +`distributed Dask cluster +`_, +as the only change needed is the cluster class. + +Another realistic usage scenario: combining dask code with joblib code, +for instance using dask for preprocessing data, and scikit-learn for +machine learning. In such a setting, it may be interesting to use +distributed as a backend scheduler for both dask and joblib, to +orchestrate the computation. + +""" + +############################################################################### +# Setup the distributed client +############################################################################### +from dask.distributed import Client, LocalCluster + +# replace with whichever cluster class you're using +# https://docs.dask.org/en/stable/deploying.html#distributed-computing +cluster = LocalCluster() +# connect client to your cluster +client = Client(cluster) + +# Monitor your computation with the Dask dashboard +print(client.dashboard_link) + +############################################################################### +# Run parallel computation using dask.distributed +############################################################################### + +import time +import joblib + + +def long_running_function(i): + time.sleep(0.1) + return i + + +############################################################################### +# The verbose messages below show that the backend is indeed the +# dask.distributed one +with joblib.parallel_config(backend="dask"): + joblib.Parallel(verbose=100)( + joblib.delayed(long_running_function)(i) for i in range(10) + ) + +############################################################################### diff --git a/testbed/joblib__joblib/examples/parallel_generator.py b/testbed/joblib__joblib/examples/parallel_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..e41ff1fe57296c2468b955d95bdb48057c208a21 --- /dev/null +++ b/testbed/joblib__joblib/examples/parallel_generator.py @@ -0,0 +1,291 @@ +""" +======================================== +Returning a generator in joblib.Parallel +======================================== + +This example illustrates memory optimization enabled by using +:class:`joblib.Parallel` to get a generator on the outputs of parallel jobs. +We first create tasks that return results with large memory footprints. +If we call :class:`~joblib.Parallel` for several of these tasks directly, we +observe a high memory usage, as all the results are held in RAM before being +processed + +Using ``return_as='generator'`` allows to progressively consume the outputs +as they arrive and keeps the memory at an acceptable level. + +In this case, the output of the `Parallel` call is a generator that yields the +results in the order the tasks have been submitted with. If the order of the +tasks does not matter (for instance if they are consumed by a commutative +aggregation function), then using ``return_as='generator_unordered'`` can be +even more efficient. + +""" + +############################################################################## +# ``MemoryMonitor`` helper +############################################################################## + +############################################################################## +# The following class is an helper to monitor the memory of the process and its +# children in another thread, so we can display it afterward. +# +# We will use ``psutil`` to monitor the memory usage in the code. Make sure it +# is installed with ``pip install psutil`` for this example. + + +import time +from psutil import Process +from threading import Thread + + +class MemoryMonitor(Thread): + """Monitor the memory usage in MB in a separate thread. + + Note that this class is good enough to highlight the memory profile of + Parallel in this example, but is not a general purpose profiler fit for + all cases. + """ + def __init__(self): + super().__init__() + self.stop = False + self.memory_buffer = [] + self.start() + + def get_memory(self): + "Get memory of a process and its children." + p = Process() + memory = p.memory_info().rss + for c in p.children(): + memory += c.memory_info().rss + return memory + + def run(self): + memory_start = self.get_memory() + while not self.stop: + self.memory_buffer.append(self.get_memory() - memory_start) + time.sleep(0.2) + + def join(self): + self.stop = True + super().join() + + +############################################################################## +# Save memory by consuming the outputs of the tasks as fast as possible +############################################################################## + +############################################################################## +# We create a task whose output takes about 15MB of RAM. +# + +import numpy as np + + +def return_big_object(i): + time.sleep(.1) + return i * np.ones((10000, 200), dtype=np.float64) + + +############################################################################## +# We create a reduce step. The input will be a generator on big objects +# generated in parallel by several instances of ``return_big_object``. + +def accumulator_sum(generator): + result = 0 + for value in generator: + result += value + print(".", end="", flush=True) + print("") + return result + + +############################################################################## +# We process many of the tasks in parallel. If ``return_as="list"`` (default), +# we should expect a usage of more than 2GB in RAM. Indeed, all the results +# are computed and stored in ``res`` before being processed by +# `accumulator_sum` and collected by the gc. + +from joblib import Parallel, delayed + +monitor = MemoryMonitor() +print("Running tasks with return_as='list'...") +res = Parallel(n_jobs=2, return_as="list")( + delayed(return_big_object)(i) for i in range(150) +) +print("Accumulate results:", end='') +res = accumulator_sum(res) +print('All tasks completed and reduced successfully.') + +# Report memory usage +del res # we clean the result to avoid memory border effects +monitor.join() +peak = max(monitor.memory_buffer) / 1e9 +print(f"Peak memory usage: {peak:.2f}GB") + + +############################################################################## +# If we use ``return_as="generator"``, ``res`` is simply a generator on the +# results that are ready. Here we consume the results as soon as they arrive +# with the ``accumulator_sum`` and once they have been used, they are collected +# by the gc. The memory footprint is thus reduced, typically around 300MB. + +monitor_gen = MemoryMonitor() +print("Create result generator with return_as='generator'...") +res = Parallel(n_jobs=2, return_as="generator")( + delayed(return_big_object)(i) for i in range(150) +) +print("Accumulate results:", end='') +res = accumulator_sum(res) +print('All tasks completed and reduced successfully.') + +# Report memory usage +del res # we clean the result to avoid memory border effects +monitor_gen.join() +peak = max(monitor_gen.memory_buffer) / 1e6 +print(f"Peak memory usage: {peak:.2f}MB") + + +############################################################################## +# We can then report the memory usage accross time of the two runs using the +# MemoryMonitor. +# +# In the first case, as the results accumulate in ``res``, the memory grows +# linearly and it is freed once the ``accumulator_sum`` function finishes. +# +# In the second case, the results are processed by the accumulator as soon as +# they arrive, and the memory does not need to be able to contain all +# the results. + +import matplotlib.pyplot as plt +plt.figure(0) +plt.semilogy( + np.maximum.accumulate(monitor.memory_buffer), + label='return_as="list"' +) +plt.semilogy( + np.maximum.accumulate(monitor_gen.memory_buffer), + label='return_as="generator"' +) +plt.xlabel("Time") +plt.xticks([], []) +plt.ylabel("Memory usage") +plt.yticks([1e7, 1e8, 1e9], ['10MB', '100MB', '1GB']) +plt.legend() +plt.show() + +############################################################################## +# It is important to note that with ``return_as="generator"``, the results are +# still accumulated in RAM after computation. But as we asynchronously process +# them, they can be freed sooner. However, if the generator is not consumed +# the memory still grows linearly. + + +############################################################################## +# Further memory efficiency for commutative aggregation +############################################################################## + +############################################################################## +# There is still room for improving the relief on memory allocation we get +# using ``return_as="generator"``. Indeed, notice how the generator of the +# previous example respects the order the tasks have been submitted with. This +# behavior can cause a build up in memory of results waiting to be consumed, +# in case some tasks finished before other tasks despite being submitted +# later. The corresponding results will be kept in memory until the slower +# tasks submitted earlier are done and have been iterated over. +# +# In case the downstream consumer of the results is reliant on the assumption +# that the results are yielded in the same order that the tasks were submitted, +# it can't be helped. But in our example, since the `+` operator is +# commutative, the function ``accumulator_sum`` does not need the generator to +# return the results with any particular order. In this case it's safe to use +# the option ``return_as="generator_unordered"``, so that the results are +# returned as soon as a task is completed, ignoring the order of task +# submission. +# +# Beware that the downstream consumer of the results must not expect them be +# returned with any deterministic or predictable order at all, since the +# progress of the tasks can depend on the availability of the workers, which +# can be affected by external events, such as system load, implementation +# details in the backend, etc. + + +############################################################################## +# To better highlight improvements in memory usage when using the parameter +# ``return_as="generator_unordered"``, let's explcitly add delay in some of +# the submitted tasks. + + +def return_big_object_delayed(i): + if (i + 20) % 60: + time.sleep(0.1) + else: + time.sleep(5) + return i * np.ones((10000, 200), dtype=np.float64) + + +############################################################################## +# Let's check memory usage when using ``return_as="generator"``... + +monitor_delayed_gen = MemoryMonitor() +print("Create result generator on delayed tasks with return_as='generator'...") +res = Parallel(n_jobs=2, return_as="generator")( + delayed(return_big_object_delayed)(i) for i in range(150) +) +print("Accumulate results:", end='') +res = accumulator_sum(res) +print('All tasks completed and reduced successfully.') + +# Report memory usage +del res # we clean the result to avoid memory border effects +monitor_delayed_gen.join() +peak = max(monitor_delayed_gen.memory_buffer) / 1e6 +print(f"Peak memory usage: {peak:.2f}MB") + +############################################################################## +# If we use ``return_as="generator_unordered"``, ``res`` will not enforce any +# order when returning the results, and will simply enable iterating on the +# results as soon as it's available. The peak memory usage is now controlled +# to an even lower level, since that results can be consumed immediately +# rather than being delayed by the compute of slower tasks that have been +# submitted earlier. + +monitor_delayed_gen_unordered = MemoryMonitor() +print( + "Create result generator on delayed tasks with " + "return_as='generator_unordered'..." +) +res = Parallel(n_jobs=2, return_as="generator_unordered")( + delayed(return_big_object_delayed)(i) for i in range(150) +) +print("Accumulate results:", end='') +res = accumulator_sum(res) +print('All tasks completed and reduced successfully.') + +# Report memory usage +del res # we clean the result to avoid memory border effects +monitor_delayed_gen_unordered.join() +peak = max(monitor_delayed_gen_unordered.memory_buffer) / 1e6 +print(f"Peak memory usage: {peak:.2f}MB") + + +############################################################################## +# Notice how the plot for ``'return_as="generator'`` now shows a high memory +# usage plateau when slow jobs cause a congestion of intermediate results +# waiting in RAM before in-order aggregation. This high memory usage is never +# observed when using ``'return_as="generator_unordered"``. + +plt.figure(1) +plt.semilogy( + np.maximum.accumulate(monitor_delayed_gen.memory_buffer), + label='return_as="generator"' +) +plt.semilogy( + np.maximum.accumulate(monitor_delayed_gen_unordered.memory_buffer), + label='return_as="generator_unordered"' +) +plt.xlabel("Time") +plt.xticks([], []) +plt.ylabel("Memory usage") +plt.yticks([1e7, 1e8, 1e9], ['10MB', '100MB', '1GB']) +plt.legend() +plt.show() diff --git a/testbed/joblib__joblib/examples/parallel_memmap.py b/testbed/joblib__joblib/examples/parallel_memmap.py new file mode 100644 index 0000000000000000000000000000000000000000..02c59f488b09d75d341551e96708a643adfb4399 --- /dev/null +++ b/testbed/joblib__joblib/examples/parallel_memmap.py @@ -0,0 +1,155 @@ +""" +=============================== +NumPy memmap in joblib.Parallel +=============================== + +This example illustrates some features enabled by using a memory map +(:class:`numpy.memmap`) within :class:`joblib.Parallel`. First, we show that +dumping a huge data array ahead of passing it to :class:`joblib.Parallel` +speeds up computation. Then, we show the possibility to provide write access to +original data. + +""" + +############################################################################## +# Speed up processing of a large data array +############################################################################## +# +# We create a large data array for which the average is computed for several +# slices. + +import numpy as np + +data = np.random.random((int(1e7),)) +window_size = int(5e5) +slices = [slice(start, start + window_size) + for start in range(0, data.size - window_size, int(1e5))] + +############################################################################### +# The ``slow_mean`` function introduces a :func:`time.sleep` call to simulate a +# more expensive computation cost for which parallel computing is beneficial. +# Parallel may not be beneficial for very fast operation, due to extra overhead +# (workers creations, communication, etc.). + +import time + + +def slow_mean(data, sl): + """Simulate a time consuming processing.""" + time.sleep(0.01) + return data[sl].mean() + + +############################################################################### +# First, we will evaluate the sequential computing on our problem. + +tic = time.time() +results = [slow_mean(data, sl) for sl in slices] +toc = time.time() +print('\nElapsed time computing the average of couple of slices {:.2f} s' + .format(toc - tic)) + +############################################################################### +# :class:`joblib.Parallel` is used to compute in parallel the average of all +# slices using 2 workers. + +from joblib import Parallel, delayed + + +tic = time.time() +results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices) +toc = time.time() +print('\nElapsed time computing the average of couple of slices {:.2f} s' + .format(toc - tic)) + +############################################################################### +# Parallel processing is already faster than the sequential processing. It is +# also possible to remove a bit of overhead by dumping the ``data`` array to a +# memmap and pass the memmap to :class:`joblib.Parallel`. + +import os +from joblib import dump, load + +folder = './joblib_memmap' +try: + os.mkdir(folder) +except FileExistsError: + pass + +data_filename_memmap = os.path.join(folder, 'data_memmap') +dump(data, data_filename_memmap) +data = load(data_filename_memmap, mmap_mode='r') + +tic = time.time() +results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices) +toc = time.time() +print('\nElapsed time computing the average of couple of slices {:.2f} s\n' + .format(toc - tic)) + +############################################################################### +# Therefore, dumping large ``data`` array ahead of calling +# :class:`joblib.Parallel` can speed up the processing by removing some +# overhead. + +############################################################################### +# Writable memmap for shared memory :class:`joblib.Parallel` +############################################################################### +# +# ``slow_mean_write_output`` will compute the mean for some given slices as in +# the previous example. However, the resulting mean will be directly written on +# the output array. + + +def slow_mean_write_output(data, sl, output, idx): + """Simulate a time consuming processing.""" + time.sleep(0.005) + res_ = data[sl].mean() + print("[Worker %d] Mean for slice %d is %f" % (os.getpid(), idx, res_)) + output[idx] = res_ + + +############################################################################### +# Prepare the folder where the memmap will be dumped. + +output_filename_memmap = os.path.join(folder, 'output_memmap') + +############################################################################### +# Pre-allocate a writable shared memory map as a container for the results of +# the parallel computation. + +output = np.memmap(output_filename_memmap, dtype=data.dtype, + shape=len(slices), mode='w+') + +############################################################################### +# ``data`` is replaced by its memory mapped version. Note that the buffer has +# already been dumped in the previous section. + +data = load(data_filename_memmap, mmap_mode='r') + +############################################################################### +# Fork the worker processes to perform computation concurrently + +Parallel(n_jobs=2)(delayed(slow_mean_write_output)(data, sl, output, idx) + for idx, sl in enumerate(slices)) + +############################################################################### +# Compare the results from the output buffer with the expected results + +print("\nExpected means computed in the parent process:\n {}" + .format(np.array(results))) +print("\nActual means computed by the worker processes:\n {}" + .format(output)) + +############################################################################### +# Clean-up the memmap +############################################################################### +# +# Remove the different memmap that we created. It might fail in Windows due +# to file permissions. + +import shutil + +try: + shutil.rmtree(folder) +except: # noqa + print('Could not clean-up automatically.') diff --git a/testbed/joblib__joblib/examples/parallel_random_state.py b/testbed/joblib__joblib/examples/parallel_random_state.py new file mode 100644 index 0000000000000000000000000000000000000000..0f80f144bc8ab72fad9b0f239c7a7602ec441a92 --- /dev/null +++ b/testbed/joblib__joblib/examples/parallel_random_state.py @@ -0,0 +1,132 @@ +# %% +""" +=================================== +Random state within joblib.Parallel +=================================== + +Randomness is affected by parallel execution differently by the different +backends. + +In particular, when using multiple processes, the random sequence can be +the same in all processes. This example illustrates the problem and shows +how to work around it. +""" + +import numpy as np +from joblib import Parallel, delayed + + +# %% +# A utility function for the example +def print_vector(vector, backend): + """Helper function to print the generated vector with a given backend.""" + print('\nThe different generated vectors using the {} backend are:\n {}' + .format(backend, np.array(vector))) + + +# %% +# Sequential behavior +##################### +# +# ``stochastic_function`` will generate five random integers. When +# calling the function several times, we are expecting to obtain +# different vectors. For instance, we will call the function five times +# in a sequential manner, we can check that the generated vectors are all +# different. + + +def stochastic_function(max_value): + """Randomly generate integer up to a maximum value.""" + return np.random.randint(max_value, size=5) + + +n_vectors = 5 +random_vector = [stochastic_function(10) for _ in range(n_vectors)] +print('\nThe different generated vectors in a sequential manner are:\n {}' + .format(np.array(random_vector))) + +# %% +# Parallel behavior +################### +# +# Joblib provides three different backends: loky (default), threading, and +# multiprocessing. + +backend = 'loky' +random_vector = Parallel(n_jobs=2, backend=backend)(delayed( + stochastic_function)(10) for _ in range(n_vectors)) +print_vector(random_vector, backend) + +############################################################################### + +backend = 'threading' +random_vector = Parallel(n_jobs=2, backend=backend)(delayed( + stochastic_function)(10) for _ in range(n_vectors)) +print_vector(random_vector, backend) + +# %% +# Loky and the threading backends behave exactly as in the sequential case and +# do not require more care. However, this is not the case regarding the +# multiprocessing backend with the "fork" or "forkserver" start method because +# the state of the global numpy random stated will be exactly duplicated +# in all the workers +# +# Note: on platforms for which the default start method is "spawn", we do not +# have this problem but we cannot use this in a Python script without +# using the if __name__ == "__main__" construct. So let's end this example +# early if that's the case: + +import multiprocessing as mp +if mp.get_start_method() != "spawn": + backend = 'multiprocessing' + random_vector = Parallel(n_jobs=2, backend=backend)(delayed( + stochastic_function)(10) for _ in range(n_vectors)) + print_vector(random_vector, backend) + +# %% +# Some of the generated vectors are exactly the same, which can be a +# problem for the application. +# +# Technically, the reason is that all forked Python processes share the +# same exact random seed. As a result, we obtain twice the same randomly +# generated vectors because we are using ``n_jobs=2``. A solution is to +# set the random state within the function which is passed to +# :class:`joblib.Parallel`. + + +def stochastic_function_seeded(max_value, random_state): + rng = np.random.RandomState(random_state) + return rng.randint(max_value, size=5) + + +# %% +# ``stochastic_function_seeded`` accepts as argument a random seed. We can +# reset this seed by passing ``None`` at every function call. In this case, we +# see that the generated vectors are all different. + +if mp.get_start_method() != "spawn": + random_vector = Parallel(n_jobs=2, backend=backend)(delayed( + stochastic_function_seeded)(10, None) for _ in range(n_vectors)) + print_vector(random_vector, backend) + +# %% +# Fixing the random state to obtain deterministic results +######################################################### +# +# The pattern of ``stochastic_function_seeded`` has another advantage: it +# allows to control the random_state by passing a known seed. For best results +# [1]_, the random state is initialized by a sequence based on a root seed and +# a job identifier. So for instance, we can replicate the same generation of +# vectors by passing a fixed state as follows. +# +# .. [1] https://numpy.org/doc/stable/reference/random/parallel.html + +if mp.get_start_method() != "spawn": + seed = 42 + random_vector = Parallel(n_jobs=2, backend=backend)(delayed( + stochastic_function_seeded)(10, [i, seed]) for i in range(n_vectors)) + print_vector(random_vector, backend) + + random_vector = Parallel(n_jobs=2, backend=backend)(delayed( + stochastic_function_seeded)(10, [i, seed]) for i in range(n_vectors)) + print_vector(random_vector, backend) diff --git a/testbed/joblib__joblib/examples/serialization_and_wrappers.py b/testbed/joblib__joblib/examples/serialization_and_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..fb7cb3ce9de04aad546159e42c7b02e53ca51908 --- /dev/null +++ b/testbed/joblib__joblib/examples/serialization_and_wrappers.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +""" +Serialization of un-picklable objects +===================================== + +This example highlights the options for tempering with joblib serialization +process. + +""" + +# Code source: Thomas Moreau +# License: BSD 3 clause + +import sys +import time +import traceback +from joblib.externals.loky import set_loky_pickler +from joblib import parallel_config +from joblib import Parallel, delayed +from joblib import wrap_non_picklable_objects + + +############################################################################### +# First, define functions which cannot be pickled with the standard ``pickle`` +# protocol. They cannot be serialized with ``pickle`` because they are defined +# in the ``__main__`` module. They can however be serialized with +# ``cloudpickle``. With the default behavior, ``loky`` is to use +# ``cloudpickle`` to serialize the objects that are sent to the workers. +# + +def func_async(i, *args): + return 2 * i + + +print(Parallel(n_jobs=2)(delayed(func_async)(21) for _ in range(1))[0]) + + +############################################################################### +# For most use-cases, using ``cloudpickle`` is efficient enough. However, this +# solution can be very slow to serialize large python objects, such as dict or +# list, compared to the standard ``pickle`` serialization. +# + +def func_async(i, *args): + return 2 * i + + +# We have to pass an extra argument with a large list (or another large python +# object). +large_list = list(range(1000000)) + +t_start = time.time() +Parallel(n_jobs=2)(delayed(func_async)(21, large_list) for _ in range(1)) +print("With loky backend and cloudpickle serialization: {:.3f}s" + .format(time.time() - t_start)) + + +############################################################################### +# If you are on a UNIX system, it is possible to fallback to the old +# ``multiprocessing`` backend, which can pickle interactively defined functions +# with the default pickle module, which is faster for such large objects. +# + +import multiprocessing as mp +if mp.get_start_method() != "spawn": + def func_async(i, *args): + return 2 * i + + with parallel_config('multiprocessing'): + t_start = time.time() + Parallel(n_jobs=2)( + delayed(func_async)(21, large_list) for _ in range(1)) + print("With multiprocessing backend and pickle serialization: {:.3f}s" + .format(time.time() - t_start)) + + +############################################################################### +# However, using ``fork`` to start new processes can cause violation of the +# POSIX specification and can have bad interaction with compiled extensions +# that use ``openmp``. Also, it is not possible to start processes with +# ``fork`` on windows where only ``spawn`` is available. The ``loky`` backend +# has been developed to mitigate these issues. +# +# To have fast pickling with ``loky``, it is possible to rely on ``pickle`` to +# serialize all communications between the main process and the workers with +# the ``loky`` backend. This can be done by setting the environment variable +# ``LOKY_PICKLER=pickle`` before the script is launched. Here we use an +# internal programmatic switch ``loky.set_loky_pickler`` for demonstration +# purposes but it has the same effect as setting ``LOKY_PICKLER``. Note that +# this switch should not be used as it has some side effects with the workers. +# + +# Now set the `loky_pickler` to use the pickle serialization from stdlib. Here, +# we do not pass the desired function ``func_async`` as it is not picklable +# but it is replaced by ``id`` for demonstration purposes. + +set_loky_pickler('pickle') +t_start = time.time() +Parallel(n_jobs=2)(delayed(id)(large_list) for _ in range(1)) +print("With pickle serialization: {:.3f}s".format(time.time() - t_start)) + + +############################################################################### +# However, the function and objects defined in ``__main__`` are not +# serializable anymore using ``pickle`` and it is not possible to call +# ``func_async`` using this pickler. +# + +def func_async(i, *args): + return 2 * i + + +try: + Parallel(n_jobs=2)(delayed(func_async)(21, large_list) for _ in range(1)) +except Exception: + traceback.print_exc(file=sys.stdout) + + +############################################################################### +# To have both fast pickling, safe process creation and serialization of +# interactive functions, ``joblib`` provides a wrapper function +# :func:`~joblib.wrap_non_picklable_objects` to wrap the non-picklable function +# and indicate to the serialization process that this specific function should +# be serialized using ``cloudpickle``. This changes the serialization behavior +# only for this function and keeps using ``pickle`` for all other objects. The +# drawback of this solution is that it modifies the object. This should not +# cause many issues with functions but can have side effects with object +# instances. +# + +@delayed +@wrap_non_picklable_objects +def func_async_wrapped(i, *args): + return 2 * i + + +t_start = time.time() +Parallel(n_jobs=2)(func_async_wrapped(21, large_list) for _ in range(1)) +print("With pickle from stdlib and wrapper: {:.3f}s" + .format(time.time() - t_start)) + + +############################################################################### +# The same wrapper can also be used for non-picklable classes. Note that the +# side effects of ``wrap_non_picklable_objects`` on objects can break magic +# methods such as ``__add__`` and can mess up the ``isinstance`` and +# ``issubclass`` functions. Some improvements will be considered if use-cases +# are reported. +# + +# Reset the loky_pickler to avoid border effects with other examples in +# sphinx-gallery. +set_loky_pickler() diff --git a/testbed/joblib__joblib/joblib/__init__.py b/testbed/joblib__joblib/joblib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73040084428e189858b15db27f3f1fd3f4020a2a --- /dev/null +++ b/testbed/joblib__joblib/joblib/__init__.py @@ -0,0 +1,148 @@ +"""Joblib is a set of tools to provide **lightweight pipelining in +Python**. In particular: + +1. transparent disk-caching of functions and lazy re-evaluation + (memoize pattern) + +2. easy simple parallel computing + +Joblib is optimized to be **fast** and **robust** on large +data in particular and has specific optimizations for `numpy` arrays. It is +**BSD-licensed**. + + + ==================== =============================================== + **Documentation:** https://joblib.readthedocs.io + + **Download:** https://pypi.python.org/pypi/joblib#downloads + + **Source code:** https://github.com/joblib/joblib + + **Report issues:** https://github.com/joblib/joblib/issues + ==================== =============================================== + + +Vision +-------- + +The vision is to provide tools to easily achieve better performance and +reproducibility when working with long running jobs. + + * **Avoid computing the same thing twice**: code is often rerun again and + again, for instance when prototyping computational-heavy jobs (as in + scientific development), but hand-crafted solutions to alleviate this + issue are error-prone and often lead to unreproducible results. + + * **Persist to disk transparently**: efficiently persisting + arbitrary objects containing large data is hard. Using + joblib's caching mechanism avoids hand-written persistence and + implicitly links the file on disk to the execution context of + the original Python object. As a result, joblib's persistence is + good for resuming an application status or computational job, eg + after a crash. + +Joblib addresses these problems while **leaving your code and your flow +control as unmodified as possible** (no framework, no new paradigms). + +Main features +------------------ + +1) **Transparent and fast disk-caching of output value:** a memoize or + make-like functionality for Python functions that works well for + arbitrary Python objects, including very large numpy arrays. Separate + persistence and flow-execution logic from domain logic or algorithmic + code by writing the operations as a set of steps with well-defined + inputs and outputs: Python functions. Joblib can save their + computation to disk and rerun it only if necessary:: + + >>> from joblib import Memory + >>> cachedir = 'your_cache_dir_goes_here' + >>> mem = Memory(cachedir) + >>> import numpy as np + >>> a = np.vander(np.arange(3)).astype(float) + >>> square = mem.cache(np.square) + >>> b = square(a) # doctest: +ELLIPSIS + ______________________________________________________________________... + [Memory] Calling square... + square(array([[0., 0., 1.], + [1., 1., 1.], + [4., 2., 1.]])) + _________________________________________________...square - ...s, 0.0min + + >>> c = square(a) + >>> # The above call did not trigger an evaluation + +2) **Embarrassingly parallel helper:** to make it easy to write readable + parallel code and debug it quickly:: + + >>> from joblib import Parallel, delayed + >>> from math import sqrt + >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + + +3) **Fast compressed Persistence**: a replacement for pickle to work + efficiently on Python objects containing large data ( + *joblib.dump* & *joblib.load* ). + +.. + >>> import shutil ; shutil.rmtree(cachedir) + +""" + +# PEP0440 compatible formatted version, see: +# https://www.python.org/dev/peps/pep-0440/ +# +# Generic release markers: +# X.Y +# X.Y.Z # For bugfix releases +# +# Admissible pre-release markers: +# X.YaN # Alpha release +# X.YbN # Beta release +# X.YrcN # Release Candidate +# X.Y # Final release +# +# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer. +# 'X.Y.dev0' is the canonical version of 'X.Y.dev' +# +__version__ = '1.4.dev0' + + +import os + +from .memory import Memory +from .memory import MemorizedResult +from .memory import register_store_backend +from .memory import expires_after + +from .logger import PrintTime +from .logger import Logger + +from .hashing import hash + +from .numpy_pickle import dump +from .numpy_pickle import load + +from .compressor import register_compressor + +from .parallel import Parallel +from .parallel import delayed +from .parallel import cpu_count +from .parallel import register_parallel_backend +from .parallel import parallel_backend +from .parallel import parallel_config +from .parallel import effective_n_jobs +from ._cloudpickle_wrapper import wrap_non_picklable_objects + + +__all__ = ['Memory', 'MemorizedResult', 'PrintTime', 'Logger', 'hash', 'dump', + 'load', 'Parallel', 'delayed', 'cpu_count', 'effective_n_jobs', + 'register_parallel_backend', 'parallel_backend', 'expires_after', + 'register_store_backend', 'register_compressor', + 'wrap_non_picklable_objects', 'parallel_config'] + + +# Workaround issue discovered in intel-openmp 2019.5: +# https://github.com/ContinuumIO/anaconda-issues/issues/11294 +os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE") diff --git a/testbed/joblib__joblib/joblib/_cloudpickle_wrapper.py b/testbed/joblib__joblib/joblib/_cloudpickle_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..daf899d04ff513e1ce9c9c41871adcfd72c8fcf7 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_cloudpickle_wrapper.py @@ -0,0 +1,19 @@ +""" +Small shim of loky's cloudpickle_wrapper to avoid failure when +multiprocessing is not available. +""" + + +from ._multiprocessing_helpers import mp + + +def _my_wrap_non_picklable_objects(obj, keep_wrapper=True): + return obj + + +if mp is not None: + from .externals.loky import wrap_non_picklable_objects +else: + wrap_non_picklable_objects = _my_wrap_non_picklable_objects + +__all__ = ["wrap_non_picklable_objects"] diff --git a/testbed/joblib__joblib/joblib/_dask.py b/testbed/joblib__joblib/joblib/_dask.py new file mode 100644 index 0000000000000000000000000000000000000000..4288ed05cd9290a1db19044ea9ceb4ec28974082 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_dask.py @@ -0,0 +1,379 @@ +from __future__ import print_function, division, absolute_import + +import asyncio +import concurrent.futures +import contextlib + +import time +from uuid import uuid4 +import weakref + +from .parallel import parallel_config +from .parallel import AutoBatchingMixin, ParallelBackendBase + +from ._utils import ( + _TracebackCapturingWrapper, + _retrieve_traceback_capturing_wrapped_call +) + +try: + import dask + import distributed +except ImportError: + dask = None + distributed = None + +if dask is not None and distributed is not None: + from dask.utils import funcname + from dask.sizeof import sizeof + from dask.distributed import ( + Client, + as_completed, + get_client, + secede, + rejoin, + ) + from distributed.utils import thread_state + + try: + # asyncio.TimeoutError, Python3-only error thrown by recent versions of + # distributed + from distributed.utils import TimeoutError as _TimeoutError + except ImportError: + from tornado.gen import TimeoutError as _TimeoutError + + +def is_weakrefable(obj): + try: + weakref.ref(obj) + return True + except TypeError: + return False + + +class _WeakKeyDictionary: + """A variant of weakref.WeakKeyDictionary for unhashable objects. + + This datastructure is used to store futures for broadcasted data objects + such as large numpy arrays or pandas dataframes that are not hashable and + therefore cannot be used as keys of traditional python dicts. + + Furthermore using a dict with id(array) as key is not safe because the + Python is likely to reuse id of recently collected arrays. + """ + + def __init__(self): + self._data = {} + + def __getitem__(self, obj): + ref, val = self._data[id(obj)] + if ref() is not obj: + # In case of a race condition with on_destroy. + raise KeyError(obj) + return val + + def __setitem__(self, obj, value): + key = id(obj) + try: + ref, _ = self._data[key] + if ref() is not obj: + # In case of race condition with on_destroy. + raise KeyError(obj) + except KeyError: + # Insert the new entry in the mapping along with a weakref + # callback to automatically delete the entry from the mapping + # as soon as the object used as key is garbage collected. + def on_destroy(_): + del self._data[key] + ref = weakref.ref(obj, on_destroy) + self._data[key] = ref, value + + def __len__(self): + return len(self._data) + + def clear(self): + self._data.clear() + + +def _funcname(x): + try: + if isinstance(x, list): + x = x[0][0] + except Exception: + pass + return funcname(x) + + +def _make_tasks_summary(tasks): + """Summarize of list of (func, args, kwargs) function calls""" + unique_funcs = {func for func, args, kwargs in tasks} + + if len(unique_funcs) == 1: + mixed = False + else: + mixed = True + return len(tasks), mixed, _funcname(tasks) + + +class Batch: + """dask-compatible wrapper that executes a batch of tasks""" + def __init__(self, tasks): + # collect some metadata from the tasks to ease Batch calls + # introspection when debugging + self._num_tasks, self._mixed, self._funcname = _make_tasks_summary( + tasks + ) + + def __call__(self, tasks=None): + results = [] + with parallel_config(backend='dask'): + for func, args, kwargs in tasks: + results.append(func(*args, **kwargs)) + return results + + def __repr__(self): + descr = f"batch_of_{self._funcname}_{self._num_tasks}_calls" + if self._mixed: + descr = "mixed_" + descr + return descr + + +def _joblib_probe_task(): + # Noop used by the joblib connector to probe when workers are ready. + pass + + +class DaskDistributedBackend(AutoBatchingMixin, ParallelBackendBase): + MIN_IDEAL_BATCH_DURATION = 0.2 + MAX_IDEAL_BATCH_DURATION = 1.0 + supports_retrieve_callback = True + default_n_jobs = -1 + + def __init__(self, scheduler_host=None, scatter=None, + client=None, loop=None, wait_for_workers_timeout=10, + **submit_kwargs): + super().__init__() + + if distributed is None: + msg = ("You are trying to use 'dask' as a joblib parallel backend " + "but dask is not installed. Please install dask " + "to fix this error.") + raise ValueError(msg) + + if client is None: + if scheduler_host: + client = Client(scheduler_host, loop=loop, + set_as_default=False) + else: + try: + client = get_client() + except ValueError as e: + msg = ("To use Joblib with Dask first create a Dask Client" + "\n\n" + " from dask.distributed import Client\n" + " client = Client()\n" + "or\n" + " client = Client('scheduler-address:8786')") + raise ValueError(msg) from e + + self.client = client + + if scatter is not None and not isinstance(scatter, (list, tuple)): + raise TypeError("scatter must be a list/tuple, got " + "`%s`" % type(scatter).__name__) + + if scatter is not None and len(scatter) > 0: + # Keep a reference to the scattered data to keep the ids the same + self._scatter = list(scatter) + scattered = self.client.scatter(scatter, broadcast=True) + self.data_futures = {id(x): f for x, f in zip(scatter, scattered)} + else: + self._scatter = [] + self.data_futures = {} + self.wait_for_workers_timeout = wait_for_workers_timeout + self.submit_kwargs = submit_kwargs + self.waiting_futures = as_completed( + [], + loop=client.loop, + with_results=True, + raise_errors=False + ) + self._results = {} + self._callbacks = {} + + async def _collect(self): + while self._continue: + async for future, result in self.waiting_futures: + cf_future = self._results.pop(future) + callback = self._callbacks.pop(future) + if future.status == "error": + typ, exc, tb = result + cf_future.set_exception(exc) + else: + cf_future.set_result(result) + callback(result) + await asyncio.sleep(0.01) + + def __reduce__(self): + return (DaskDistributedBackend, ()) + + def get_nested_backend(self): + return DaskDistributedBackend(client=self.client), -1 + + def configure(self, n_jobs=1, parallel=None, **backend_args): + self.parallel = parallel + return self.effective_n_jobs(n_jobs) + + def start_call(self): + self._continue = True + self.client.loop.add_callback(self._collect) + self.call_data_futures = _WeakKeyDictionary() + + def stop_call(self): + # The explicit call to clear is required to break a cycling reference + # to the futures. + self._continue = False + # wait for the future collection routine (self._backend._collect) to + # finish in order to limit asyncio warnings due to aborting _collect + # during a following backend termination call + time.sleep(0.01) + self.call_data_futures.clear() + + def effective_n_jobs(self, n_jobs): + effective_n_jobs = sum(self.client.ncores().values()) + if effective_n_jobs != 0 or not self.wait_for_workers_timeout: + return effective_n_jobs + + # If there is no worker, schedule a probe task to wait for the workers + # to come up and be available. If the dask cluster is in adaptive mode + # task might cause the cluster to provision some workers. + try: + self.client.submit(_joblib_probe_task).result( + timeout=self.wait_for_workers_timeout + ) + except _TimeoutError as e: + error_msg = ( + "DaskDistributedBackend has no worker after {} seconds. " + "Make sure that workers are started and can properly connect " + "to the scheduler and increase the joblib/dask connection " + "timeout with:\n\n" + "parallel_config(backend='dask', wait_for_workers_timeout={})" + ).format(self.wait_for_workers_timeout, + max(10, 2 * self.wait_for_workers_timeout)) + raise TimeoutError(error_msg) from e + return sum(self.client.ncores().values()) + + async def _to_func_args(self, func): + itemgetters = dict() + + # Futures that are dynamically generated during a single call to + # Parallel.__call__. + call_data_futures = getattr(self, 'call_data_futures', None) + + async def maybe_to_futures(args): + out = [] + for arg in args: + arg_id = id(arg) + if arg_id in itemgetters: + out.append(itemgetters[arg_id]) + continue + + f = self.data_futures.get(arg_id, None) + if f is None and call_data_futures is not None: + try: + f = await call_data_futures[arg] + except KeyError: + pass + if f is None: + if is_weakrefable(arg) and sizeof(arg) > 1e3: + # Automatically scatter large objects to some of + # the workers to avoid duplicated data transfers. + # Rely on automated inter-worker data stealing if + # more workers need to reuse this data + # concurrently. + # set hash=False - nested scatter calls (i.e + # calling client.scatter inside a dask worker) + # using hash=True often raise CancelledError, + # see dask/distributed#3703 + _coro = self.client.scatter( + arg, + asynchronous=True, + hash=False + ) + # Centralize the scattering of identical arguments + # between concurrent apply_async callbacks by + # exposing the running coroutine in + # call_data_futures before it completes. + t = asyncio.Task(_coro) + call_data_futures[arg] = t + + f = await t + + if f is not None: + out.append(f) + else: + out.append(arg) + return out + + tasks = [] + for f, args, kwargs in func.items: + args = list(await maybe_to_futures(args)) + kwargs = dict(zip(kwargs.keys(), + await maybe_to_futures(kwargs.values()))) + tasks.append((f, args, kwargs)) + + return (Batch(tasks), tasks) + + def apply_async(self, func, callback=None): + + cf_future = concurrent.futures.Future() + cf_future.get = cf_future.result # achieve AsyncResult API + + async def f(func, callback): + batch, tasks = await self._to_func_args(func) + key = f'{repr(batch)}-{uuid4().hex}' + + dask_future = self.client.submit( + _TracebackCapturingWrapper(batch), + tasks=tasks, + key=key, + **self.submit_kwargs + ) + self.waiting_futures.add(dask_future) + self._callbacks[dask_future] = callback + self._results[dask_future] = cf_future + + self.client.loop.add_callback(f, func, callback) + + return cf_future + + def retrieve_result_callback(self, out): + return _retrieve_traceback_capturing_wrapped_call(out) + + def abort_everything(self, ensure_ready=True): + """ Tell the client to cancel any task submitted via this instance + + joblib.Parallel will never access those results + """ + with self.waiting_futures.lock: + self.waiting_futures.futures.clear() + while not self.waiting_futures.queue.empty(): + self.waiting_futures.queue.get() + + @contextlib.contextmanager + def retrieval_context(self): + """Override ParallelBackendBase.retrieval_context to avoid deadlocks. + + This removes thread from the worker's thread pool (using 'secede'). + Seceding avoids deadlock in nested parallelism settings. + """ + # See 'joblib.Parallel.__call__' and 'joblib.Parallel.retrieve' for how + # this is used. + if hasattr(thread_state, 'execution_state'): + # we are in a worker. Secede to avoid deadlock. + secede() + + yield + + if hasattr(thread_state, 'execution_state'): + rejoin() diff --git a/testbed/joblib__joblib/joblib/_memmapping_reducer.py b/testbed/joblib__joblib/joblib/_memmapping_reducer.py new file mode 100644 index 0000000000000000000000000000000000000000..13f5c4a17ef0794dc965ca3e3a3ef216125e2946 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_memmapping_reducer.py @@ -0,0 +1,657 @@ +""" +Reducer using memory mapping for numpy arrays +""" +# Author: Thomas Moreau +# Copyright: 2017, Thomas Moreau +# License: BSD 3 clause + +from mmap import mmap +import errno +import os +import stat +import threading +import atexit +import tempfile +import time +import warnings +import weakref +from uuid import uuid4 +from multiprocessing import util + +from pickle import whichmodule, loads, dumps, HIGHEST_PROTOCOL, PicklingError + +try: + WindowsError +except NameError: + WindowsError = type(None) + +try: + import numpy as np + from numpy.lib.stride_tricks import as_strided +except ImportError: + np = None + +from .numpy_pickle import dump, load, load_temporary_memmap +from .backports import make_memmap +from .disk import delete_folder +from .externals.loky.backend import resource_tracker + +# Some system have a ramdisk mounted by default, we can use it instead of /tmp +# as the default folder to dump big arrays to share with subprocesses. +SYSTEM_SHARED_MEM_FS = '/dev/shm' + +# Minimal number of bytes available on SYSTEM_SHARED_MEM_FS to consider using +# it as the default folder to dump big arrays to share with subprocesses. +SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(2e9) + +# Folder and file permissions to chmod temporary files generated by the +# memmapping pool. Only the owner of the Python process can access the +# temporary files and folder. +FOLDER_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR +FILE_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR + +# Set used in joblib workers, referencing the filenames of temporary memmaps +# created by joblib to speed up data communication. In child processes, we add +# a finalizer to these memmaps that sends a maybe_unlink call to the +# resource_tracker, in order to free main memory as fast as possible. +JOBLIB_MMAPS = set() + + +def _log_and_unlink(filename): + from .externals.loky.backend.resource_tracker import _resource_tracker + util.debug( + "[FINALIZER CALL] object mapping to {} about to be deleted," + " decrementing the refcount of the file (pid: {})".format( + os.path.basename(filename), os.getpid())) + _resource_tracker.maybe_unlink(filename, "file") + + +def add_maybe_unlink_finalizer(memmap): + util.debug( + "[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid {})" + "".format(type(memmap), id(memmap), os.path.basename(memmap.filename), + os.getpid())) + weakref.finalize(memmap, _log_and_unlink, memmap.filename) + + +def unlink_file(filename): + """Wrapper around os.unlink with a retry mechanism. + + The retry mechanism has been implemented primarily to overcome a race + condition happening during the finalizer of a np.memmap: when a process + holding the last reference to a mmap-backed np.memmap/np.array is about to + delete this array (and close the reference), it sends a maybe_unlink + request to the resource_tracker. This request can be processed faster than + it takes for the last reference of the memmap to be closed, yielding (on + Windows) a PermissionError in the resource_tracker loop. + """ + NUM_RETRIES = 10 + for retry_no in range(1, NUM_RETRIES + 1): + try: + os.unlink(filename) + break + except PermissionError: + util.debug( + '[ResourceTracker] tried to unlink {}, got ' + 'PermissionError'.format(filename) + ) + if retry_no == NUM_RETRIES: + raise + else: + time.sleep(.2) + except FileNotFoundError: + # In case of a race condition when deleting the temporary folder, + # avoid noisy FileNotFoundError exception in the resource tracker. + pass + + +resource_tracker._CLEANUP_FUNCS['file'] = unlink_file + + +class _WeakArrayKeyMap: + """A variant of weakref.WeakKeyDictionary for unhashable numpy arrays. + + This datastructure will be used with numpy arrays as obj keys, therefore we + do not use the __get__ / __set__ methods to avoid any conflict with the + numpy fancy indexing syntax. + """ + + def __init__(self): + self._data = {} + + def get(self, obj): + ref, val = self._data[id(obj)] + if ref() is not obj: + # In case of race condition with on_destroy: could never be + # triggered by the joblib tests with CPython. + raise KeyError(obj) + return val + + def set(self, obj, value): + key = id(obj) + try: + ref, _ = self._data[key] + if ref() is not obj: + # In case of race condition with on_destroy: could never be + # triggered by the joblib tests with CPython. + raise KeyError(obj) + except KeyError: + # Insert the new entry in the mapping along with a weakref + # callback to automatically delete the entry from the mapping + # as soon as the object used as key is garbage collected. + def on_destroy(_): + del self._data[key] + ref = weakref.ref(obj, on_destroy) + self._data[key] = ref, value + + def __getstate__(self): + raise PicklingError("_WeakArrayKeyMap is not pickleable") + + +############################################################################### +# Support for efficient transient pickling of numpy data structures + + +def _get_backing_memmap(a): + """Recursively look up the original np.memmap instance base if any.""" + b = getattr(a, 'base', None) + if b is None: + # TODO: check scipy sparse datastructure if scipy is installed + # a nor its descendants do not have a memmap base + return None + + elif isinstance(b, mmap): + # a is already a real memmap instance. + return a + + else: + # Recursive exploration of the base ancestry + return _get_backing_memmap(b) + + +def _get_temp_dir(pool_folder_name, temp_folder=None): + """Get the full path to a subfolder inside the temporary folder. + + Parameters + ---------- + pool_folder_name : str + Sub-folder name used for the serialization of a pool instance. + + temp_folder: str, optional + Folder to be used by the pool for memmapping large arrays + for sharing memory with worker processes. If None, this will try in + order: + + - a folder pointed by the JOBLIB_TEMP_FOLDER environment + variable, + - /dev/shm if the folder exists and is writable: this is a + RAMdisk filesystem available by default on modern Linux + distributions, + - the default system temporary folder that can be + overridden with TMP, TMPDIR or TEMP environment + variables, typically /tmp under Unix operating systems. + + Returns + ------- + pool_folder : str + full path to the temporary folder + use_shared_mem : bool + whether the temporary folder is written to the system shared memory + folder or some other temporary folder. + """ + use_shared_mem = False + if temp_folder is None: + temp_folder = os.environ.get('JOBLIB_TEMP_FOLDER', None) + if temp_folder is None: + if os.path.exists(SYSTEM_SHARED_MEM_FS) and hasattr(os, 'statvfs'): + try: + shm_stats = os.statvfs(SYSTEM_SHARED_MEM_FS) + available_nbytes = shm_stats.f_bsize * shm_stats.f_bavail + if available_nbytes > SYSTEM_SHARED_MEM_FS_MIN_SIZE: + # Try to see if we have write access to the shared mem + # folder only if it is reasonably large (that is 2GB or + # more). + temp_folder = SYSTEM_SHARED_MEM_FS + pool_folder = os.path.join(temp_folder, pool_folder_name) + if not os.path.exists(pool_folder): + os.makedirs(pool_folder) + use_shared_mem = True + except (IOError, OSError): + # Missing rights in the /dev/shm partition, fallback to regular + # temp folder. + temp_folder = None + if temp_folder is None: + # Fallback to the default tmp folder, typically /tmp + temp_folder = tempfile.gettempdir() + temp_folder = os.path.abspath(os.path.expanduser(temp_folder)) + pool_folder = os.path.join(temp_folder, pool_folder_name) + return pool_folder, use_shared_mem + + +def has_shareable_memory(a): + """Return True if a is backed by some mmap buffer directly or not.""" + return _get_backing_memmap(a) is not None + + +def _strided_from_memmap(filename, dtype, mode, offset, order, shape, strides, + total_buffer_len, unlink_on_gc_collect): + """Reconstruct an array view on a memory mapped file.""" + if mode == 'w+': + # Do not zero the original data when unpickling + mode = 'r+' + + if strides is None: + # Simple, contiguous memmap + return make_memmap( + filename, dtype=dtype, shape=shape, mode=mode, offset=offset, + order=order, unlink_on_gc_collect=unlink_on_gc_collect + ) + else: + # For non-contiguous data, memmap the total enclosing buffer and then + # extract the non-contiguous view with the stride-tricks API + base = make_memmap( + filename, dtype=dtype, shape=total_buffer_len, offset=offset, + mode=mode, order=order, unlink_on_gc_collect=unlink_on_gc_collect + ) + return as_strided(base, shape=shape, strides=strides) + + +def _reduce_memmap_backed(a, m): + """Pickling reduction for memmap backed arrays. + + a is expected to be an instance of np.ndarray (or np.memmap) + m is expected to be an instance of np.memmap on the top of the ``base`` + attribute ancestry of a. ``m.base`` should be the real python mmap object. + """ + # offset that comes from the striding differences between a and m + util.debug('[MEMMAP REDUCE] reducing a memmap-backed array ' + '(shape, {}, pid: {})'.format(a.shape, os.getpid())) + try: + from numpy.lib.array_utils import byte_bounds + except (ModuleNotFoundError, ImportError): + # Backward-compat for numpy < 2.0 + from numpy import byte_bounds + a_start, a_end = byte_bounds(a) + m_start = byte_bounds(m)[0] + offset = a_start - m_start + + # offset from the backing memmap + offset += m.offset + + if m.flags['F_CONTIGUOUS']: + order = 'F' + else: + # The backing memmap buffer is necessarily contiguous hence C if not + # Fortran + order = 'C' + + if a.flags['F_CONTIGUOUS'] or a.flags['C_CONTIGUOUS']: + # If the array is a contiguous view, no need to pass the strides + strides = None + total_buffer_len = None + else: + # Compute the total number of items to map from which the strided + # view will be extracted. + strides = a.strides + total_buffer_len = (a_end - a_start) // a.itemsize + + return (_strided_from_memmap, + (m.filename, a.dtype, m.mode, offset, order, a.shape, strides, + total_buffer_len, False)) + + +def reduce_array_memmap_backward(a): + """reduce a np.array or a np.memmap from a child process""" + m = _get_backing_memmap(a) + if isinstance(m, np.memmap) and m.filename not in JOBLIB_MMAPS: + # if a is backed by a memmaped file, reconstruct a using the + # memmaped file. + return _reduce_memmap_backed(a, m) + else: + # a is either a regular (not memmap-backed) numpy array, or an array + # backed by a shared temporary file created by joblib. In the latter + # case, in order to limit the lifespan of these temporary files, we + # serialize the memmap as a regular numpy array, and decref the + # file backing the memmap (done implicitly in a previously registered + # finalizer, see ``unlink_on_gc_collect`` for more details) + return ( + loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL), ) + ) + + +class ArrayMemmapForwardReducer(object): + """Reducer callable to dump large arrays to memmap files. + + Parameters + ---------- + max_nbytes: int + Threshold to trigger memmapping of large arrays to files created + a folder. + temp_folder_resolver: callable + An callable in charge of resolving a temporary folder name where files + for backing memmapped arrays are created. + mmap_mode: 'r', 'r+' or 'c' + Mode for the created memmap datastructure. See the documentation of + numpy.memmap for more details. Note: 'w+' is coerced to 'r+' + automatically to avoid zeroing the data on unpickling. + verbose: int, optional, 0 by default + If verbose > 0, memmap creations are logged. + If verbose > 1, both memmap creations, reuse and array pickling are + logged. + prewarm: bool, optional, False by default. + Force a read on newly memmapped array to make sure that OS pre-cache it + memory. This can be useful to avoid concurrent disk access when the + same data array is passed to different worker processes. + """ + + def __init__(self, max_nbytes, temp_folder_resolver, mmap_mode, + unlink_on_gc_collect, verbose=0, prewarm=True): + self._max_nbytes = max_nbytes + self._temp_folder_resolver = temp_folder_resolver + self._mmap_mode = mmap_mode + self.verbose = int(verbose) + if prewarm == "auto": + self._prewarm = not self._temp_folder.startswith( + SYSTEM_SHARED_MEM_FS + ) + else: + self._prewarm = prewarm + self._prewarm = prewarm + self._memmaped_arrays = _WeakArrayKeyMap() + self._temporary_memmaped_filenames = set() + self._unlink_on_gc_collect = unlink_on_gc_collect + + @property + def _temp_folder(self): + return self._temp_folder_resolver() + + def __reduce__(self): + # The ArrayMemmapForwardReducer is passed to the children processes: it + # needs to be pickled but the _WeakArrayKeyMap need to be skipped as + # it's only guaranteed to be consistent with the parent process memory + # garbage collection. + # Although this reducer is pickled, it is not needed in its destination + # process (child processes), as we only use this reducer to send + # memmaps from the parent process to the children processes. For this + # reason, we can afford skipping the resolver, (which would otherwise + # be unpicklable), and pass it as None instead. + args = (self._max_nbytes, None, self._mmap_mode, + self._unlink_on_gc_collect) + kwargs = { + 'verbose': self.verbose, + 'prewarm': self._prewarm, + } + return ArrayMemmapForwardReducer, args, kwargs + + def __call__(self, a): + m = _get_backing_memmap(a) + if m is not None and isinstance(m, np.memmap): + # a is already backed by a memmap file, let's reuse it directly + return _reduce_memmap_backed(a, m) + + if (not a.dtype.hasobject and self._max_nbytes is not None and + a.nbytes > self._max_nbytes): + # check that the folder exists (lazily create the pool temp folder + # if required) + try: + os.makedirs(self._temp_folder) + os.chmod(self._temp_folder, FOLDER_PERMISSIONS) + except OSError as e: + if e.errno != errno.EEXIST: + raise e + + try: + basename = self._memmaped_arrays.get(a) + except KeyError: + # Generate a new unique random filename. The process and thread + # ids are only useful for debugging purpose and to make it + # easier to cleanup orphaned files in case of hard process + # kill (e.g. by "kill -9" or segfault). + basename = "{}-{}-{}.pkl".format( + os.getpid(), id(threading.current_thread()), uuid4().hex) + self._memmaped_arrays.set(a, basename) + filename = os.path.join(self._temp_folder, basename) + + # In case the same array with the same content is passed several + # times to the pool subprocess children, serialize it only once + + is_new_memmap = filename not in self._temporary_memmaped_filenames + + # add the memmap to the list of temporary memmaps created by joblib + self._temporary_memmaped_filenames.add(filename) + + if self._unlink_on_gc_collect: + # Bump reference count of the memmap by 1 to account for + # shared usage of the memmap by a child process. The + # corresponding decref call will be executed upon calling + # resource_tracker.maybe_unlink, registered as a finalizer in + # the child. + # the incref/decref calls here are only possible when the child + # and the parent share the same resource_tracker. It is not the + # case for the multiprocessing backend, but it does not matter + # because unlinking a memmap from a child process is only + # useful to control the memory usage of long-lasting child + # processes, while the multiprocessing-based pools terminate + # their workers at the end of a map() call. + resource_tracker.register(filename, "file") + + if is_new_memmap: + # Incref each temporary memmap created by joblib one extra + # time. This means that these memmaps will only be deleted + # once an extra maybe_unlink() is called, which is done once + # all the jobs have completed (or been canceled) in the + # Parallel._terminate_backend() method. + resource_tracker.register(filename, "file") + + if not os.path.exists(filename): + util.debug( + "[ARRAY DUMP] Pickling new array (shape={}, dtype={}) " + "creating a new memmap at {}".format( + a.shape, a.dtype, filename)) + for dumped_filename in dump(a, filename): + os.chmod(dumped_filename, FILE_PERMISSIONS) + + if self._prewarm: + # Warm up the data by accessing it. This operation ensures + # that the disk access required to create the memmapping + # file are performed in the reducing process and avoids + # concurrent memmap creation in multiple children + # processes. + load(filename, mmap_mode=self._mmap_mode).max() + + else: + util.debug( + "[ARRAY DUMP] Pickling known array (shape={}, dtype={}) " + "reusing memmap file: {}".format( + a.shape, a.dtype, os.path.basename(filename))) + + # The worker process will use joblib.load to memmap the data + return ( + (load_temporary_memmap, (filename, self._mmap_mode, + self._unlink_on_gc_collect)) + ) + else: + # do not convert a into memmap, let pickler do its usual copy with + # the default system pickler + util.debug( + '[ARRAY DUMP] Pickling array (NO MEMMAPPING) (shape={}, ' + ' dtype={}).'.format(a.shape, a.dtype)) + return (loads, (dumps(a, protocol=HIGHEST_PROTOCOL),)) + + +def get_memmapping_reducers( + forward_reducers=None, backward_reducers=None, + temp_folder_resolver=None, max_nbytes=1e6, mmap_mode='r', verbose=0, + prewarm=False, unlink_on_gc_collect=True, **kwargs): + """Construct a pair of memmapping reducer linked to a tmpdir. + + This function manage the creation and the clean up of the temporary folders + underlying the memory maps and should be use to get the reducers necessary + to construct joblib pool or executor. + """ + if forward_reducers is None: + forward_reducers = dict() + if backward_reducers is None: + backward_reducers = dict() + + if np is not None: + # Register smart numpy.ndarray reducers that detects memmap backed + # arrays and that is also able to dump to memmap large in-memory + # arrays over the max_nbytes threshold + forward_reduce_ndarray = ArrayMemmapForwardReducer( + max_nbytes, temp_folder_resolver, mmap_mode, unlink_on_gc_collect, + verbose, prewarm=prewarm) + forward_reducers[np.ndarray] = forward_reduce_ndarray + forward_reducers[np.memmap] = forward_reduce_ndarray + + # Communication from child process to the parent process always + # pickles in-memory numpy.ndarray without dumping them as memmap + # to avoid confusing the caller and make it tricky to collect the + # temporary folder + backward_reducers[np.ndarray] = reduce_array_memmap_backward + backward_reducers[np.memmap] = reduce_array_memmap_backward + + return forward_reducers, backward_reducers + + +class TemporaryResourcesManager(object): + """Stateful object able to manage temporary folder and pickles + + It exposes: + - a per-context folder name resolving API that memmap-based reducers will + rely on to know where to pickle the temporary memmaps + - a temporary file/folder management API that internally uses the + resource_tracker. + """ + + def __init__(self, temp_folder_root=None, context_id=None): + self._current_temp_folder = None + self._temp_folder_root = temp_folder_root + self._use_shared_mem = None + self._cached_temp_folders = dict() + self._id = uuid4().hex + self._finalizers = {} + if context_id is None: + # It would be safer to not assign a default context id (less silent + # bugs), but doing this while maintaining backward compatibility + # with the previous, context-unaware version get_memmaping_executor + # exposes too many low-level details. + context_id = uuid4().hex + self.set_current_context(context_id) + + def set_current_context(self, context_id): + self._current_context_id = context_id + self.register_new_context(context_id) + + def register_new_context(self, context_id): + # Prepare a sub-folder name specific to a context (usually a unique id + # generated by each instance of the Parallel class). Do not create in + # advance to spare FS write access if no array is to be dumped). + if context_id in self._cached_temp_folders: + return + else: + # During its lifecycle, one Parallel object can have several + # executors associated to it (for instance, if a loky worker raises + # an exception, joblib shutdowns the executor and instantly + # recreates a new one before raising the error - see + # ``ensure_ready``. Because we don't want two executors tied to + # the same Parallel object (and thus the same context id) to + # register/use/delete the same folder, we also add an id specific + # to the current Manager (and thus specific to its associated + # executor) to the folder name. + new_folder_name = ( + "joblib_memmapping_folder_{}_{}_{}".format( + os.getpid(), self._id, context_id) + ) + new_folder_path, _ = _get_temp_dir( + new_folder_name, self._temp_folder_root + ) + self.register_folder_finalizer(new_folder_path, context_id) + self._cached_temp_folders[context_id] = new_folder_path + + def resolve_temp_folder_name(self): + """Return a folder name specific to the currently activated context""" + return self._cached_temp_folders[self._current_context_id] + + # resource management API + + def register_folder_finalizer(self, pool_subfolder, context_id): + # Register the garbage collector at program exit in case caller forgets + # to call terminate explicitly: note we do not pass any reference to + # ensure that this callback won't prevent garbage collection of + # parallel instance and related file handler resources such as POSIX + # semaphores and pipes + pool_module_name = whichmodule(delete_folder, 'delete_folder') + resource_tracker.register(pool_subfolder, "folder") + + def _cleanup(): + # In some cases the Python runtime seems to set delete_folder to + # None just before exiting when accessing the delete_folder + # function from the closure namespace. So instead we reimport + # the delete_folder function explicitly. + # https://github.com/joblib/joblib/issues/328 + # We cannot just use from 'joblib.pool import delete_folder' + # because joblib should only use relative imports to allow + # easy vendoring. + delete_folder = __import__( + pool_module_name, fromlist=['delete_folder'] + ).delete_folder + try: + delete_folder(pool_subfolder, allow_non_empty=True) + resource_tracker.unregister(pool_subfolder, "folder") + except OSError: + warnings.warn("Failed to delete temporary folder: {}" + .format(pool_subfolder)) + + self._finalizers[context_id] = atexit.register(_cleanup) + + def _clean_temporary_resources(self, context_id=None, force=False, + allow_non_empty=False): + """Clean temporary resources created by a process-based pool""" + if context_id is None: + # Iterates over a copy of the cache keys to avoid Error due to + # iterating over a changing size dictionary. + for context_id in list(self._cached_temp_folders): + self._clean_temporary_resources( + context_id, force=force, allow_non_empty=allow_non_empty + ) + else: + temp_folder = self._cached_temp_folders.get(context_id) + if temp_folder and os.path.exists(temp_folder): + for filename in os.listdir(temp_folder): + if force: + # Some workers have failed and the ref counted might + # be off. The workers should have shut down by this + # time so forcefully clean up the files. + resource_tracker.unregister( + os.path.join(temp_folder, filename), "file" + ) + else: + resource_tracker.maybe_unlink( + os.path.join(temp_folder, filename), "file" + ) + + # When forcing clean-up, try to delete the folder even if some + # files are still in it. Otherwise, try to delete the folder + allow_non_empty |= force + + # Clean up the folder if possible, either if it is empty or + # if none of the files in it are in used and allow_non_empty. + try: + delete_folder( + temp_folder, allow_non_empty=allow_non_empty + ) + # Forget the folder once it has been deleted + self._cached_temp_folders.pop(context_id, None) + resource_tracker.unregister(temp_folder, "folder") + + # Also cancel the finalizers that gets triggered at gc. + finalizer = self._finalizers.pop(context_id, None) + if finalizer is not None: + atexit.unregister(finalizer) + + except OSError: + # Temporary folder cannot be deleted right now. + # This folder will be cleaned up by an atexit + # finalizer registered by the memmapping_reducer. + pass diff --git a/testbed/joblib__joblib/joblib/_multiprocessing_helpers.py b/testbed/joblib__joblib/joblib/_multiprocessing_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..bde4bc1905311cdc4cd337e9b72e3b24f50a3ed5 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_multiprocessing_helpers.py @@ -0,0 +1,53 @@ +"""Helper module to factorize the conditional multiprocessing import logic + +We use a distinct module to simplify import statements and avoid introducing +circular dependencies (for instance for the assert_spawning name). +""" +import os +import warnings + + +# Obtain possible configuration from the environment, assuming 1 (on) +# by default, upon 0 set to None. Should instructively fail if some non +# 0/1 value is set. +mp = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or None +if mp: + try: + import multiprocessing as mp + import _multiprocessing # noqa + except ImportError: + mp = None + +# 2nd stage: validate that locking is available on the system and +# issue a warning if not +if mp is not None: + try: + # try to create a named semaphore using SemLock to make sure they are + # available on this platform. We use the low level object + # _multiprocessing.SemLock to avoid spawning a resource tracker on + # Unix system or changing the default backend. + import tempfile + from _multiprocessing import SemLock + + _rand = tempfile._RandomNameSequence() + for i in range(100): + try: + name = '/joblib-{}-{}' .format( + os.getpid(), next(_rand)) + _sem = SemLock(0, 0, 1, name=name, unlink=True) + del _sem # cleanup + break + except FileExistsError as e: # pragma: no cover + if i >= 99: + raise FileExistsError( + 'cannot find name for semaphore') from e + except (FileExistsError, AttributeError, ImportError, OSError) as e: + mp = None + warnings.warn('%s. joblib will operate in serial mode' % (e,)) + + +# 3rd stage: backward compat for the assert_spawning helper +if mp is not None: + from multiprocessing.context import assert_spawning +else: + assert_spawning = None diff --git a/testbed/joblib__joblib/joblib/_parallel_backends.py b/testbed/joblib__joblib/joblib/_parallel_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..8201c96bcf61b5c6e61821e7073a0babf6510268 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_parallel_backends.py @@ -0,0 +1,649 @@ +""" +Backends for embarrassingly parallel code. +""" + +import gc +import os +import warnings +import threading +import contextlib +from abc import ABCMeta, abstractmethod + +from ._utils import ( + _TracebackCapturingWrapper, + _retrieve_traceback_capturing_wrapped_call +) + +from ._multiprocessing_helpers import mp + +if mp is not None: + from .pool import MemmappingPool + from multiprocessing.pool import ThreadPool + from .executor import get_memmapping_executor + + # Import loky only if multiprocessing is present + from .externals.loky import process_executor, cpu_count + from .externals.loky.process_executor import ShutdownExecutorError + + +class ParallelBackendBase(metaclass=ABCMeta): + """Helper abc which defines all methods a ParallelBackend must implement""" + + supports_inner_max_num_threads = False + supports_retrieve_callback = False + default_n_jobs = 1 + + @property + def supports_return_generator(self): + return self.supports_retrieve_callback + + @property + def supports_timeout(self): + return self.supports_retrieve_callback + + nesting_level = None + + def __init__(self, nesting_level=None, inner_max_num_threads=None, + **kwargs): + super().__init__(**kwargs) + self.nesting_level = nesting_level + self.inner_max_num_threads = inner_max_num_threads + + MAX_NUM_THREADS_VARS = [ + 'OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', + 'BLIS_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NUMBA_NUM_THREADS', + 'NUMEXPR_NUM_THREADS', + ] + + TBB_ENABLE_IPC_VAR = "ENABLE_IPC" + + @abstractmethod + def effective_n_jobs(self, n_jobs): + """Determine the number of jobs that can actually run in parallel + + n_jobs is the number of workers requested by the callers. Passing + n_jobs=-1 means requesting all available workers for instance matching + the number of CPU cores on the worker host(s). + + This method should return a guesstimate of the number of workers that + can actually perform work concurrently. The primary use case is to make + it possible for the caller to know in how many chunks to slice the + work. + + In general working on larger data chunks is more efficient (less + scheduling overhead and better use of CPU cache prefetching heuristics) + as long as all the workers have enough work to do. + """ + + @abstractmethod + def apply_async(self, func, callback=None): + """Schedule a func to be run""" + + def retrieve_result_callback(self, out): + """Called within the callback function passed in apply_async. + + The argument of this function is the argument given to a callback in + the considered backend. It is supposed to return the outcome of a task + if it succeeded or raise the exception if it failed. + """ + + def configure(self, n_jobs=1, parallel=None, prefer=None, require=None, + **backend_args): + """Reconfigure the backend and return the number of workers. + + This makes it possible to reuse an existing backend instance for + successive independent calls to Parallel with different parameters. + """ + self.parallel = parallel + return self.effective_n_jobs(n_jobs) + + def start_call(self): + """Call-back method called at the beginning of a Parallel call""" + + def stop_call(self): + """Call-back method called at the end of a Parallel call""" + + def terminate(self): + """Shutdown the workers and free the shared memory.""" + + def compute_batch_size(self): + """Determine the optimal batch size""" + return 1 + + def batch_completed(self, batch_size, duration): + """Callback indicate how long it took to run a batch""" + + def get_exceptions(self): + """List of exception types to be captured.""" + return [] + + def abort_everything(self, ensure_ready=True): + """Abort any running tasks + + This is called when an exception has been raised when executing a task + and all the remaining tasks will be ignored and can therefore be + aborted to spare computation resources. + + If ensure_ready is True, the backend should be left in an operating + state as future tasks might be re-submitted via that same backend + instance. + + If ensure_ready is False, the implementer of this method can decide + to leave the backend in a closed / terminated state as no new task + are expected to be submitted to this backend. + + Setting ensure_ready to False is an optimization that can be leveraged + when aborting tasks via killing processes from a local process pool + managed by the backend it-self: if we expect no new tasks, there is no + point in re-creating new workers. + """ + # Does nothing by default: to be overridden in subclasses when + # canceling tasks is possible. + pass + + def get_nested_backend(self): + """Backend instance to be used by nested Parallel calls. + + By default a thread-based backend is used for the first level of + nesting. Beyond, switch to sequential backend to avoid spawning too + many threads on the host. + """ + nesting_level = getattr(self, 'nesting_level', 0) + 1 + if nesting_level > 1: + return SequentialBackend(nesting_level=nesting_level), None + else: + return ThreadingBackend(nesting_level=nesting_level), None + + @contextlib.contextmanager + def retrieval_context(self): + """Context manager to manage an execution context. + + Calls to Parallel.retrieve will be made inside this context. + + By default, this does nothing. It may be useful for subclasses to + handle nested parallelism. In particular, it may be required to avoid + deadlocks if a backend manages a fixed number of workers, when those + workers may be asked to do nested Parallel calls. Without + 'retrieval_context' this could lead to deadlock, as all the workers + managed by the backend may be "busy" waiting for the nested parallel + calls to finish, but the backend has no free workers to execute those + tasks. + """ + yield + + def _prepare_worker_env(self, n_jobs): + """Return environment variables limiting threadpools in external libs. + + This function return a dict containing environment variables to pass + when creating a pool of process. These environment variables limit the + number of threads to `n_threads` for OpenMP, MKL, Accelerated and + OpenBLAS libraries in the child processes. + """ + explicit_n_threads = self.inner_max_num_threads + default_n_threads = max(cpu_count() // n_jobs, 1) + + # Set the inner environment variables to self.inner_max_num_threads if + # it is given. Else, default to cpu_count // n_jobs unless the variable + # is already present in the parent process environment. + env = {} + for var in self.MAX_NUM_THREADS_VARS: + if explicit_n_threads is None: + var_value = os.environ.get(var, default_n_threads) + else: + var_value = explicit_n_threads + + env[var] = str(var_value) + + if self.TBB_ENABLE_IPC_VAR not in os.environ: + # To avoid over-subscription when using TBB, let the TBB schedulers + # use Inter Process Communication to coordinate: + env[self.TBB_ENABLE_IPC_VAR] = "1" + return env + + @staticmethod + def in_main_thread(): + return isinstance(threading.current_thread(), threading._MainThread) + + +class SequentialBackend(ParallelBackendBase): + """A ParallelBackend which will execute all batches sequentially. + + Does not use/create any threading objects, and hence has minimal + overhead. Used when n_jobs == 1. + """ + + uses_threads = True + supports_timeout = False + supports_retrieve_callback = False + supports_sharedmem = True + + def effective_n_jobs(self, n_jobs): + """Determine the number of jobs which are going to run in parallel""" + if n_jobs == 0: + raise ValueError('n_jobs == 0 in Parallel has no meaning') + return 1 + + def apply_async(self, func, callback=None): + """Schedule a func to be run""" + raise RuntimeError("Should never be called for SequentialBackend.") + + def retrieve_result_callback(self, out): + raise RuntimeError("Should never be called for SequentialBackend.") + + def get_nested_backend(self): + # import is not top level to avoid cyclic import errors. + from .parallel import get_active_backend + + # SequentialBackend should neither change the nesting level, the + # default backend or the number of jobs. Just return the current one. + return get_active_backend() + + +class PoolManagerMixin(object): + """A helper class for managing pool of workers.""" + + _pool = None + + def effective_n_jobs(self, n_jobs): + """Determine the number of jobs which are going to run in parallel""" + if n_jobs == 0: + raise ValueError('n_jobs == 0 in Parallel has no meaning') + elif mp is None or n_jobs is None: + # multiprocessing is not available or disabled, fallback + # to sequential mode + return 1 + elif n_jobs < 0: + n_jobs = max(cpu_count() + 1 + n_jobs, 1) + return n_jobs + + def terminate(self): + """Shutdown the process or thread pool""" + if self._pool is not None: + self._pool.close() + self._pool.terminate() # terminate does a join() + self._pool = None + + def _get_pool(self): + """Used by apply_async to make it possible to implement lazy init""" + return self._pool + + def apply_async(self, func, callback=None): + """Schedule a func to be run""" + # Here, we need a wrapper to avoid crashes on KeyboardInterruptErrors. + # We also call the callback on error, to make sure the pool does not + # wait on crashed jobs. + return self._get_pool().apply_async( + _TracebackCapturingWrapper(func), (), + callback=callback, error_callback=callback + ) + + def retrieve_result_callback(self, out): + """Mimic concurrent.futures results, raising an error if needed.""" + return _retrieve_traceback_capturing_wrapped_call(out) + + def abort_everything(self, ensure_ready=True): + """Shutdown the pool and restart a new one with the same parameters""" + self.terminate() + if ensure_ready: + self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel, + **self.parallel._backend_args) + + +class AutoBatchingMixin(object): + """A helper class for automagically batching jobs.""" + + # In seconds, should be big enough to hide multiprocessing dispatching + # overhead. + # This settings was found by running benchmarks/bench_auto_batching.py + # with various parameters on various platforms. + MIN_IDEAL_BATCH_DURATION = .2 + + # Should not be too high to avoid stragglers: long jobs running alone + # on a single worker while other workers have no work to process any more. + MAX_IDEAL_BATCH_DURATION = 2 + + # Batching counters default values + _DEFAULT_EFFECTIVE_BATCH_SIZE = 1 + _DEFAULT_SMOOTHED_BATCH_DURATION = 0.0 + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE + self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION + + def compute_batch_size(self): + """Determine the optimal batch size""" + old_batch_size = self._effective_batch_size + batch_duration = self._smoothed_batch_duration + if (batch_duration > 0 and + batch_duration < self.MIN_IDEAL_BATCH_DURATION): + # The current batch size is too small: the duration of the + # processing of a batch of task is not large enough to hide + # the scheduling overhead. + ideal_batch_size = int(old_batch_size * + self.MIN_IDEAL_BATCH_DURATION / + batch_duration) + # Multiply by two to limit oscilations between min and max. + ideal_batch_size *= 2 + + # dont increase the batch size too fast to limit huge batch sizes + # potentially leading to starving worker + batch_size = min(2 * old_batch_size, ideal_batch_size) + + batch_size = max(batch_size, 1) + + self._effective_batch_size = batch_size + if self.parallel.verbose >= 10: + self.parallel._print( + f"Batch computation too fast ({batch_duration}s.) " + f"Setting batch_size={batch_size}." + ) + elif (batch_duration > self.MAX_IDEAL_BATCH_DURATION and + old_batch_size >= 2): + # The current batch size is too big. If we schedule overly long + # running batches some CPUs might wait with nothing left to do + # while a couple of CPUs a left processing a few long running + # batches. Better reduce the batch size a bit to limit the + # likelihood of scheduling such stragglers. + + # decrease the batch size quickly to limit potential starving + ideal_batch_size = int( + old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration + ) + # Multiply by two to limit oscilations between min and max. + batch_size = max(2 * ideal_batch_size, 1) + self._effective_batch_size = batch_size + if self.parallel.verbose >= 10: + self.parallel._print( + f"Batch computation too slow ({batch_duration}s.) " + f"Setting batch_size={batch_size}." + ) + else: + # No batch size adjustment + batch_size = old_batch_size + + if batch_size != old_batch_size: + # Reset estimation of the smoothed mean batch duration: this + # estimate is updated in the multiprocessing apply_async + # CallBack as long as the batch_size is constant. Therefore + # we need to reset the estimate whenever we re-tune the batch + # size. + self._smoothed_batch_duration = \ + self._DEFAULT_SMOOTHED_BATCH_DURATION + + return batch_size + + def batch_completed(self, batch_size, duration): + """Callback indicate how long it took to run a batch""" + if batch_size == self._effective_batch_size: + # Update the smoothed streaming estimate of the duration of a batch + # from dispatch to completion + old_duration = self._smoothed_batch_duration + if old_duration == self._DEFAULT_SMOOTHED_BATCH_DURATION: + # First record of duration for this batch size after the last + # reset. + new_duration = duration + else: + # Update the exponentially weighted average of the duration of + # batch for the current effective size. + new_duration = 0.8 * old_duration + 0.2 * duration + self._smoothed_batch_duration = new_duration + + def reset_batch_stats(self): + """Reset batch statistics to default values. + + This avoids interferences with future jobs. + """ + self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE + self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION + + +class ThreadingBackend(PoolManagerMixin, ParallelBackendBase): + """A ParallelBackend which will use a thread pool to execute batches in. + + This is a low-overhead backend but it suffers from the Python Global + Interpreter Lock if the called function relies a lot on Python objects. + Mostly useful when the execution bottleneck is a compiled extension that + explicitly releases the GIL (for instance a Cython loop wrapped in a "with + nogil" block or an expensive call to a library such as NumPy). + + The actual thread pool is lazily initialized: the actual thread pool + construction is delayed to the first call to apply_async. + + ThreadingBackend is used as the default backend for nested calls. + """ + + supports_retrieve_callback = True + uses_threads = True + supports_sharedmem = True + + def configure(self, n_jobs=1, parallel=None, **backend_args): + """Build a process or thread pool and return the number of workers""" + n_jobs = self.effective_n_jobs(n_jobs) + if n_jobs == 1: + # Avoid unnecessary overhead and use sequential backend instead. + raise FallbackToBackend( + SequentialBackend(nesting_level=self.nesting_level)) + self.parallel = parallel + self._n_jobs = n_jobs + return n_jobs + + def _get_pool(self): + """Lazily initialize the thread pool + + The actual pool of worker threads is only initialized at the first + call to apply_async. + """ + if self._pool is None: + self._pool = ThreadPool(self._n_jobs) + return self._pool + + +class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin, + ParallelBackendBase): + """A ParallelBackend which will use a multiprocessing.Pool. + + Will introduce some communication and memory overhead when exchanging + input and output data with the with the worker Python processes. + However, does not suffer from the Python Global Interpreter Lock. + """ + + supports_retrieve_callback = True + supports_return_generator = False + + def effective_n_jobs(self, n_jobs): + """Determine the number of jobs which are going to run in parallel. + + This also checks if we are attempting to create a nested parallel + loop. + """ + if mp is None: + return 1 + + if mp.current_process().daemon: + # Daemonic processes cannot have children + if n_jobs != 1: + if inside_dask_worker(): + msg = ( + "Inside a Dask worker with daemon=True, " + "setting n_jobs=1.\nPossible work-arounds:\n" + "- dask.config.set(" + "{'distributed.worker.daemon': False})" + "- set the environment variable " + "DASK_DISTRIBUTED__WORKER__DAEMON=False\n" + "before creating your Dask cluster." + ) + else: + msg = ( + 'Multiprocessing-backed parallel loops ' + 'cannot be nested, setting n_jobs=1' + ) + warnings.warn(msg, stacklevel=3) + return 1 + + if process_executor._CURRENT_DEPTH > 0: + # Mixing loky and multiprocessing in nested loop is not supported + if n_jobs != 1: + warnings.warn( + 'Multiprocessing-backed parallel loops cannot be nested,' + ' below loky, setting n_jobs=1', + stacklevel=3) + return 1 + + elif not (self.in_main_thread() or self.nesting_level == 0): + # Prevent posix fork inside in non-main posix threads + if n_jobs != 1: + warnings.warn( + 'Multiprocessing-backed parallel loops cannot be nested' + ' below threads, setting n_jobs=1', + stacklevel=3) + return 1 + + return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs) + + def configure(self, n_jobs=1, parallel=None, prefer=None, require=None, + **memmappingpool_args): + """Build a process or thread pool and return the number of workers""" + n_jobs = self.effective_n_jobs(n_jobs) + if n_jobs == 1: + raise FallbackToBackend( + SequentialBackend(nesting_level=self.nesting_level)) + + # Make sure to free as much memory as possible before forking + gc.collect() + self._pool = MemmappingPool(n_jobs, **memmappingpool_args) + self.parallel = parallel + return n_jobs + + def terminate(self): + """Shutdown the process or thread pool""" + super(MultiprocessingBackend, self).terminate() + self.reset_batch_stats() + + +class LokyBackend(AutoBatchingMixin, ParallelBackendBase): + """Managing pool of workers with loky instead of multiprocessing.""" + + supports_retrieve_callback = True + supports_inner_max_num_threads = True + + def configure(self, n_jobs=1, parallel=None, prefer=None, require=None, + idle_worker_timeout=300, **memmappingexecutor_args): + """Build a process executor and return the number of workers""" + n_jobs = self.effective_n_jobs(n_jobs) + if n_jobs == 1: + raise FallbackToBackend( + SequentialBackend(nesting_level=self.nesting_level)) + + self._workers = get_memmapping_executor( + n_jobs, timeout=idle_worker_timeout, + env=self._prepare_worker_env(n_jobs=n_jobs), + context_id=parallel._id, **memmappingexecutor_args) + self.parallel = parallel + return n_jobs + + def effective_n_jobs(self, n_jobs): + """Determine the number of jobs which are going to run in parallel""" + if n_jobs == 0: + raise ValueError('n_jobs == 0 in Parallel has no meaning') + elif mp is None or n_jobs is None: + # multiprocessing is not available or disabled, fallback + # to sequential mode + return 1 + elif mp.current_process().daemon: + # Daemonic processes cannot have children + if n_jobs != 1: + if inside_dask_worker(): + msg = ( + "Inside a Dask worker with daemon=True, " + "setting n_jobs=1.\nPossible work-arounds:\n" + "- dask.config.set(" + "{'distributed.worker.daemon': False})\n" + "- set the environment variable " + "DASK_DISTRIBUTED__WORKER__DAEMON=False\n" + "before creating your Dask cluster." + ) + else: + msg = ( + 'Loky-backed parallel loops cannot be called in a' + ' multiprocessing, setting n_jobs=1' + ) + warnings.warn(msg, stacklevel=3) + + return 1 + elif not (self.in_main_thread() or self.nesting_level == 0): + # Prevent posix fork inside in non-main posix threads + if n_jobs != 1: + warnings.warn( + 'Loky-backed parallel loops cannot be nested below ' + 'threads, setting n_jobs=1', + stacklevel=3) + return 1 + elif n_jobs < 0: + n_jobs = max(cpu_count() + 1 + n_jobs, 1) + return n_jobs + + def apply_async(self, func, callback=None): + """Schedule a func to be run""" + future = self._workers.submit(func) + if callback is not None: + future.add_done_callback(callback) + return future + + def retrieve_result_callback(self, out): + try: + return out.result() + except ShutdownExecutorError: + raise RuntimeError( + "The executor underlying Parallel has been shutdown. " + "This is likely due to the garbage collection of a previous " + "generator from a call to Parallel with return_as='generator'." + " Make sure the generator is not garbage collected when " + "submitting a new job or that it is first properly exhausted." + ) + + def terminate(self): + if self._workers is not None: + # Don't terminate the workers as we want to reuse them in later + # calls, but cleanup the temporary resources that the Parallel call + # created. This 'hack' requires a private, low-level operation. + self._workers._temp_folder_manager._clean_temporary_resources( + context_id=self.parallel._id, force=False + ) + self._workers = None + + self.reset_batch_stats() + + def abort_everything(self, ensure_ready=True): + """Shutdown the workers and restart a new one with the same parameters + """ + self._workers.terminate(kill_workers=True) + self._workers = None + + if ensure_ready: + self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel) + + +class FallbackToBackend(Exception): + """Raised when configuration should fallback to another backend""" + + def __init__(self, backend): + self.backend = backend + + +def inside_dask_worker(): + """Check whether the current function is executed inside a Dask worker. + """ + # This function can not be in joblib._dask because there would be a + # circular import: + # _dask imports _parallel_backend that imports _dask ... + try: + from distributed import get_worker + except ImportError: + return False + + try: + get_worker() + return True + except ValueError: + return False diff --git a/testbed/joblib__joblib/joblib/_store_backends.py b/testbed/joblib__joblib/joblib/_store_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..ce9146098a22944e7877fc5fbb4913f8c26869f0 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_store_backends.py @@ -0,0 +1,469 @@ +"""Storage providers backends for Memory caching.""" + +from pickle import PicklingError +import re +import os +import os.path +import datetime +import json +import shutil +import warnings +import collections +import operator +import threading +from abc import ABCMeta, abstractmethod + +from .backports import concurrency_safe_rename +from .disk import mkdirp, memstr_to_bytes, rm_subdirs +from . import numpy_pickle + +CacheItemInfo = collections.namedtuple('CacheItemInfo', + 'path size last_access') + + +class CacheWarning(Warning): + """Warning to capture dump failures except for PicklingError.""" + pass + + +def concurrency_safe_write(object_to_write, filename, write_func): + """Writes an object into a unique file in a concurrency-safe way.""" + thread_id = id(threading.current_thread()) + temporary_filename = '{}.thread-{}-pid-{}'.format( + filename, thread_id, os.getpid()) + write_func(object_to_write, temporary_filename) + + return temporary_filename + + +class StoreBackendBase(metaclass=ABCMeta): + """Helper Abstract Base Class which defines all methods that + a StorageBackend must implement.""" + + location = None + + @abstractmethod + def _open_item(self, f, mode): + """Opens an item on the store and return a file-like object. + + This method is private and only used by the StoreBackendMixin object. + + Parameters + ---------- + f: a file-like object + The file-like object where an item is stored and retrieved + mode: string, optional + the mode in which the file-like object is opened allowed valued are + 'rb', 'wb' + + Returns + ------- + a file-like object + """ + + @abstractmethod + def _item_exists(self, location): + """Checks if an item location exists in the store. + + This method is private and only used by the StoreBackendMixin object. + + Parameters + ---------- + location: string + The location of an item. On a filesystem, this corresponds to the + absolute path, including the filename, of a file. + + Returns + ------- + True if the item exists, False otherwise + """ + + @abstractmethod + def _move_item(self, src, dst): + """Moves an item from src to dst in the store. + + This method is private and only used by the StoreBackendMixin object. + + Parameters + ---------- + src: string + The source location of an item + dst: string + The destination location of an item + """ + + @abstractmethod + def create_location(self, location): + """Creates a location on the store. + + Parameters + ---------- + location: string + The location in the store. On a filesystem, this corresponds to a + directory. + """ + + @abstractmethod + def clear_location(self, location): + """Clears a location on the store. + + Parameters + ---------- + location: string + The location in the store. On a filesystem, this corresponds to a + directory or a filename absolute path + """ + + @abstractmethod + def get_items(self): + """Returns the whole list of items available in the store. + + Returns + ------- + The list of items identified by their ids (e.g filename in a + filesystem). + """ + + @abstractmethod + def configure(self, location, verbose=0, backend_options=dict()): + """Configures the store. + + Parameters + ---------- + location: string + The base location used by the store. On a filesystem, this + corresponds to a directory. + verbose: int + The level of verbosity of the store + backend_options: dict + Contains a dictionary of named parameters used to configure the + store backend. + """ + + +class StoreBackendMixin(object): + """Class providing all logic for managing the store in a generic way. + + The StoreBackend subclass has to implement 3 methods: create_location, + clear_location and configure. The StoreBackend also has to provide + a private _open_item, _item_exists and _move_item methods. The _open_item + method has to have the same signature as the builtin open and return a + file-like object. + """ + + def load_item(self, path, verbose=1, msg=None): + """Load an item from the store given its path as a list of + strings.""" + full_path = os.path.join(self.location, *path) + + if verbose > 1: + if verbose < 10: + print('{0}...'.format(msg)) + else: + print('{0} from {1}'.format(msg, full_path)) + + mmap_mode = (None if not hasattr(self, 'mmap_mode') + else self.mmap_mode) + + filename = os.path.join(full_path, 'output.pkl') + if not self._item_exists(filename): + raise KeyError("Non-existing item (may have been " + "cleared).\nFile %s does not exist" % filename) + + # file-like object cannot be used when mmap_mode is set + if mmap_mode is None: + with self._open_item(filename, "rb") as f: + item = numpy_pickle.load(f) + else: + item = numpy_pickle.load(filename, mmap_mode=mmap_mode) + return item + + def dump_item(self, path, item, verbose=1): + """Dump an item in the store at the path given as a list of + strings.""" + try: + item_path = os.path.join(self.location, *path) + if not self._item_exists(item_path): + self.create_location(item_path) + filename = os.path.join(item_path, 'output.pkl') + if verbose > 10: + print('Persisting in %s' % item_path) + + def write_func(to_write, dest_filename): + with self._open_item(dest_filename, "wb") as f: + try: + numpy_pickle.dump(to_write, f, compress=self.compress) + except PicklingError as e: + # TODO(1.5) turn into error + warnings.warn( + "Unable to cache to disk: failed to pickle " + "output. In version 1.5 this will raise an " + f"exception. Exception: {e}.", + FutureWarning + ) + + self._concurrency_safe_write(item, filename, write_func) + except Exception as e: # noqa: E722 + warnings.warn( + "Unable to cache to disk. Possibly a race condition in the " + f"creation of the directory. Exception: {e}.", + CacheWarning + ) + + def clear_item(self, path): + """Clear the item at the path, given as a list of strings.""" + item_path = os.path.join(self.location, *path) + if self._item_exists(item_path): + self.clear_location(item_path) + + def contains_item(self, path): + """Check if there is an item at the path, given as a list of + strings""" + item_path = os.path.join(self.location, *path) + filename = os.path.join(item_path, 'output.pkl') + + return self._item_exists(filename) + + def get_item_info(self, path): + """Return information about item.""" + return {'location': os.path.join(self.location, + *path)} + + def get_metadata(self, path): + """Return actual metadata of an item.""" + try: + item_path = os.path.join(self.location, *path) + filename = os.path.join(item_path, 'metadata.json') + with self._open_item(filename, 'rb') as f: + return json.loads(f.read().decode('utf-8')) + except: # noqa: E722 + return {} + + def store_metadata(self, path, metadata): + """Store metadata of a computation.""" + try: + item_path = os.path.join(self.location, *path) + self.create_location(item_path) + filename = os.path.join(item_path, 'metadata.json') + + def write_func(to_write, dest_filename): + with self._open_item(dest_filename, "wb") as f: + f.write(json.dumps(to_write).encode('utf-8')) + + self._concurrency_safe_write(metadata, filename, write_func) + except: # noqa: E722 + pass + + def contains_path(self, path): + """Check cached function is available in store.""" + func_path = os.path.join(self.location, *path) + return self.object_exists(func_path) + + def clear_path(self, path): + """Clear all items with a common path in the store.""" + func_path = os.path.join(self.location, *path) + if self._item_exists(func_path): + self.clear_location(func_path) + + def store_cached_func_code(self, path, func_code=None): + """Store the code of the cached function.""" + func_path = os.path.join(self.location, *path) + if not self._item_exists(func_path): + self.create_location(func_path) + + if func_code is not None: + filename = os.path.join(func_path, "func_code.py") + with self._open_item(filename, 'wb') as f: + f.write(func_code.encode('utf-8')) + + def get_cached_func_code(self, path): + """Store the code of the cached function.""" + path += ['func_code.py', ] + filename = os.path.join(self.location, *path) + try: + with self._open_item(filename, 'rb') as f: + return f.read().decode('utf-8') + except: # noqa: E722 + raise + + def get_cached_func_info(self, path): + """Return information related to the cached function if it exists.""" + return {'location': os.path.join(self.location, *path)} + + def clear(self): + """Clear the whole store content.""" + self.clear_location(self.location) + + def enforce_store_limits( + self, bytes_limit, items_limit=None, age_limit=None + ): + """ + Remove the store's oldest files to enforce item, byte, and age limits. + """ + items_to_delete = self._get_items_to_delete( + bytes_limit, items_limit, age_limit + ) + + for item in items_to_delete: + if self.verbose > 10: + print('Deleting item {0}'.format(item)) + try: + self.clear_location(item.path) + except OSError: + # Even with ignore_errors=True shutil.rmtree can raise OSError + # with: + # [Errno 116] Stale file handle if another process has deleted + # the folder already. + pass + + def _get_items_to_delete( + self, bytes_limit, items_limit=None, age_limit=None + ): + """ + Get items to delete to keep the store under size, file, & age limits. + """ + if isinstance(bytes_limit, str): + bytes_limit = memstr_to_bytes(bytes_limit) + + items = self.get_items() + if not items: + return [] + + size = sum(item.size for item in items) + + if bytes_limit is not None: + to_delete_size = size - bytes_limit + else: + to_delete_size = 0 + + if items_limit is not None: + to_delete_items = len(items) - items_limit + else: + to_delete_items = 0 + + if age_limit is not None: + older_item = min(item.last_access for item in items) + deadline = datetime.datetime.now() - age_limit + else: + deadline = None + + if ( + to_delete_size <= 0 and to_delete_items <= 0 + and (deadline is None or older_item > deadline) + ): + return [] + + # We want to delete first the cache items that were accessed a + # long time ago + items.sort(key=operator.attrgetter('last_access')) + + items_to_delete = [] + size_so_far = 0 + items_so_far = 0 + + for item in items: + if ( + (size_so_far >= to_delete_size) + and items_so_far >= to_delete_items + and (deadline is None or deadline < item.last_access) + ): + break + + items_to_delete.append(item) + size_so_far += item.size + items_so_far += 1 + + return items_to_delete + + def _concurrency_safe_write(self, to_write, filename, write_func): + """Writes an object into a file in a concurrency-safe way.""" + temporary_filename = concurrency_safe_write(to_write, + filename, write_func) + self._move_item(temporary_filename, filename) + + def __repr__(self): + """Printable representation of the store location.""" + return '{class_name}(location="{location}")'.format( + class_name=self.__class__.__name__, location=self.location) + + +class FileSystemStoreBackend(StoreBackendBase, StoreBackendMixin): + """A StoreBackend used with local or network file systems.""" + + _open_item = staticmethod(open) + _item_exists = staticmethod(os.path.exists) + _move_item = staticmethod(concurrency_safe_rename) + + def clear_location(self, location): + """Delete location on store.""" + if (location == self.location): + rm_subdirs(location) + else: + shutil.rmtree(location, ignore_errors=True) + + def create_location(self, location): + """Create object location on store""" + mkdirp(location) + + def get_items(self): + """Returns the whole list of items available in the store.""" + items = [] + + for dirpath, _, filenames in os.walk(self.location): + is_cache_hash_dir = re.match('[a-f0-9]{32}', + os.path.basename(dirpath)) + + if is_cache_hash_dir: + output_filename = os.path.join(dirpath, 'output.pkl') + try: + last_access = os.path.getatime(output_filename) + except OSError: + try: + last_access = os.path.getatime(dirpath) + except OSError: + # The directory has already been deleted + continue + + last_access = datetime.datetime.fromtimestamp(last_access) + try: + full_filenames = [os.path.join(dirpath, fn) + for fn in filenames] + dirsize = sum(os.path.getsize(fn) + for fn in full_filenames) + except OSError: + # Either output_filename or one of the files in + # dirpath does not exist any more. We assume this + # directory is being cleaned by another process already + continue + + items.append(CacheItemInfo(dirpath, dirsize, + last_access)) + + return items + + def configure(self, location, verbose=1, backend_options=None): + """Configure the store backend. + + For this backend, valid store options are 'compress' and 'mmap_mode' + """ + if backend_options is None: + backend_options = {} + + # setup location directory + self.location = location + if not os.path.exists(self.location): + mkdirp(self.location) + + # item can be stored compressed for faster I/O + self.compress = backend_options.get('compress', False) + + # FileSystemStoreBackend can be used with mmap_mode options under + # certain conditions. + mmap_mode = backend_options.get('mmap_mode') + if self.compress and mmap_mode is not None: + warnings.warn('Compressed items cannot be memmapped in a ' + 'filesystem store. Option will be ignored.', + stacklevel=2) + + self.mmap_mode = mmap_mode + self.verbose = verbose diff --git a/testbed/joblib__joblib/joblib/_utils.py b/testbed/joblib__joblib/joblib/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7cc64ee51695fe18e2fc8a819696e0246b54f8 --- /dev/null +++ b/testbed/joblib__joblib/joblib/_utils.py @@ -0,0 +1,83 @@ +# Adapted from https://stackoverflow.com/a/9558001/2536294 + +import ast +from dataclasses import dataclass +import operator as op + + +from ._multiprocessing_helpers import mp + +if mp is not None: + from .externals.loky.process_executor import _ExceptionWithTraceback + + +# supported operators +operators = { + ast.Add: op.add, + ast.Sub: op.sub, + ast.Mult: op.mul, + ast.Div: op.truediv, + ast.FloorDiv: op.floordiv, + ast.Mod: op.mod, + ast.Pow: op.pow, + ast.USub: op.neg, +} + + +def eval_expr(expr): + """ + >>> eval_expr('2*6') + 12 + >>> eval_expr('2**6') + 64 + >>> eval_expr('1 + 2*3**(4) / (6 + -7)') + -161.0 + """ + try: + return eval_(ast.parse(expr, mode="eval").body) + except (TypeError, SyntaxError, KeyError) as e: + raise ValueError( + f"{expr!r} is not a valid or supported arithmetic expression." + ) from e + + +def eval_(node): + if isinstance(node, ast.Constant): # + return node.value + elif isinstance(node, ast.BinOp): # + return operators[type(node.op)](eval_(node.left), eval_(node.right)) + elif isinstance(node, ast.UnaryOp): # e.g., -1 + return operators[type(node.op)](eval_(node.operand)) + else: + raise TypeError(node) + + +@dataclass(frozen=True) +class _Sentinel: + """A sentinel to mark a parameter as not explicitly set""" + default_value: object + + def __repr__(self): + return f"default({self.default_value!r})" + + +class _TracebackCapturingWrapper: + """Protect function call and return error with traceback.""" + + def __init__(self, func): + self.func = func + + def __call__(self, **kwargs): + try: + return self.func(**kwargs) + except BaseException as e: + return _ExceptionWithTraceback(e) + + +def _retrieve_traceback_capturing_wrapped_call(out): + if isinstance(out, _ExceptionWithTraceback): + rebuild, args = out.__reduce__() + out = rebuild(*args) + if isinstance(out, BaseException): + raise out + return out diff --git a/testbed/joblib__joblib/joblib/backports.py b/testbed/joblib__joblib/joblib/backports.py new file mode 100644 index 0000000000000000000000000000000000000000..3a14f107689e82b634da6794d30e658fdc000987 --- /dev/null +++ b/testbed/joblib__joblib/joblib/backports.py @@ -0,0 +1,177 @@ +""" +Backports of fixes for joblib dependencies +""" +import os +import re +import time + +from os.path import basename +from multiprocessing import util + + +class Version: + """Backport from deprecated distutils + + We maintain this backport to avoid introducing a new dependency on + `packaging`. + + We might rexplore this choice in the future if all major Python projects + introduce a dependency on packaging anyway. + """ + + def __init__(self, vstring=None): + if vstring: + self.parse(vstring) + + def __repr__(self): + return "%s ('%s')" % (self.__class__.__name__, str(self)) + + def __eq__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c == 0 + + def __lt__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c < 0 + + def __le__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c <= 0 + + def __gt__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c > 0 + + def __ge__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c >= 0 + + +class LooseVersion(Version): + """Backport from deprecated distutils + + We maintain this backport to avoid introducing a new dependency on + `packaging`. + + We might rexplore this choice in the future if all major Python projects + introduce a dependency on packaging anyway. + """ + + component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) + + def __init__(self, vstring=None): + if vstring: + self.parse(vstring) + + def parse(self, vstring): + # I've given up on thinking I can reconstruct the version string + # from the parsed tuple -- so I just store the string here for + # use by __str__ + self.vstring = vstring + components = [x for x in self.component_re.split(vstring) + if x and x != '.'] + for i, obj in enumerate(components): + try: + components[i] = int(obj) + except ValueError: + pass + + self.version = components + + def __str__(self): + return self.vstring + + def __repr__(self): + return "LooseVersion ('%s')" % str(self) + + def _cmp(self, other): + if isinstance(other, str): + other = LooseVersion(other) + elif not isinstance(other, LooseVersion): + return NotImplemented + + if self.version == other.version: + return 0 + if self.version < other.version: + return -1 + if self.version > other.version: + return 1 + + +try: + import numpy as np + + def make_memmap(filename, dtype='uint8', mode='r+', offset=0, + shape=None, order='C', unlink_on_gc_collect=False): + """Custom memmap constructor compatible with numpy.memmap. + + This function: + - is a backport the numpy memmap offset fix (See + https://github.com/numpy/numpy/pull/8443 for more details. + The numpy fix is available starting numpy 1.13) + - adds ``unlink_on_gc_collect``, which specifies explicitly whether + the process re-constructing the memmap owns a reference to the + underlying file. If set to True, it adds a finalizer to the + newly-created memmap that sends a maybe_unlink request for the + memmaped file to resource_tracker. + """ + util.debug( + "[MEMMAP READ] creating a memmap (shape {}, filename {}, " + "pid {})".format(shape, basename(filename), os.getpid()) + ) + + mm = np.memmap(filename, dtype=dtype, mode=mode, offset=offset, + shape=shape, order=order) + if LooseVersion(np.__version__) < '1.13': + mm.offset = offset + if unlink_on_gc_collect: + from ._memmapping_reducer import add_maybe_unlink_finalizer + add_maybe_unlink_finalizer(mm) + return mm +except ImportError: + def make_memmap(filename, dtype='uint8', mode='r+', offset=0, + shape=None, order='C', unlink_on_gc_collect=False): + raise NotImplementedError( + "'joblib.backports.make_memmap' should not be used " + 'if numpy is not installed.') + + +if os.name == 'nt': + # https://github.com/joblib/joblib/issues/540 + access_denied_errors = (5, 13) + from os import replace + + def concurrency_safe_rename(src, dst): + """Renames ``src`` into ``dst`` overwriting ``dst`` if it exists. + + On Windows os.replace can yield permission errors if executed by two + different processes. + """ + max_sleep_time = 1 + total_sleep_time = 0 + sleep_time = 0.001 + while total_sleep_time < max_sleep_time: + try: + replace(src, dst) + break + except Exception as exc: + if getattr(exc, 'winerror', None) in access_denied_errors: + time.sleep(sleep_time) + total_sleep_time += sleep_time + sleep_time *= 2 + else: + raise + else: + raise +else: + from os import replace as concurrency_safe_rename # noqa diff --git a/testbed/joblib__joblib/joblib/compressor.py b/testbed/joblib__joblib/joblib/compressor.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9e2618a48339e1af8cf2da573fd0af8c96f0b0 --- /dev/null +++ b/testbed/joblib__joblib/joblib/compressor.py @@ -0,0 +1,570 @@ +"""Classes and functions for managing compressors.""" + +import io +import zlib +from joblib.backports import LooseVersion + +try: + from threading import RLock +except ImportError: + from dummy_threading import RLock + +try: + import bz2 +except ImportError: + bz2 = None + +try: + import lz4 + from lz4.frame import LZ4FrameFile +except ImportError: + lz4 = None + +try: + import lzma +except ImportError: + lzma = None + + +LZ4_NOT_INSTALLED_ERROR = ('LZ4 is not installed. Install it with pip: ' + 'https://python-lz4.readthedocs.io/') + +# Registered compressors +_COMPRESSORS = {} + +# Magic numbers of supported compression file formats. +_ZFILE_PREFIX = b'ZF' # used with pickle files created before 0.9.3. +_ZLIB_PREFIX = b'\x78' +_GZIP_PREFIX = b'\x1f\x8b' +_BZ2_PREFIX = b'BZ' +_XZ_PREFIX = b'\xfd\x37\x7a\x58\x5a' +_LZMA_PREFIX = b'\x5d\x00' +_LZ4_PREFIX = b'\x04\x22\x4D\x18' + + +def register_compressor(compressor_name, compressor, + force=False): + """Register a new compressor. + + Parameters + ---------- + compressor_name: str. + The name of the compressor. + compressor: CompressorWrapper + An instance of a 'CompressorWrapper'. + """ + global _COMPRESSORS + if not isinstance(compressor_name, str): + raise ValueError("Compressor name should be a string, " + "'{}' given.".format(compressor_name)) + + if not isinstance(compressor, CompressorWrapper): + raise ValueError("Compressor should implement the CompressorWrapper " + "interface, '{}' given.".format(compressor)) + + if (compressor.fileobj_factory is not None and + (not hasattr(compressor.fileobj_factory, 'read') or + not hasattr(compressor.fileobj_factory, 'write') or + not hasattr(compressor.fileobj_factory, 'seek') or + not hasattr(compressor.fileobj_factory, 'tell'))): + raise ValueError("Compressor 'fileobj_factory' attribute should " + "implement the file object interface, '{}' given." + .format(compressor.fileobj_factory)) + + if compressor_name in _COMPRESSORS and not force: + raise ValueError("Compressor '{}' already registered." + .format(compressor_name)) + + _COMPRESSORS[compressor_name] = compressor + + +class CompressorWrapper(): + """A wrapper around a compressor file object. + + Attributes + ---------- + obj: a file-like object + The object must implement the buffer interface and will be used + internally to compress/decompress the data. + prefix: bytestring + A bytestring corresponding to the magic number that identifies the + file format associated to the compressor. + extension: str + The file extension used to automatically select this compressor during + a dump to a file. + """ + + def __init__(self, obj, prefix=b'', extension=''): + self.fileobj_factory = obj + self.prefix = prefix + self.extension = extension + + def compressor_file(self, fileobj, compresslevel=None): + """Returns an instance of a compressor file object.""" + if compresslevel is None: + return self.fileobj_factory(fileobj, 'wb') + else: + return self.fileobj_factory(fileobj, 'wb', + compresslevel=compresslevel) + + def decompressor_file(self, fileobj): + """Returns an instance of a decompressor file object.""" + return self.fileobj_factory(fileobj, 'rb') + + +class BZ2CompressorWrapper(CompressorWrapper): + + prefix = _BZ2_PREFIX + extension = '.bz2' + + def __init__(self): + if bz2 is not None: + self.fileobj_factory = bz2.BZ2File + else: + self.fileobj_factory = None + + def _check_versions(self): + if bz2 is None: + raise ValueError('bz2 module is not compiled on your python ' + 'standard library.') + + def compressor_file(self, fileobj, compresslevel=None): + """Returns an instance of a compressor file object.""" + self._check_versions() + if compresslevel is None: + return self.fileobj_factory(fileobj, 'wb') + else: + return self.fileobj_factory(fileobj, 'wb', + compresslevel=compresslevel) + + def decompressor_file(self, fileobj): + """Returns an instance of a decompressor file object.""" + self._check_versions() + fileobj = self.fileobj_factory(fileobj, 'rb') + return fileobj + + +class LZMACompressorWrapper(CompressorWrapper): + + prefix = _LZMA_PREFIX + extension = '.lzma' + _lzma_format_name = 'FORMAT_ALONE' + + def __init__(self): + if lzma is not None: + self.fileobj_factory = lzma.LZMAFile + self._lzma_format = getattr(lzma, self._lzma_format_name) + else: + self.fileobj_factory = None + + def _check_versions(self): + if lzma is None: + raise ValueError('lzma module is not compiled on your python ' + 'standard library.') + + def compressor_file(self, fileobj, compresslevel=None): + """Returns an instance of a compressor file object.""" + if compresslevel is None: + return self.fileobj_factory(fileobj, 'wb', + format=self._lzma_format) + else: + return self.fileobj_factory(fileobj, 'wb', + format=self._lzma_format, + preset=compresslevel) + + def decompressor_file(self, fileobj): + """Returns an instance of a decompressor file object.""" + return lzma.LZMAFile(fileobj, 'rb') + + +class XZCompressorWrapper(LZMACompressorWrapper): + + prefix = _XZ_PREFIX + extension = '.xz' + _lzma_format_name = 'FORMAT_XZ' + + +class LZ4CompressorWrapper(CompressorWrapper): + + prefix = _LZ4_PREFIX + extension = '.lz4' + + def __init__(self): + if lz4 is not None: + self.fileobj_factory = LZ4FrameFile + else: + self.fileobj_factory = None + + def _check_versions(self): + if lz4 is None: + raise ValueError(LZ4_NOT_INSTALLED_ERROR) + lz4_version = lz4.__version__ + if lz4_version.startswith("v"): + lz4_version = lz4_version[1:] + if LooseVersion(lz4_version) < LooseVersion('0.19'): + raise ValueError(LZ4_NOT_INSTALLED_ERROR) + + def compressor_file(self, fileobj, compresslevel=None): + """Returns an instance of a compressor file object.""" + self._check_versions() + if compresslevel is None: + return self.fileobj_factory(fileobj, 'wb') + else: + return self.fileobj_factory(fileobj, 'wb', + compression_level=compresslevel) + + def decompressor_file(self, fileobj): + """Returns an instance of a decompressor file object.""" + self._check_versions() + return self.fileobj_factory(fileobj, 'rb') + + +############################################################################### +# base file compression/decompression object definition +_MODE_CLOSED = 0 +_MODE_READ = 1 +_MODE_READ_EOF = 2 +_MODE_WRITE = 3 +_BUFFER_SIZE = 8192 + + +class BinaryZlibFile(io.BufferedIOBase): + """A file object providing transparent zlib (de)compression. + + TODO python2_drop: is it still needed since we dropped Python 2 support A + BinaryZlibFile can act as a wrapper for an existing file object, or refer + directly to a named file on disk. + + Note that BinaryZlibFile provides only a *binary* file interface: data read + is returned as bytes, and data to be written should be given as bytes. + + This object is an adaptation of the BZ2File object and is compatible with + versions of python >= 2.7. + + If filename is a str or bytes object, it gives the name + of the file to be opened. Otherwise, it should be a file object, + which will be used to read or write the compressed data. + + mode can be 'rb' for reading (default) or 'wb' for (over)writing + + If mode is 'wb', compresslevel can be a number between 1 + and 9 specifying the level of compression: 1 produces the least + compression, and 9 produces the most compression. 3 is the default. + """ + + wbits = zlib.MAX_WBITS + + def __init__(self, filename, mode="rb", compresslevel=3): + # This lock must be recursive, so that BufferedIOBase's + # readline(), readlines() and writelines() don't deadlock. + self._lock = RLock() + self._fp = None + self._closefp = False + self._mode = _MODE_CLOSED + self._pos = 0 + self._size = -1 + self.compresslevel = compresslevel + + if not isinstance(compresslevel, int) or not (1 <= compresslevel <= 9): + raise ValueError("'compresslevel' must be an integer " + "between 1 and 9. You provided 'compresslevel={}'" + .format(compresslevel)) + + if mode == "rb": + self._mode = _MODE_READ + self._decompressor = zlib.decompressobj(self.wbits) + self._buffer = b"" + self._buffer_offset = 0 + elif mode == "wb": + self._mode = _MODE_WRITE + self._compressor = zlib.compressobj(self.compresslevel, + zlib.DEFLATED, self.wbits, + zlib.DEF_MEM_LEVEL, 0) + else: + raise ValueError("Invalid mode: %r" % (mode,)) + + if isinstance(filename, str): + self._fp = io.open(filename, mode) + self._closefp = True + elif hasattr(filename, "read") or hasattr(filename, "write"): + self._fp = filename + else: + raise TypeError("filename must be a str or bytes object, " + "or a file") + + def close(self): + """Flush and close the file. + + May be called more than once without error. Once the file is + closed, any other operation on it will raise a ValueError. + """ + with self._lock: + if self._mode == _MODE_CLOSED: + return + try: + if self._mode in (_MODE_READ, _MODE_READ_EOF): + self._decompressor = None + elif self._mode == _MODE_WRITE: + self._fp.write(self._compressor.flush()) + self._compressor = None + finally: + try: + if self._closefp: + self._fp.close() + finally: + self._fp = None + self._closefp = False + self._mode = _MODE_CLOSED + self._buffer = b"" + self._buffer_offset = 0 + + @property + def closed(self): + """True if this file is closed.""" + return self._mode == _MODE_CLOSED + + def fileno(self): + """Return the file descriptor for the underlying file.""" + self._check_not_closed() + return self._fp.fileno() + + def seekable(self): + """Return whether the file supports seeking.""" + return self.readable() and self._fp.seekable() + + def readable(self): + """Return whether the file was opened for reading.""" + self._check_not_closed() + return self._mode in (_MODE_READ, _MODE_READ_EOF) + + def writable(self): + """Return whether the file was opened for writing.""" + self._check_not_closed() + return self._mode == _MODE_WRITE + + # Mode-checking helper functions. + + def _check_not_closed(self): + if self.closed: + fname = getattr(self._fp, 'name', None) + msg = "I/O operation on closed file" + if fname is not None: + msg += " {}".format(fname) + msg += "." + raise ValueError(msg) + + def _check_can_read(self): + if self._mode not in (_MODE_READ, _MODE_READ_EOF): + self._check_not_closed() + raise io.UnsupportedOperation("File not open for reading") + + def _check_can_write(self): + if self._mode != _MODE_WRITE: + self._check_not_closed() + raise io.UnsupportedOperation("File not open for writing") + + def _check_can_seek(self): + if self._mode not in (_MODE_READ, _MODE_READ_EOF): + self._check_not_closed() + raise io.UnsupportedOperation("Seeking is only supported " + "on files open for reading") + if not self._fp.seekable(): + raise io.UnsupportedOperation("The underlying file object " + "does not support seeking") + + # Fill the readahead buffer if it is empty. Returns False on EOF. + def _fill_buffer(self): + if self._mode == _MODE_READ_EOF: + return False + # Depending on the input data, our call to the decompressor may not + # return any data. In this case, try again after reading another block. + while self._buffer_offset == len(self._buffer): + try: + rawblock = (self._decompressor.unused_data or + self._fp.read(_BUFFER_SIZE)) + if not rawblock: + raise EOFError + except EOFError: + # End-of-stream marker and end of file. We're good. + self._mode = _MODE_READ_EOF + self._size = self._pos + return False + else: + self._buffer = self._decompressor.decompress(rawblock) + self._buffer_offset = 0 + return True + + # Read data until EOF. + # If return_data is false, consume the data without returning it. + def _read_all(self, return_data=True): + # The loop assumes that _buffer_offset is 0. Ensure that this is true. + self._buffer = self._buffer[self._buffer_offset:] + self._buffer_offset = 0 + + blocks = [] + while self._fill_buffer(): + if return_data: + blocks.append(self._buffer) + self._pos += len(self._buffer) + self._buffer = b"" + if return_data: + return b"".join(blocks) + + # Read a block of up to n bytes. + # If return_data is false, consume the data without returning it. + def _read_block(self, n_bytes, return_data=True): + # If we have enough data buffered, return immediately. + end = self._buffer_offset + n_bytes + if end <= len(self._buffer): + data = self._buffer[self._buffer_offset: end] + self._buffer_offset = end + self._pos += len(data) + return data if return_data else None + + # The loop assumes that _buffer_offset is 0. Ensure that this is true. + self._buffer = self._buffer[self._buffer_offset:] + self._buffer_offset = 0 + + blocks = [] + while n_bytes > 0 and self._fill_buffer(): + if n_bytes < len(self._buffer): + data = self._buffer[:n_bytes] + self._buffer_offset = n_bytes + else: + data = self._buffer + self._buffer = b"" + if return_data: + blocks.append(data) + self._pos += len(data) + n_bytes -= len(data) + if return_data: + return b"".join(blocks) + + def read(self, size=-1): + """Read up to size uncompressed bytes from the file. + + If size is negative or omitted, read until EOF is reached. + Returns b'' if the file is already at EOF. + """ + with self._lock: + self._check_can_read() + if size == 0: + return b"" + elif size < 0: + return self._read_all() + else: + return self._read_block(size) + + def readinto(self, b): + """Read up to len(b) bytes into b. + + Returns the number of bytes read (0 for EOF). + """ + with self._lock: + return io.BufferedIOBase.readinto(self, b) + + def write(self, data): + """Write a byte string to the file. + + Returns the number of uncompressed bytes written, which is + always len(data). Note that due to buffering, the file on disk + may not reflect the data written until close() is called. + """ + with self._lock: + self._check_can_write() + # Convert data type if called by io.BufferedWriter. + if isinstance(data, memoryview): + data = data.tobytes() + + compressed = self._compressor.compress(data) + self._fp.write(compressed) + self._pos += len(data) + return len(data) + + # Rewind the file to the beginning of the data stream. + def _rewind(self): + self._fp.seek(0, 0) + self._mode = _MODE_READ + self._pos = 0 + self._decompressor = zlib.decompressobj(self.wbits) + self._buffer = b"" + self._buffer_offset = 0 + + def seek(self, offset, whence=0): + """Change the file position. + + The new position is specified by offset, relative to the + position indicated by whence. Values for whence are: + + 0: start of stream (default); offset must not be negative + 1: current stream position + 2: end of stream; offset must not be positive + + Returns the new file position. + + Note that seeking is emulated, so depending on the parameters, + this operation may be extremely slow. + """ + with self._lock: + self._check_can_seek() + + # Recalculate offset as an absolute file position. + if whence == 0: + pass + elif whence == 1: + offset = self._pos + offset + elif whence == 2: + # Seeking relative to EOF - we need to know the file's size. + if self._size < 0: + self._read_all(return_data=False) + offset = self._size + offset + else: + raise ValueError("Invalid value for whence: %s" % (whence,)) + + # Make it so that offset is the number of bytes to skip forward. + if offset < self._pos: + self._rewind() + else: + offset -= self._pos + + # Read and discard data until we reach the desired position. + self._read_block(offset, return_data=False) + + return self._pos + + def tell(self): + """Return the current file position.""" + with self._lock: + self._check_not_closed() + return self._pos + + +class ZlibCompressorWrapper(CompressorWrapper): + + def __init__(self): + CompressorWrapper.__init__(self, obj=BinaryZlibFile, + prefix=_ZLIB_PREFIX, extension='.z') + + +class BinaryGzipFile(BinaryZlibFile): + """A file object providing transparent gzip (de)compression. + + If filename is a str or bytes object, it gives the name + of the file to be opened. Otherwise, it should be a file object, + which will be used to read or write the compressed data. + + mode can be 'rb' for reading (default) or 'wb' for (over)writing + + If mode is 'wb', compresslevel can be a number between 1 + and 9 specifying the level of compression: 1 produces the least + compression, and 9 produces the most compression. 3 is the default. + """ + + wbits = 31 # zlib compressor/decompressor wbits value for gzip format. + + +class GzipCompressorWrapper(CompressorWrapper): + + def __init__(self): + CompressorWrapper.__init__(self, obj=BinaryGzipFile, + prefix=_GZIP_PREFIX, extension='.gz') diff --git a/testbed/joblib__joblib/joblib/disk.py b/testbed/joblib__joblib/joblib/disk.py new file mode 100644 index 0000000000000000000000000000000000000000..32fbb89f6dc6c9c7df532c5fefa14934f16321f6 --- /dev/null +++ b/testbed/joblib__joblib/joblib/disk.py @@ -0,0 +1,136 @@ +""" +Disk management utilities. +""" + +# Authors: Gael Varoquaux +# Lars Buitinck +# Copyright (c) 2010 Gael Varoquaux +# License: BSD Style, 3 clauses. + + +import os +import sys +import time +import errno +import shutil + +from multiprocessing import util + + +try: + WindowsError +except NameError: + WindowsError = OSError + + +def disk_used(path): + """ Return the disk usage in a directory.""" + size = 0 + for file in os.listdir(path) + ['.']: + stat = os.stat(os.path.join(path, file)) + if hasattr(stat, 'st_blocks'): + size += stat.st_blocks * 512 + else: + # on some platform st_blocks is not available (e.g., Windows) + # approximate by rounding to next multiple of 512 + size += (stat.st_size // 512 + 1) * 512 + # We need to convert to int to avoid having longs on some systems (we + # don't want longs to avoid problems we SQLite) + return int(size / 1024.) + + +def memstr_to_bytes(text): + """ Convert a memory text to its value in bytes. + """ + kilo = 1024 + units = dict(K=kilo, M=kilo ** 2, G=kilo ** 3) + try: + size = int(units[text[-1]] * float(text[:-1])) + except (KeyError, ValueError) as e: + raise ValueError( + "Invalid literal for size give: %s (type %s) should be " + "alike '10G', '500M', '50K'." % (text, type(text))) from e + return size + + +def mkdirp(d): + """Ensure directory d exists (like mkdir -p on Unix) + No guarantee that the directory is writable. + """ + try: + os.makedirs(d) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + +# if a rmtree operation fails in rm_subdirs, wait for this much time (in secs), +# then retry up to RM_SUBDIRS_N_RETRY times. If it still fails, raise the +# exception. this mechanism ensures that the sub-process gc have the time to +# collect and close the memmaps before we fail. +RM_SUBDIRS_RETRY_TIME = 0.1 +RM_SUBDIRS_N_RETRY = 10 + + +def rm_subdirs(path, onerror=None): + """Remove all subdirectories in this path. + + The directory indicated by `path` is left in place, and its subdirectories + are erased. + + If onerror is set, it is called to handle the error with arguments (func, + path, exc_info) where func is os.listdir, os.remove, or os.rmdir; + path is the argument to that function that caused it to fail; and + exc_info is a tuple returned by sys.exc_info(). If onerror is None, + an exception is raised. + """ + + # NOTE this code is adapted from the one in shutil.rmtree, and is + # just as fast + + names = [] + try: + names = os.listdir(path) + except os.error: + if onerror is not None: + onerror(os.listdir, path, sys.exc_info()) + else: + raise + + for name in names: + fullname = os.path.join(path, name) + delete_folder(fullname, onerror=onerror) + + +def delete_folder(folder_path, onerror=None, allow_non_empty=True): + """Utility function to cleanup a temporary folder if it still exists.""" + if os.path.isdir(folder_path): + if onerror is not None: + shutil.rmtree(folder_path, False, onerror) + else: + # allow the rmtree to fail once, wait and re-try. + # if the error is raised again, fail + err_count = 0 + while True: + files = os.listdir(folder_path) + try: + if len(files) == 0 or allow_non_empty: + shutil.rmtree( + folder_path, ignore_errors=False, onerror=None + ) + util.debug( + "Successfully deleted {}".format(folder_path)) + break + else: + raise OSError( + "Expected empty folder {} but got {} " + "files.".format(folder_path, len(files)) + ) + except (OSError, WindowsError): + err_count += 1 + if err_count > RM_SUBDIRS_N_RETRY: + # the folder cannot be deleted right now. It maybe + # because some temporary files have not been deleted + # yet. + raise + time.sleep(RM_SUBDIRS_RETRY_TIME) diff --git a/testbed/joblib__joblib/joblib/executor.py b/testbed/joblib__joblib/joblib/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..6837a7d147411cd74034a078ff98cab916ec36ce --- /dev/null +++ b/testbed/joblib__joblib/joblib/executor.py @@ -0,0 +1,117 @@ +"""Utility function to construct a loky.ReusableExecutor with custom pickler. + +This module provides efficient ways of working with data stored in +shared memory with numpy.memmap arrays without inducing any memory +copy between the parent and child processes. +""" +# Author: Thomas Moreau +# Copyright: 2017, Thomas Moreau +# License: BSD 3 clause + +from ._memmapping_reducer import get_memmapping_reducers +from ._memmapping_reducer import TemporaryResourcesManager +from .externals.loky.reusable_executor import _ReusablePoolExecutor + + +_executor_args = None + + +def get_memmapping_executor(n_jobs, **kwargs): + return MemmappingExecutor.get_memmapping_executor(n_jobs, **kwargs) + + +class MemmappingExecutor(_ReusablePoolExecutor): + + @classmethod + def get_memmapping_executor(cls, n_jobs, timeout=300, initializer=None, + initargs=(), env=None, temp_folder=None, + context_id=None, **backend_args): + """Factory for ReusableExecutor with automatic memmapping for large + numpy arrays. + """ + global _executor_args + # Check if we can reuse the executor here instead of deferring the test + # to loky as the reducers are objects that changes at each call. + executor_args = backend_args.copy() + executor_args.update(env if env else {}) + executor_args.update(dict( + timeout=timeout, initializer=initializer, initargs=initargs)) + reuse = _executor_args is None or _executor_args == executor_args + _executor_args = executor_args + + manager = TemporaryResourcesManager(temp_folder) + + # reducers access the temporary folder in which to store temporary + # pickles through a call to manager.resolve_temp_folder_name. resolving + # the folder name dynamically is useful to use different folders across + # calls of a same reusable executor + job_reducers, result_reducers = get_memmapping_reducers( + unlink_on_gc_collect=True, + temp_folder_resolver=manager.resolve_temp_folder_name, + **backend_args) + _executor, executor_is_reused = super().get_reusable_executor( + n_jobs, job_reducers=job_reducers, result_reducers=result_reducers, + reuse=reuse, timeout=timeout, initializer=initializer, + initargs=initargs, env=env + ) + + if not executor_is_reused: + # Only set a _temp_folder_manager for new executors. Reused + # executors already have a _temporary_folder_manager that must not + # be re-assigned like that because it is referenced in various + # places in the reducing machinery of the executor. + _executor._temp_folder_manager = manager + + if context_id is not None: + # Only register the specified context once we know which manager + # the current executor is using, in order to not register an atexit + # finalizer twice for the same folder. + _executor._temp_folder_manager.register_new_context(context_id) + + return _executor + + def terminate(self, kill_workers=False): + + self.shutdown(kill_workers=kill_workers) + + # When workers are killed in a brutal manner, they cannot execute the + # finalizer of their shared memmaps. The refcount of those memmaps may + # be off by an unknown number, so instead of decref'ing them, we force + # delete the whole temporary folder, and unregister them. There is no + # risk of PermissionError at folder deletion because at this + # point, all child processes are dead, so all references to temporary + # memmaps are closed. Otherwise, just try to delete as much as possible + # with allow_non_empty=True but if we can't, it will be clean up later + # on by the resource_tracker. + with self._submit_resize_lock: + self._temp_folder_manager._clean_temporary_resources( + force=kill_workers, allow_non_empty=True + ) + + @property + def _temp_folder(self): + # Legacy property in tests. could be removed if we refactored the + # memmapping tests. SHOULD ONLY BE USED IN TESTS! + # We cache this property because it is called late in the tests - at + # this point, all context have been unregistered, and + # resolve_temp_folder_name raises an error. + if getattr(self, '_cached_temp_folder', None) is not None: + return self._cached_temp_folder + else: + self._cached_temp_folder = self._temp_folder_manager.resolve_temp_folder_name() # noqa + return self._cached_temp_folder + + +class _TestingMemmappingExecutor(MemmappingExecutor): + """Wrapper around ReusableExecutor to ease memmapping testing with Pool + and Executor. This is only for testing purposes. + + """ + def apply_async(self, func, args): + """Schedule a func to be run""" + future = self.submit(func, *args) + future.get = future.result + return future + + def map(self, f, *args): + return list(super().map(f, *args)) diff --git a/testbed/joblib__joblib/joblib/externals/__init__.py b/testbed/joblib__joblib/joblib/externals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/joblib__joblib/joblib/externals/cloudpickle/__init__.py b/testbed/joblib__joblib/joblib/externals/cloudpickle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58a8d086ff616b2ef75ab0d788d990e749f96e8d --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/cloudpickle/__init__.py @@ -0,0 +1,18 @@ +from . import cloudpickle +from .cloudpickle import * # noqa + +__doc__ = cloudpickle.__doc__ + +__version__ = "3.0.0" + +__all__ = [ # noqa + "__version__", + "Pickler", + "CloudPickler", + "dumps", + "loads", + "dump", + "load", + "register_pickle_by_value", + "unregister_pickle_by_value", +] diff --git a/testbed/joblib__joblib/joblib/externals/cloudpickle/cloudpickle.py b/testbed/joblib__joblib/joblib/externals/cloudpickle/cloudpickle.py new file mode 100644 index 0000000000000000000000000000000000000000..eb43a9676bbb11bdecf187e7f6cde51f793ff3fc --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/cloudpickle/cloudpickle.py @@ -0,0 +1,1487 @@ +"""Pickler class to extend the standard pickle.Pickler functionality + +The main objective is to make it natural to perform distributed computing on +clusters (such as PySpark, Dask, Ray...) with interactively defined code +(functions, classes, ...) written in notebooks or console. + +In particular this pickler adds the following features: +- serialize interactively-defined or locally-defined functions, classes, + enums, typevars, lambdas and nested functions to compiled byte code; +- deal with some other non-serializable objects in an ad-hoc manner where + applicable. + +This pickler is therefore meant to be used for the communication between short +lived Python processes running the same version of Python and libraries. In +particular, it is not meant to be used for long term storage of Python objects. + +It does not include an unpickler, as standard Python unpickling suffices. + +This module was extracted from the `cloud` package, developed by `PiCloud, Inc. +`_. + +Copyright (c) 2012-now, CloudPickle developers and contributors. +Copyright (c) 2012, Regents of the University of California. +Copyright (c) 2009 `PiCloud, Inc. `_. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the University of California, Berkeley nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS 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 THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import _collections_abc +from collections import ChainMap, OrderedDict +import abc +import builtins +import copyreg +import dataclasses +import dis +from enum import Enum +import io +import itertools +import logging +import opcode +import pickle +from pickle import _getattribute +import platform +import struct +import sys +import threading +import types +import typing +import uuid +import warnings +import weakref + +# The following import is required to be imported in the cloudpickle +# namespace to be able to load pickle files generated with older versions of +# cloudpickle. See: tests/test_backward_compat.py +from types import CellType # noqa: F401 + + +# cloudpickle is meant for inter process communication: we expect all +# communicating processes to run the same Python version hence we favor +# communication speed over compatibility: +DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL + +# Names of modules whose resources should be treated as dynamic. +_PICKLE_BY_VALUE_MODULES = set() + +# Track the provenance of reconstructed dynamic classes to make it possible to +# reconstruct instances from the matching singleton class definition when +# appropriate and preserve the usual "isinstance" semantics of Python objects. +_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary() +_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary() +_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock() + +PYPY = platform.python_implementation() == "PyPy" + +builtin_code_type = None +if PYPY: + # builtin-code objects only exist in pypy + builtin_code_type = type(float.__new__.__code__) + +_extract_code_globals_cache = weakref.WeakKeyDictionary() + + +def _get_or_create_tracker_id(class_def): + with _DYNAMIC_CLASS_TRACKER_LOCK: + class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def) + if class_tracker_id is None: + class_tracker_id = uuid.uuid4().hex + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def + return class_tracker_id + + +def _lookup_class_or_track(class_tracker_id, class_def): + if class_tracker_id is not None: + with _DYNAMIC_CLASS_TRACKER_LOCK: + class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault( + class_tracker_id, class_def + ) + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + return class_def + + +def register_pickle_by_value(module): + """Register a module to make it functions and classes picklable by value. + + By default, functions and classes that are attributes of an importable + module are to be pickled by reference, that is relying on re-importing + the attribute from the module at load time. + + If `register_pickle_by_value(module)` is called, all its functions and + classes are subsequently to be pickled by value, meaning that they can + be loaded in Python processes where the module is not importable. + + This is especially useful when developing a module in a distributed + execution environment: restarting the client Python process with the new + source code is enough: there is no need to re-install the new version + of the module on all the worker nodes nor to restart the workers. + + Note: this feature is considered experimental. See the cloudpickle + README.md file for more details and limitations. + """ + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + # In the future, cloudpickle may need a way to access any module registered + # for pickling by value in order to introspect relative imports inside + # functions pickled by value. (see + # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633). + # This access can be ensured by checking that module is present in + # sys.modules at registering time and assuming that it will still be in + # there when accessed during pickling. Another alternative would be to + # store a weakref to the module. Even though cloudpickle does not implement + # this introspection yet, in order to avoid a possible breaking change + # later, we still enforce the presence of module inside sys.modules. + if module.__name__ not in sys.modules: + raise ValueError( + f"{module} was not imported correctly, have you used an " + "`import` statement to access it?" + ) + _PICKLE_BY_VALUE_MODULES.add(module.__name__) + + +def unregister_pickle_by_value(module): + """Unregister that the input module should be pickled by value.""" + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + if module.__name__ not in _PICKLE_BY_VALUE_MODULES: + raise ValueError(f"{module} is not registered for pickle by value") + else: + _PICKLE_BY_VALUE_MODULES.remove(module.__name__) + + +def list_registry_pickle_by_value(): + return _PICKLE_BY_VALUE_MODULES.copy() + + +def _is_registered_pickle_by_value(module): + module_name = module.__name__ + if module_name in _PICKLE_BY_VALUE_MODULES: + return True + while True: + parent_name = module_name.rsplit(".", 1)[0] + if parent_name == module_name: + break + if parent_name in _PICKLE_BY_VALUE_MODULES: + return True + module_name = parent_name + return False + + +def _whichmodule(obj, name): + """Find the module an object belongs to. + + This function differs from ``pickle.whichmodule`` in two ways: + - it does not mangle the cases where obj's module is __main__ and obj was + not found in any module. + - Errors arising during module introspection are ignored, as those errors + are considered unwanted side effects. + """ + module_name = getattr(obj, "__module__", None) + + if module_name is not None: + return module_name + # Protect the iteration by using a copy of sys.modules against dynamic + # modules that trigger imports of other modules upon calls to getattr or + # other threads importing at the same time. + for module_name, module in sys.modules.copy().items(): + # Some modules such as coverage can inject non-module objects inside + # sys.modules + if ( + module_name == "__main__" + or module is None + or not isinstance(module, types.ModuleType) + ): + continue + try: + if _getattribute(module, name)[0] is obj: + return module_name + except Exception: + pass + return None + + +def _should_pickle_by_reference(obj, name=None): + """Test whether an function or a class should be pickled by reference + + Pickling by reference means by that the object (typically a function or a + class) is an attribute of a module that is assumed to be importable in the + target Python environment. Loading will therefore rely on importing the + module and then calling `getattr` on it to access the function or class. + + Pickling by reference is the only option to pickle functions and classes + in the standard library. In cloudpickle the alternative option is to + pickle by value (for instance for interactively or locally defined + functions and classes or for attributes of modules that have been + explicitly registered to be pickled by value. + """ + if isinstance(obj, types.FunctionType) or issubclass(type(obj), type): + module_and_name = _lookup_module_and_qualname(obj, name=name) + if module_and_name is None: + return False + module, name = module_and_name + return not _is_registered_pickle_by_value(module) + + elif isinstance(obj, types.ModuleType): + # We assume that sys.modules is primarily used as a cache mechanism for + # the Python import machinery. Checking if a module has been added in + # is sys.modules therefore a cheap and simple heuristic to tell us + # whether we can assume that a given module could be imported by name + # in another Python process. + if _is_registered_pickle_by_value(obj): + return False + return obj.__name__ in sys.modules + else: + raise TypeError( + "cannot check importability of {} instances".format(type(obj).__name__) + ) + + +def _lookup_module_and_qualname(obj, name=None): + if name is None: + name = getattr(obj, "__qualname__", None) + if name is None: # pragma: no cover + # This used to be needed for Python 2.7 support but is probably not + # needed anymore. However we keep the __name__ introspection in case + # users of cloudpickle rely on this old behavior for unknown reasons. + name = getattr(obj, "__name__", None) + + module_name = _whichmodule(obj, name) + + if module_name is None: + # In this case, obj.__module__ is None AND obj was not found in any + # imported module. obj is thus treated as dynamic. + return None + + if module_name == "__main__": + return None + + # Note: if module_name is in sys.modules, the corresponding module is + # assumed importable at unpickling time. See #357 + module = sys.modules.get(module_name, None) + if module is None: + # The main reason why obj's module would not be imported is that this + # module has been dynamically created, using for example + # types.ModuleType. The other possibility is that module was removed + # from sys.modules after obj was created/imported. But this case is not + # supported, as the standard pickle does not support it either. + return None + + try: + obj2, parent = _getattribute(module, name) + except AttributeError: + # obj was not found inside the module it points to + return None + if obj2 is not obj: + return None + return module, name + + +def _extract_code_globals(co): + """Find all globals names read or written to by codeblock co.""" + out_names = _extract_code_globals_cache.get(co) + if out_names is None: + # We use a dict with None values instead of a set to get a + # deterministic order and avoid introducing non-deterministic pickle + # bytes as a results. + out_names = {name: None for name in _walk_global_ops(co)} + + # Declaring a function inside another one using the "def ..." syntax + # generates a constant code object corresponding to the one of the + # nested function's As the nested function may itself need global + # variables, we need to introspect its code, extract its globals, (look + # for code object in it's co_consts attribute..) and add the result to + # code_globals + if co.co_consts: + for const in co.co_consts: + if isinstance(const, types.CodeType): + out_names.update(_extract_code_globals(const)) + + _extract_code_globals_cache[co] = out_names + + return out_names + + +def _find_imported_submodules(code, top_level_dependencies): + """Find currently imported submodules used by a function. + + Submodules used by a function need to be detected and referenced for the + function to work correctly at depickling time. Because submodules can be + referenced as attribute of their parent package (``package.submodule``), we + need a special introspection technique that does not rely on GLOBAL-related + opcodes to find references of them in a code object. + + Example: + ``` + import concurrent.futures + import cloudpickle + def func(): + x = concurrent.futures.ThreadPoolExecutor + if __name__ == '__main__': + cloudpickle.dumps(func) + ``` + The globals extracted by cloudpickle in the function's state include the + concurrent package, but not its submodule (here, concurrent.futures), which + is the module used by func. Find_imported_submodules will detect the usage + of concurrent.futures. Saving this module alongside with func will ensure + that calling func once depickled does not fail due to concurrent.futures + not being imported + """ + + subimports = [] + # check if any known dependency is an imported package + for x in top_level_dependencies: + if ( + isinstance(x, types.ModuleType) + and hasattr(x, "__package__") + and x.__package__ + ): + # check if the package has any currently loaded sub-imports + prefix = x.__name__ + "." + # A concurrent thread could mutate sys.modules, + # make sure we iterate over a copy to avoid exceptions + for name in list(sys.modules): + # Older versions of pytest will add a "None" module to + # sys.modules. + if name is not None and name.startswith(prefix): + # check whether the function can address the sub-module + tokens = set(name[len(prefix) :].split(".")) + if not tokens - set(code.co_names): + subimports.append(sys.modules[name]) + return subimports + + +# relevant opcodes +STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"] +DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"] +LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"] +GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL) +HAVE_ARGUMENT = dis.HAVE_ARGUMENT +EXTENDED_ARG = dis.EXTENDED_ARG + + +_BUILTIN_TYPE_NAMES = {} +for k, v in types.__dict__.items(): + if type(v) is type: + _BUILTIN_TYPE_NAMES[v] = k + + +def _builtin_type(name): + if name == "ClassType": # pragma: no cover + # Backward compat to load pickle files generated with cloudpickle + # < 1.3 even if loading pickle files from older versions is not + # officially supported. + return type + return getattr(types, name) + + +def _walk_global_ops(code): + """Yield referenced name for global-referencing instructions in code.""" + for instr in dis.get_instructions(code): + op = instr.opcode + if op in GLOBAL_OPS: + yield instr.argval + + +def _extract_class_dict(cls): + """Retrieve a copy of the dict of a class without the inherited method.""" + clsdict = dict(cls.__dict__) # copy dict proxy to a dict + if len(cls.__bases__) == 1: + inherited_dict = cls.__bases__[0].__dict__ + else: + inherited_dict = {} + for base in reversed(cls.__bases__): + inherited_dict.update(base.__dict__) + to_remove = [] + for name, value in clsdict.items(): + try: + base_value = inherited_dict[name] + if value is base_value: + to_remove.append(name) + except KeyError: + pass + for name in to_remove: + clsdict.pop(name) + return clsdict + + +def is_tornado_coroutine(func): + """Return whether `func` is a Tornado coroutine function. + + Running coroutines are not supported. + """ + warnings.warn( + "is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be " + "removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function " + "directly instead.", + category=DeprecationWarning, + ) + if "tornado.gen" not in sys.modules: + return False + gen = sys.modules["tornado.gen"] + if not hasattr(gen, "is_coroutine_function"): + # Tornado version is too old + return False + return gen.is_coroutine_function(func) + + +def subimport(name): + # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is + # the name of a submodule, __import__ will return the top-level root module + # of this submodule. For instance, __import__('os.path') returns the `os` + # module. + __import__(name) + return sys.modules[name] + + +def dynamic_subimport(name, vars): + mod = types.ModuleType(name) + mod.__dict__.update(vars) + mod.__dict__["__builtins__"] = builtins.__dict__ + return mod + + +def _get_cell_contents(cell): + try: + return cell.cell_contents + except ValueError: + # Handle empty cells explicitly with a sentinel value. + return _empty_cell_value + + +def instance(cls): + """Create a new instance of a class. + + Parameters + ---------- + cls : type + The class to create an instance of. + + Returns + ------- + instance : cls + A new instance of ``cls``. + """ + return cls() + + +@instance +class _empty_cell_value: + """Sentinel for empty closures.""" + + @classmethod + def __reduce__(cls): + return cls.__name__ + + +def _make_function(code, globals, name, argdefs, closure): + # Setting __builtins__ in globals is needed for nogil CPython. + globals["__builtins__"] = __builtins__ + return types.FunctionType(code, globals, name, argdefs, closure) + + +def _make_empty_cell(): + if False: + # trick the compiler into creating an empty cell in our lambda + cell = None + raise AssertionError("this route should not be executed") + + return (lambda: cell).__closure__[0] + + +def _make_cell(value=_empty_cell_value): + cell = _make_empty_cell() + if value is not _empty_cell_value: + cell.cell_contents = value + return cell + + +def _make_skeleton_class( + type_constructor, name, bases, type_kwargs, class_tracker_id, extra +): + """Build dynamic class with an empty __dict__ to be filled once memoized + + If class_tracker_id is not None, try to lookup an existing class definition + matching that id. If none is found, track a newly reconstructed class + definition under that id so that other instances stemming from the same + class id will also reuse this class definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + skeleton_class = types.new_class( + name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs) + ) + return _lookup_class_or_track(class_tracker_id, skeleton_class) + + +def _make_skeleton_enum( + bases, name, qualname, members, module, class_tracker_id, extra +): + """Build dynamic enum with an empty __dict__ to be filled once memoized + + The creation of the enum class is inspired by the code of + EnumMeta._create_. + + If class_tracker_id is not None, try to lookup an existing enum definition + matching that id. If none is found, track a newly reconstructed enum + definition under that id so that other instances stemming from the same + class id will also reuse this enum definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + # enums always inherit from their base Enum class at the last position in + # the list of base classes: + enum_base = bases[-1] + metacls = enum_base.__class__ + classdict = metacls.__prepare__(name, bases) + + for member_name, member_value in members.items(): + classdict[member_name] = member_value + enum_class = metacls.__new__(metacls, name, bases, classdict) + enum_class.__module__ = module + enum_class.__qualname__ = qualname + + return _lookup_class_or_track(class_tracker_id, enum_class) + + +def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id): + tv = typing.TypeVar( + name, + *constraints, + bound=bound, + covariant=covariant, + contravariant=contravariant, + ) + return _lookup_class_or_track(class_tracker_id, tv) + + +def _decompose_typevar(obj): + return ( + obj.__name__, + obj.__bound__, + obj.__constraints__, + obj.__covariant__, + obj.__contravariant__, + _get_or_create_tracker_id(obj), + ) + + +def _typevar_reduce(obj): + # TypeVar instances require the module information hence why we + # are not using the _should_pickle_by_reference directly + module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__) + + if module_and_name is None: + return (_make_typevar, _decompose_typevar(obj)) + elif _is_registered_pickle_by_value(module_and_name[0]): + return (_make_typevar, _decompose_typevar(obj)) + + return (getattr, module_and_name) + + +def _get_bases(typ): + if "__orig_bases__" in getattr(typ, "__dict__", {}): + # For generic types (see PEP 560) + # Note that simply checking `hasattr(typ, '__orig_bases__')` is not + # correct. Subclasses of a fully-parameterized generic class does not + # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')` + # will return True because it's defined in the base class. + bases_attr = "__orig_bases__" + else: + # For regular class objects + bases_attr = "__bases__" + return getattr(typ, bases_attr) + + +def _make_dict_keys(obj, is_ordered=False): + if is_ordered: + return OrderedDict.fromkeys(obj).keys() + else: + return dict.fromkeys(obj).keys() + + +def _make_dict_values(obj, is_ordered=False): + if is_ordered: + return OrderedDict((i, _) for i, _ in enumerate(obj)).values() + else: + return {i: _ for i, _ in enumerate(obj)}.values() + + +def _make_dict_items(obj, is_ordered=False): + if is_ordered: + return OrderedDict(obj).items() + else: + return obj.items() + + +# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS +# ------------------------------------------------- + + +def _class_getnewargs(obj): + type_kwargs = {} + if "__module__" in obj.__dict__: + type_kwargs["__module__"] = obj.__module__ + + __dict__ = obj.__dict__.get("__dict__", None) + if isinstance(__dict__, property): + type_kwargs["__dict__"] = __dict__ + + return ( + type(obj), + obj.__name__, + _get_bases(obj), + type_kwargs, + _get_or_create_tracker_id(obj), + None, + ) + + +def _enum_getnewargs(obj): + members = {e.name: e.value for e in obj} + return ( + obj.__bases__, + obj.__name__, + obj.__qualname__, + members, + obj.__module__, + _get_or_create_tracker_id(obj), + None, + ) + + +# COLLECTION OF OBJECTS RECONSTRUCTORS +# ------------------------------------ +def _file_reconstructor(retval): + return retval + + +# COLLECTION OF OBJECTS STATE GETTERS +# ----------------------------------- + + +def _function_getstate(func): + # - Put func's dynamic attributes (stored in func.__dict__) in state. These + # attributes will be restored at unpickling time using + # f.__dict__.update(state) + # - Put func's members into slotstate. Such attributes will be restored at + # unpickling time by iterating over slotstate and calling setattr(func, + # slotname, slotvalue) + slotstate = { + "__name__": func.__name__, + "__qualname__": func.__qualname__, + "__annotations__": func.__annotations__, + "__kwdefaults__": func.__kwdefaults__, + "__defaults__": func.__defaults__, + "__module__": func.__module__, + "__doc__": func.__doc__, + "__closure__": func.__closure__, + } + + f_globals_ref = _extract_code_globals(func.__code__) + f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__} + + if func.__closure__ is not None: + closure_values = list(map(_get_cell_contents, func.__closure__)) + else: + closure_values = () + + # Extract currently-imported submodules used by func. Storing these modules + # in a smoke _cloudpickle_subimports attribute of the object's state will + # trigger the side effect of importing these modules at unpickling time + # (which is necessary for func to work correctly once depickled) + slotstate["_cloudpickle_submodules"] = _find_imported_submodules( + func.__code__, itertools.chain(f_globals.values(), closure_values) + ) + slotstate["__globals__"] = f_globals + + state = func.__dict__ + return state, slotstate + + +def _class_getstate(obj): + clsdict = _extract_class_dict(obj) + clsdict.pop("__weakref__", None) + + if issubclass(type(obj), abc.ABCMeta): + # If obj is an instance of an ABCMeta subclass, don't pickle the + # cache/negative caches populated during isinstance/issubclass + # checks, but pickle the list of registered subclasses of obj. + clsdict.pop("_abc_cache", None) + clsdict.pop("_abc_negative_cache", None) + clsdict.pop("_abc_negative_cache_version", None) + registry = clsdict.pop("_abc_registry", None) + if registry is None: + # The abc caches and registered subclasses of a + # class are bundled into the single _abc_impl attribute + clsdict.pop("_abc_impl", None) + (registry, _, _, _) = abc._get_dump(obj) + + clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry] + else: + # In the above if clause, registry is a set of weakrefs -- in + # this case, registry is a WeakSet + clsdict["_abc_impl"] = [type_ for type_ in registry] + + if "__slots__" in clsdict: + # pickle string length optimization: member descriptors of obj are + # created automatically from obj's __slots__ attribute, no need to + # save them in obj's state + if isinstance(obj.__slots__, str): + clsdict.pop(obj.__slots__) + else: + for k in obj.__slots__: + clsdict.pop(k, None) + + clsdict.pop("__dict__", None) # unpicklable property object + + return (clsdict, {}) + + +def _enum_getstate(obj): + clsdict, slotstate = _class_getstate(obj) + + members = {e.name: e.value for e in obj} + # Cleanup the clsdict that will be passed to _make_skeleton_enum: + # Those attributes are already handled by the metaclass. + for attrname in [ + "_generate_next_value_", + "_member_names_", + "_member_map_", + "_member_type_", + "_value2member_map_", + ]: + clsdict.pop(attrname, None) + for member in members: + clsdict.pop(member) + # Special handling of Enum subclasses + return clsdict, slotstate + + +# COLLECTIONS OF OBJECTS REDUCERS +# ------------------------------- +# A reducer is a function taking a single argument (obj), and that returns a +# tuple with all the necessary data to re-construct obj. Apart from a few +# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to +# correctly pickle an object. +# While many built-in objects (Exceptions objects, instances of the "object" +# class, etc), are shipped with their own built-in reducer (invoked using +# obj.__reduce__), some do not. The following methods were created to "fill +# these holes". + + +def _code_reduce(obj): + """code object reducer.""" + # If you are not sure about the order of arguments, take a look at help + # of the specific type from types, for example: + # >>> from types import CodeType + # >>> help(CodeType) + if hasattr(obj, "co_exceptiontable"): + # Python 3.11 and later: there are some new attributes + # related to the enhanced exceptions. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_names, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_qualname, + obj.co_firstlineno, + obj.co_linetable, + obj.co_exceptiontable, + obj.co_freevars, + obj.co_cellvars, + ) + elif hasattr(obj, "co_linetable"): + # Python 3.10 and later: obj.co_lnotab is deprecated and constructor + # expects obj.co_linetable instead. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_names, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_firstlineno, + obj.co_linetable, + obj.co_freevars, + obj.co_cellvars, + ) + elif hasattr(obj, "co_nmeta"): # pragma: no cover + # "nogil" Python: modified attributes from 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_framesize, + obj.co_ndefaultargs, + obj.co_nmeta, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_firstlineno, + obj.co_lnotab, + obj.co_exc_handlers, + obj.co_jump_table, + obj.co_freevars, + obj.co_cellvars, + obj.co_free2reg, + obj.co_cell2reg, + ) + else: + # Backward compat for 3.8 and 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_names, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_firstlineno, + obj.co_lnotab, + obj.co_freevars, + obj.co_cellvars, + ) + return types.CodeType, args + + +def _cell_reduce(obj): + """Cell (containing values of a function's free variables) reducer.""" + try: + obj.cell_contents + except ValueError: # cell is empty + return _make_empty_cell, () + else: + return _make_cell, (obj.cell_contents,) + + +def _classmethod_reduce(obj): + orig_func = obj.__func__ + return type(obj), (orig_func,) + + +def _file_reduce(obj): + """Save a file.""" + import io + + if not hasattr(obj, "name") or not hasattr(obj, "mode"): + raise pickle.PicklingError( + "Cannot pickle files that do not map to an actual file" + ) + if obj is sys.stdout: + return getattr, (sys, "stdout") + if obj is sys.stderr: + return getattr, (sys, "stderr") + if obj is sys.stdin: + raise pickle.PicklingError("Cannot pickle standard input") + if obj.closed: + raise pickle.PicklingError("Cannot pickle closed files") + if hasattr(obj, "isatty") and obj.isatty(): + raise pickle.PicklingError("Cannot pickle files that map to tty objects") + if "r" not in obj.mode and "+" not in obj.mode: + raise pickle.PicklingError( + "Cannot pickle files that are not opened for reading: %s" % obj.mode + ) + + name = obj.name + + retval = io.StringIO() + + try: + # Read the whole file + curloc = obj.tell() + obj.seek(0) + contents = obj.read() + obj.seek(curloc) + except OSError as e: + raise pickle.PicklingError( + "Cannot pickle file %s as it cannot be read" % name + ) from e + retval.write(contents) + retval.seek(curloc) + + retval.name = name + return _file_reconstructor, (retval,) + + +def _getset_descriptor_reduce(obj): + return getattr, (obj.__objclass__, obj.__name__) + + +def _mappingproxy_reduce(obj): + return types.MappingProxyType, (dict(obj),) + + +def _memoryview_reduce(obj): + return bytes, (obj.tobytes(),) + + +def _module_reduce(obj): + if _should_pickle_by_reference(obj): + return subimport, (obj.__name__,) + else: + # Some external libraries can populate the "__builtins__" entry of a + # module's `__dict__` with unpicklable objects (see #316). For that + # reason, we do not attempt to pickle the "__builtins__" entry, and + # restore a default value for it at unpickling time. + state = obj.__dict__.copy() + state.pop("__builtins__", None) + return dynamic_subimport, (obj.__name__, state) + + +def _method_reduce(obj): + return (types.MethodType, (obj.__func__, obj.__self__)) + + +def _logger_reduce(obj): + return logging.getLogger, (obj.name,) + + +def _root_logger_reduce(obj): + return logging.getLogger, () + + +def _property_reduce(obj): + return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__) + + +def _weakset_reduce(obj): + return weakref.WeakSet, (list(obj),) + + +def _dynamic_class_reduce(obj): + """Save a class that can't be referenced as a module attribute. + + This method is used to serialize classes that are defined inside + functions, or that otherwise can't be serialized as attribute lookups + from importable modules. + """ + if Enum is not None and issubclass(obj, Enum): + return ( + _make_skeleton_enum, + _enum_getnewargs(obj), + _enum_getstate(obj), + None, + None, + _class_setstate, + ) + else: + return ( + _make_skeleton_class, + _class_getnewargs(obj), + _class_getstate(obj), + None, + None, + _class_setstate, + ) + + +def _class_reduce(obj): + """Select the reducer depending on the dynamic nature of the class obj.""" + if obj is type(None): # noqa + return type, (None,) + elif obj is type(Ellipsis): + return type, (Ellipsis,) + elif obj is type(NotImplemented): + return type, (NotImplemented,) + elif obj in _BUILTIN_TYPE_NAMES: + return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],) + elif not _should_pickle_by_reference(obj): + return _dynamic_class_reduce(obj) + return NotImplemented + + +def _dict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj),) + + +def _dict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj),) + + +def _dict_items_reduce(obj): + return _make_dict_items, (dict(obj),) + + +def _odict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj), True) + + +def _odict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj), True) + + +def _odict_items_reduce(obj): + return _make_dict_items, (dict(obj), True) + + +def _dataclass_field_base_reduce(obj): + return _get_dataclass_field_type_sentinel, (obj.name,) + + +# COLLECTIONS OF OBJECTS STATE SETTERS +# ------------------------------------ +# state setters are called at unpickling time, once the object is created and +# it has to be updated to how it was at unpickling time. + + +def _function_setstate(obj, state): + """Update the state of a dynamic function. + + As __closure__ and __globals__ are readonly attributes of a function, we + cannot rely on the native setstate routine of pickle.load_build, that calls + setattr on items of the slotstate. Instead, we have to modify them inplace. + """ + state, slotstate = state + obj.__dict__.update(state) + + obj_globals = slotstate.pop("__globals__") + obj_closure = slotstate.pop("__closure__") + # _cloudpickle_subimports is a set of submodules that must be loaded for + # the pickled function to work correctly at unpickling time. Now that these + # submodules are depickled (hence imported), they can be removed from the + # object's state (the object state only served as a reference holder to + # these submodules) + slotstate.pop("_cloudpickle_submodules") + + obj.__globals__.update(obj_globals) + obj.__globals__["__builtins__"] = __builtins__ + + if obj_closure is not None: + for i, cell in enumerate(obj_closure): + try: + value = cell.cell_contents + except ValueError: # cell is empty + continue + obj.__closure__[i].cell_contents = value + + for k, v in slotstate.items(): + setattr(obj, k, v) + + +def _class_setstate(obj, state): + state, slotstate = state + registry = None + for attrname, attr in state.items(): + if attrname == "_abc_impl": + registry = attr + else: + setattr(obj, attrname, attr) + if registry is not None: + for subclass in registry: + obj.register(subclass) + + return obj + + +# COLLECTION OF DATACLASS UTILITIES +# --------------------------------- +# There are some internal sentinel values whose identity must be preserved when +# unpickling dataclass fields. Each sentinel value has a unique name that we can +# use to retrieve its identity at unpickling time. + + +_DATACLASSE_FIELD_TYPE_SENTINELS = { + dataclasses._FIELD.name: dataclasses._FIELD, + dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR, + dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR, +} + + +def _get_dataclass_field_type_sentinel(name): + return _DATACLASSE_FIELD_TYPE_SENTINELS[name] + + +class Pickler(pickle.Pickler): + # set of reducers defined and used by cloudpickle (private) + _dispatch_table = {} + _dispatch_table[classmethod] = _classmethod_reduce + _dispatch_table[io.TextIOWrapper] = _file_reduce + _dispatch_table[logging.Logger] = _logger_reduce + _dispatch_table[logging.RootLogger] = _root_logger_reduce + _dispatch_table[memoryview] = _memoryview_reduce + _dispatch_table[property] = _property_reduce + _dispatch_table[staticmethod] = _classmethod_reduce + _dispatch_table[CellType] = _cell_reduce + _dispatch_table[types.CodeType] = _code_reduce + _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce + _dispatch_table[types.ModuleType] = _module_reduce + _dispatch_table[types.MethodType] = _method_reduce + _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce + _dispatch_table[weakref.WeakSet] = _weakset_reduce + _dispatch_table[typing.TypeVar] = _typevar_reduce + _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce + _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce + _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce + _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce + _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce + _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce + _dispatch_table[abc.abstractmethod] = _classmethod_reduce + _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce + _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce + _dispatch_table[abc.abstractproperty] = _property_reduce + _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce + + dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table) + + # function reducers are defined as instance methods of cloudpickle.Pickler + # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref) + def _dynamic_function_reduce(self, func): + """Reduce a function that is not pickleable via attribute lookup.""" + newargs = self._function_getnewargs(func) + state = _function_getstate(func) + return (_make_function, newargs, state, None, None, _function_setstate) + + def _function_reduce(self, obj): + """Reducer for function objects. + + If obj is a top-level attribute of a file-backed module, this reducer + returns NotImplemented, making the cloudpickle.Pickler fall back to + traditional pickle.Pickler routines to save obj. Otherwise, it reduces + obj using a custom cloudpickle reducer designed specifically to handle + dynamic functions. + """ + if _should_pickle_by_reference(obj): + return NotImplemented + else: + return self._dynamic_function_reduce(obj) + + def _function_getnewargs(self, func): + code = func.__code__ + + # base_globals represents the future global namespace of func at + # unpickling time. Looking it up and storing it in + # cloudpickle.Pickler.globals_ref allow functions sharing the same + # globals at pickling time to also share them once unpickled, at one + # condition: since globals_ref is an attribute of a cloudpickle.Pickler + # instance, and that a new cloudpickle.Pickler is created each time + # cloudpickle.dump or cloudpickle.dumps is called, functions also need + # to be saved within the same invocation of + # cloudpickle.dump/cloudpickle.dumps (for example: + # cloudpickle.dumps([f1, f2])). There is no such limitation when using + # cloudpickle.Pickler.dump, as long as the multiple invocations are + # bound to the same cloudpickle.Pickler instance. + base_globals = self.globals_ref.setdefault(id(func.__globals__), {}) + + if base_globals == {}: + # Add module attributes used to resolve relative imports + # instructions inside func. + for k in ["__package__", "__name__", "__path__", "__file__"]: + if k in func.__globals__: + base_globals[k] = func.__globals__[k] + + # Do not bind the free variables before the function is created to + # avoid infinite recursion. + if func.__closure__ is None: + closure = None + else: + closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars))) + + return code, base_globals, None, None, closure + + def dump(self, obj): + try: + return super().dump(obj) + except RuntimeError as e: + if len(e.args) > 0 and "recursion" in e.args[0]: + msg = "Could not pickle object as excessively deep recursion required." + raise pickle.PicklingError(msg) from e + else: + raise + + def __init__(self, file, protocol=None, buffer_callback=None): + if protocol is None: + protocol = DEFAULT_PROTOCOL + super().__init__(file, protocol=protocol, buffer_callback=buffer_callback) + # map functions __globals__ attribute ids, to ensure that functions + # sharing the same global namespace at pickling time also share + # their global namespace at unpickling time. + self.globals_ref = {} + self.proto = int(protocol) + + if not PYPY: + # pickle.Pickler is the C implementation of the CPython pickler and + # therefore we rely on reduce_override method to customize the pickler + # behavior. + + # `cloudpickle.Pickler.dispatch` is only left for backward + # compatibility - note that when using protocol 5, + # `cloudpickle.Pickler.dispatch` is not an extension of + # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler` + # subclasses the C-implemented `pickle.Pickler`, which does not expose + # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler` + # used `cloudpickle.Pickler.dispatch` as a class-level attribute + # storing all reducers implemented by cloudpickle, but the attribute + # name was not a great choice given because it would collide with a + # similarly named attribute in the pure-Python `pickle._Pickler` + # implementation in the standard library. + dispatch = dispatch_table + + # Implementation of the reducer_override callback, in order to + # efficiently serialize dynamic functions and classes by subclassing + # the C-implemented `pickle.Pickler`. + # TODO: decorrelate reducer_override (which is tied to CPython's + # implementation - would it make sense to backport it to pypy? - and + # pickle's protocol 5 which is implementation agnostic. Currently, the + # availability of both notions coincide on CPython's pickle, but it may + # not be the case anymore when pypy implements protocol 5. + + def reducer_override(self, obj): + """Type-agnostic reducing callback for function and classes. + + For performance reasons, subclasses of the C `pickle.Pickler` class + cannot register custom reducers for functions and classes in the + dispatch_table attribute. Reducers for such types must instead + implemented via the special `reducer_override` method. + + Note that this method will be called for any object except a few + builtin-types (int, lists, dicts etc.), which differs from reducers + in the Pickler's dispatch_table, each of them being invoked for + objects of a specific type only. + + This property comes in handy for classes: although most classes are + instances of the ``type`` metaclass, some of them can be instances + of other custom metaclasses (such as enum.EnumMeta for example). In + particular, the metaclass will likely not be known in advance, and + thus cannot be special-cased using an entry in the dispatch_table. + reducer_override, among other things, allows us to register a + reducer that will be called for any class, independently of its + type. + + Notes: + + * reducer_override has the priority over dispatch_table-registered + reducers. + * reducer_override can be used to fix other limitations of + cloudpickle for other types that suffered from type-specific + reducers, such as Exceptions. See + https://github.com/cloudpipe/cloudpickle/issues/248 + """ + t = type(obj) + try: + is_anyclass = issubclass(t, type) + except TypeError: # t is not a class (old Boost; see SF #502085) + is_anyclass = False + + if is_anyclass: + return _class_reduce(obj) + elif isinstance(obj, types.FunctionType): + return self._function_reduce(obj) + else: + # fallback to save_global, including the Pickler's + # dispatch_table + return NotImplemented + + else: + # When reducer_override is not available, hack the pure-Python + # Pickler's types.FunctionType and type savers. Note: the type saver + # must override Pickler.save_global, because pickle.py contains a + # hard-coded call to save_global when pickling meta-classes. + dispatch = pickle.Pickler.dispatch.copy() + + def _save_reduce_pickle5( + self, + func, + args, + state=None, + listitems=None, + dictitems=None, + state_setter=None, + obj=None, + ): + save = self.save + write = self.write + self.save_reduce( + func, + args, + state=None, + listitems=listitems, + dictitems=dictitems, + obj=obj, + ) + # backport of the Python 3.8 state_setter pickle operations + save(state_setter) + save(obj) # simple BINGET opcode as obj is already memoized. + save(state) + write(pickle.TUPLE2) + # Trigger a state_setter(obj, state) function call. + write(pickle.REDUCE) + # The purpose of state_setter is to carry-out an + # inplace modification of obj. We do not care about what the + # method might return, so its output is eventually removed from + # the stack. + write(pickle.POP) + + def save_global(self, obj, name=None, pack=struct.pack): + """Main dispatch method. + + The name of this method is somewhat misleading: all types get + dispatched here. + """ + if obj is type(None): # noqa + return self.save_reduce(type, (None,), obj=obj) + elif obj is type(Ellipsis): + return self.save_reduce(type, (Ellipsis,), obj=obj) + elif obj is type(NotImplemented): + return self.save_reduce(type, (NotImplemented,), obj=obj) + elif obj in _BUILTIN_TYPE_NAMES: + return self.save_reduce( + _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj + ) + + if name is not None: + super().save_global(obj, name=name) + elif not _should_pickle_by_reference(obj, name=name): + self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj) + else: + super().save_global(obj, name=name) + + dispatch[type] = save_global + + def save_function(self, obj, name=None): + """Registered with the dispatch to handle all function types. + + Determines what kind of function obj is (e.g. lambda, defined at + interactive prompt, etc) and handles the pickling appropriately. + """ + if _should_pickle_by_reference(obj, name=name): + return super().save_global(obj, name=name) + elif PYPY and isinstance(obj.__code__, builtin_code_type): + return self.save_pypy_builtin_func(obj) + else: + return self._save_reduce_pickle5( + *self._dynamic_function_reduce(obj), obj=obj + ) + + def save_pypy_builtin_func(self, obj): + """Save pypy equivalent of builtin functions. + + PyPy does not have the concept of builtin-functions. Instead, + builtin-functions are simple function instances, but with a + builtin-code attribute. + Most of the time, builtin functions should be pickled by attribute. + But PyPy has flaky support for __qualname__, so some builtin + functions such as float.__new__ will be classified as dynamic. For + this reason only, we created this special routine. Because + builtin-functions are not expected to have closure or globals, + there is no additional hack (compared the one already implemented + in pickle) to protect ourselves from reference cycles. A simple + (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note + also that PyPy improved their support for __qualname__ in v3.6, so + this routing should be removed when cloudpickle supports only PyPy + 3.6 and later. + """ + rv = ( + types.FunctionType, + (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__), + obj.__dict__, + ) + self.save_reduce(*rv, obj=obj) + + dispatch[types.FunctionType] = save_function + + +# Shorthands similar to pickle.dump/pickle.dumps + + +def dump(obj, file, protocol=None, buffer_callback=None): + """Serialize obj as bytes streamed into file + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj) + + +def dumps(obj, protocol=None, buffer_callback=None): + """Serialize obj as a string of bytes allocated in memory + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + with io.BytesIO() as file: + cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback) + cp.dump(obj) + return file.getvalue() + + +# Include pickles unloading functions in this namespace for convenience. +load, loads = pickle.load, pickle.loads + +# Backward compat alias. +CloudPickler = Pickler diff --git a/testbed/joblib__joblib/joblib/externals/cloudpickle/cloudpickle_fast.py b/testbed/joblib__joblib/joblib/externals/cloudpickle/cloudpickle_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..52d6732e44ebcc0053b24969943f7c3b742268bb --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/cloudpickle/cloudpickle_fast.py @@ -0,0 +1,13 @@ +"""Compatibility module. + +It can be necessary to load files generated by previous versions of cloudpickle +that rely on symbols being defined under the `cloudpickle.cloudpickle_fast` +namespace. + +See: tests/test_backward_compat.py +""" +from . import cloudpickle + + +def __getattr__(name): + return getattr(cloudpickle, name) diff --git a/testbed/joblib__joblib/joblib/externals/loky/__init__.py b/testbed/joblib__joblib/joblib/externals/loky/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5886d2a62092bdc9f444d7a22058d065de567818 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/__init__.py @@ -0,0 +1,44 @@ +r"""The :mod:`loky` module manages a pool of worker that can be re-used across time. +It provides a robust and dynamic implementation os the +:class:`ProcessPoolExecutor` and a function :func:`get_reusable_executor` which +hide the pool management under the hood. +""" +from concurrent.futures import ( + ALL_COMPLETED, + FIRST_COMPLETED, + FIRST_EXCEPTION, + CancelledError, + Executor, + TimeoutError, + as_completed, + wait, +) + +from ._base import Future +from .backend.context import cpu_count +from .backend.reduction import set_loky_pickler +from .reusable_executor import get_reusable_executor +from .cloudpickle_wrapper import wrap_non_picklable_objects +from .process_executor import BrokenProcessPool, ProcessPoolExecutor + + +__all__ = [ + "get_reusable_executor", + "cpu_count", + "wait", + "as_completed", + "Future", + "Executor", + "ProcessPoolExecutor", + "BrokenProcessPool", + "CancelledError", + "TimeoutError", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wrap_non_picklable_objects", + "set_loky_pickler", +] + + +__version__ = "3.4.1" diff --git a/testbed/joblib__joblib/joblib/externals/loky/_base.py b/testbed/joblib__joblib/joblib/externals/loky/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..da0abc1e7fa18363e6342a3b67410f1429e6fa10 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/_base.py @@ -0,0 +1,28 @@ +############################################################################### +# Modification of concurrent.futures.Future +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from concurrent/futures/_base.py (17/02/2017) +# * Do not use yield from +# * Use old super syntax +# +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +from concurrent.futures import Future as _BaseFuture +from concurrent.futures._base import LOGGER + + +# To make loky._base.Future instances awaitable by concurrent.futures.wait, +# derive our custom Future class from _BaseFuture. _invoke_callback is the only +# modification made to this class in loky. +# TODO investigate why using `concurrent.futures.Future` directly does not +# always work in our test suite. +class Future(_BaseFuture): + def _invoke_callbacks(self): + for callback in self._done_callbacks: + try: + callback(self) + except BaseException: + LOGGER.exception(f"exception calling callback for {self!r}") diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/__init__.py b/testbed/joblib__joblib/joblib/externals/loky/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d339aa644599cf5728394200abdfa19a1256aa02 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/__init__.py @@ -0,0 +1,14 @@ +import os +from multiprocessing import synchronize + +from .context import get_context + + +def _make_name(): + return f"/loky-{os.getpid()}-{next(synchronize.SemLock._rand)}" + + +# monkey patch the name creation for multiprocessing +synchronize.SemLock._make_name = staticmethod(_make_name) + +__all__ = ["get_context"] diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/_posix_reduction.py b/testbed/joblib__joblib/joblib/externals/loky/backend/_posix_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..4b800ec07ff26af38174097a194e24413bf6fc2d --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/_posix_reduction.py @@ -0,0 +1,67 @@ +############################################################################### +# Extra reducers for Unix based system and connections objects +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from multiprocessing/reduction.py (17/02/2017) +# * Add adapted reduction for LokyProcesses and socket/Connection +# +import os +import socket +import _socket +from multiprocessing.connection import Connection +from multiprocessing.context import get_spawning_popen + +from .reduction import register + +HAVE_SEND_HANDLE = ( + hasattr(socket, "CMSG_LEN") + and hasattr(socket, "SCM_RIGHTS") + and hasattr(socket.socket, "sendmsg") +) + + +def _mk_inheritable(fd): + os.set_inheritable(fd, True) + return fd + + +def DupFd(fd): + """Return a wrapper for an fd.""" + popen_obj = get_spawning_popen() + if popen_obj is not None: + return popen_obj.DupFd(popen_obj.duplicate_for_child(fd)) + elif HAVE_SEND_HANDLE: + from multiprocessing import resource_sharer + + return resource_sharer.DupFd(fd) + else: + raise TypeError( + "Cannot pickle connection object. This object can only be " + "passed when spawning a new process" + ) + + +def _reduce_socket(s): + df = DupFd(s.fileno()) + return _rebuild_socket, (df, s.family, s.type, s.proto) + + +def _rebuild_socket(df, family, type, proto): + fd = df.detach() + return socket.fromfd(fd, family, type, proto) + + +def rebuild_connection(df, readable, writable): + fd = df.detach() + return Connection(fd, readable, writable) + + +def reduce_connection(conn): + df = DupFd(conn.fileno()) + return rebuild_connection, (df, conn.readable, conn.writable) + + +register(socket.socket, _reduce_socket) +register(_socket.socket, _reduce_socket) +register(Connection, reduce_connection) diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/_win_reduction.py b/testbed/joblib__joblib/joblib/externals/loky/backend/_win_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..506d0ecba7c8951ddeaa05b48eb1bdadc8d5ff46 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/_win_reduction.py @@ -0,0 +1,18 @@ +############################################################################### +# Extra reducers for Windows system and connections objects +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from multiprocessing/reduction.py (17/02/2017) +# * Add adapted reduction for LokyProcesses and socket/PipeConnection +# +import socket +from multiprocessing import connection +from multiprocessing.reduction import _reduce_socket + +from .reduction import register + +# register reduction for win32 communication objects +register(socket.socket, _reduce_socket) +register(connection.Connection, connection.reduce_connection) +register(connection.PipeConnection, connection.reduce_pipe_connection) diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/context.py b/testbed/joblib__joblib/joblib/externals/loky/backend/context.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f590317e75752fdd0b4962b9f3ecbbbaf50b37 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/context.py @@ -0,0 +1,378 @@ +############################################################################### +# Basic context management with LokyContext +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from multiprocessing/context.py +# * Create a context ensuring loky uses only objects that are compatible +# * Add LokyContext to the list of context of multiprocessing so loky can be +# used with multiprocessing.set_start_method +# * Implement a CFS-aware amd physical-core aware cpu_count function. +# +import os +import sys +import math +import subprocess +import traceback +import warnings +import multiprocessing as mp +from multiprocessing import get_context as mp_get_context +from multiprocessing.context import BaseContext + + +from .process import LokyProcess, LokyInitMainProcess + +# Apparently, on older Python versions, loky cannot work 61 workers on Windows +# but instead 60: ¯\_(ツ)_/¯ +if sys.version_info >= (3, 8): + from concurrent.futures.process import _MAX_WINDOWS_WORKERS + + if sys.version_info < (3, 10): + _MAX_WINDOWS_WORKERS = _MAX_WINDOWS_WORKERS - 1 +else: + # compat for versions before 3.8 which do not define this. + _MAX_WINDOWS_WORKERS = 60 + +START_METHODS = ["loky", "loky_init_main", "spawn"] +if sys.platform != "win32": + START_METHODS += ["fork", "forkserver"] + +_DEFAULT_START_METHOD = None + +# Cache for the number of physical cores to avoid repeating subprocess calls. +# It should not change during the lifetime of the program. +physical_cores_cache = None + + +def get_context(method=None): + # Try to overload the default context + method = method or _DEFAULT_START_METHOD or "loky" + if method == "fork": + # If 'fork' is explicitly requested, warn user about potential issues. + warnings.warn( + "`fork` start method should not be used with " + "`loky` as it does not respect POSIX. Try using " + "`spawn` or `loky` instead.", + UserWarning, + ) + try: + return mp_get_context(method) + except ValueError: + raise ValueError( + f"Unknown context '{method}'. Value should be in " + f"{START_METHODS}." + ) + + +def set_start_method(method, force=False): + global _DEFAULT_START_METHOD + if _DEFAULT_START_METHOD is not None and not force: + raise RuntimeError("context has already been set") + assert method is None or method in START_METHODS, ( + f"'{method}' is not a valid start_method. It should be in " + f"{START_METHODS}" + ) + + _DEFAULT_START_METHOD = method + + +def get_start_method(): + return _DEFAULT_START_METHOD + + +def cpu_count(only_physical_cores=False): + """Return the number of CPUs the current process can use. + + The returned number of CPUs accounts for: + * the number of CPUs in the system, as given by + ``multiprocessing.cpu_count``; + * the CPU affinity settings of the current process + (available on some Unix systems); + * Cgroup CPU bandwidth limit (available on Linux only, typically + set by docker and similar container orchestration systems); + * the value of the LOKY_MAX_CPU_COUNT environment variable if defined. + and is given as the minimum of these constraints. + + If ``only_physical_cores`` is True, return the number of physical cores + instead of the number of logical cores (hyperthreading / SMT). Note that + this option is not enforced if the number of usable cores is controlled in + any other way such as: process affinity, Cgroup restricted CPU bandwidth + or the LOKY_MAX_CPU_COUNT environment variable. If the number of physical + cores is not found, return the number of logical cores. + + Note that on Windows, the returned number of CPUs cannot exceed 61 (or 60 for + Python < 3.10), see: + https://bugs.python.org/issue26903. + + It is also always larger or equal to 1. + """ + # Note: os.cpu_count() is allowed to return None in its docstring + os_cpu_count = os.cpu_count() or 1 + if sys.platform == "win32": + # On Windows, attempting to use more than 61 CPUs would result in a + # OS-level error. See https://bugs.python.org/issue26903. According to + # https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups + # it might be possible to go beyond with a lot of extra work but this + # does not look easy. + os_cpu_count = min(os_cpu_count, _MAX_WINDOWS_WORKERS) + + cpu_count_user = _cpu_count_user(os_cpu_count) + aggregate_cpu_count = max(min(os_cpu_count, cpu_count_user), 1) + + if not only_physical_cores: + return aggregate_cpu_count + + if cpu_count_user < os_cpu_count: + # Respect user setting + return max(cpu_count_user, 1) + + cpu_count_physical, exception = _count_physical_cores() + if cpu_count_physical != "not found": + return cpu_count_physical + + # Fallback to default behavior + if exception is not None: + # warns only the first time + warnings.warn( + "Could not find the number of physical cores for the " + f"following reason:\n{exception}\n" + "Returning the number of logical cores instead. You can " + "silence this warning by setting LOKY_MAX_CPU_COUNT to " + "the number of cores you want to use." + ) + traceback.print_tb(exception.__traceback__) + + return aggregate_cpu_count + + +def _cpu_count_cgroup(os_cpu_count): + # Cgroup CPU bandwidth limit available in Linux since 2.6 kernel + cpu_max_fname = "/sys/fs/cgroup/cpu.max" + cfs_quota_fname = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" + cfs_period_fname = "/sys/fs/cgroup/cpu/cpu.cfs_period_us" + if os.path.exists(cpu_max_fname): + # cgroup v2 + # https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html + with open(cpu_max_fname) as fh: + cpu_quota_us, cpu_period_us = fh.read().strip().split() + elif os.path.exists(cfs_quota_fname) and os.path.exists(cfs_period_fname): + # cgroup v1 + # https://www.kernel.org/doc/html/latest/scheduler/sched-bwc.html#management + with open(cfs_quota_fname) as fh: + cpu_quota_us = fh.read().strip() + with open(cfs_period_fname) as fh: + cpu_period_us = fh.read().strip() + else: + # No Cgroup CPU bandwidth limit (e.g. non-Linux platform) + cpu_quota_us = "max" + cpu_period_us = 100_000 # unused, for consistency with default values + + if cpu_quota_us == "max": + # No active Cgroup quota on a Cgroup-capable platform + return os_cpu_count + else: + cpu_quota_us = int(cpu_quota_us) + cpu_period_us = int(cpu_period_us) + if cpu_quota_us > 0 and cpu_period_us > 0: + return math.ceil(cpu_quota_us / cpu_period_us) + else: # pragma: no cover + # Setting a negative cpu_quota_us value is a valid way to disable + # cgroup CPU bandwith limits + return os_cpu_count + + +def _cpu_count_affinity(os_cpu_count): + # Number of available CPUs given affinity settings + if hasattr(os, "sched_getaffinity"): + try: + return len(os.sched_getaffinity(0)) + except NotImplementedError: + pass + + # On PyPy and possibly other platforms, os.sched_getaffinity does not exist + # or raises NotImplementedError, let's try with the psutil if installed. + try: + import psutil + + p = psutil.Process() + if hasattr(p, "cpu_affinity"): + return len(p.cpu_affinity()) + + except ImportError: # pragma: no cover + if ( + sys.platform == "linux" + and os.environ.get("LOKY_MAX_CPU_COUNT") is None + ): + # PyPy does not implement os.sched_getaffinity on Linux which + # can cause severe oversubscription problems. Better warn the + # user in this particularly pathological case which can wreck + # havoc, typically on CI workers. + warnings.warn( + "Failed to inspect CPU affinity constraints on this system. " + "Please install psutil or explictly set LOKY_MAX_CPU_COUNT." + ) + + # This can happen for platforms that do not implement any kind of CPU + # infinity such as macOS-based platforms. + return os_cpu_count + + +def _cpu_count_user(os_cpu_count): + """Number of user defined available CPUs""" + cpu_count_affinity = _cpu_count_affinity(os_cpu_count) + + cpu_count_cgroup = _cpu_count_cgroup(os_cpu_count) + + # User defined soft-limit passed as a loky specific environment variable. + cpu_count_loky = int(os.environ.get("LOKY_MAX_CPU_COUNT", os_cpu_count)) + + return min(cpu_count_affinity, cpu_count_cgroup, cpu_count_loky) + + +def _count_physical_cores(): + """Return a tuple (number of physical cores, exception) + + If the number of physical cores is found, exception is set to None. + If it has not been found, return ("not found", exception). + + The number of physical cores is cached to avoid repeating subprocess calls. + """ + exception = None + + # First check if the value is cached + global physical_cores_cache + if physical_cores_cache is not None: + return physical_cores_cache, exception + + # Not cached yet, find it + try: + if sys.platform == "linux": + cpu_info = subprocess.run( + "lscpu --parse=core".split(), capture_output=True, text=True + ) + cpu_info = cpu_info.stdout.splitlines() + cpu_info = {line for line in cpu_info if not line.startswith("#")} + cpu_count_physical = len(cpu_info) + elif sys.platform == "win32": + cpu_info = subprocess.run( + "wmic CPU Get NumberOfCores /Format:csv".split(), + capture_output=True, + text=True, + ) + cpu_info = cpu_info.stdout.splitlines() + cpu_info = [ + l.split(",")[1] + for l in cpu_info + if (l and l != "Node,NumberOfCores") + ] + cpu_count_physical = sum(map(int, cpu_info)) + elif sys.platform == "darwin": + cpu_info = subprocess.run( + "sysctl -n hw.physicalcpu".split(), + capture_output=True, + text=True, + ) + cpu_info = cpu_info.stdout + cpu_count_physical = int(cpu_info) + else: + raise NotImplementedError(f"unsupported platform: {sys.platform}") + + # if cpu_count_physical < 1, we did not find a valid value + if cpu_count_physical < 1: + raise ValueError(f"found {cpu_count_physical} physical cores < 1") + + except Exception as e: + exception = e + cpu_count_physical = "not found" + + # Put the result in cache + physical_cores_cache = cpu_count_physical + + return cpu_count_physical, exception + + +class LokyContext(BaseContext): + """Context relying on the LokyProcess.""" + + _name = "loky" + Process = LokyProcess + cpu_count = staticmethod(cpu_count) + + def Queue(self, maxsize=0, reducers=None): + """Returns a queue object""" + from .queues import Queue + + return Queue(maxsize, reducers=reducers, ctx=self.get_context()) + + def SimpleQueue(self, reducers=None): + """Returns a queue object""" + from .queues import SimpleQueue + + return SimpleQueue(reducers=reducers, ctx=self.get_context()) + + if sys.platform != "win32": + """For Unix platform, use our custom implementation of synchronize + ensuring that we use the loky.backend.resource_tracker to clean-up + the semaphores in case of a worker crash. + """ + + def Semaphore(self, value=1): + """Returns a semaphore object""" + from .synchronize import Semaphore + + return Semaphore(value=value) + + def BoundedSemaphore(self, value): + """Returns a bounded semaphore object""" + from .synchronize import BoundedSemaphore + + return BoundedSemaphore(value) + + def Lock(self): + """Returns a lock object""" + from .synchronize import Lock + + return Lock() + + def RLock(self): + """Returns a recurrent lock object""" + from .synchronize import RLock + + return RLock() + + def Condition(self, lock=None): + """Returns a condition object""" + from .synchronize import Condition + + return Condition(lock) + + def Event(self): + """Returns an event object""" + from .synchronize import Event + + return Event() + + +class LokyInitMainContext(LokyContext): + """Extra context with LokyProcess, which does load the main module + + This context is used for compatibility in the case ``cloudpickle`` is not + present on the running system. This permits to load functions defined in + the ``main`` module, using proper safeguards. The declaration of the + ``executor`` should be protected by ``if __name__ == "__main__":`` and the + functions and variable used from main should be out of this block. + + This mimics the default behavior of multiprocessing under Windows and the + behavior of the ``spawn`` start method on a posix system. + For more details, see the end of the following section of python doc + https://docs.python.org/3/library/multiprocessing.html#multiprocessing-programming + """ + + _name = "loky_init_main" + Process = LokyInitMainProcess + + +# Register loky context so it works with multiprocessing.get_context +ctx_loky = LokyContext() +mp.context._concrete_contexts["loky"] = ctx_loky +mp.context._concrete_contexts["loky_init_main"] = LokyInitMainContext() diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/fork_exec.py b/testbed/joblib__joblib/joblib/externals/loky/backend/fork_exec.py new file mode 100644 index 0000000000000000000000000000000000000000..2353c42f51a6e6c558ce70e35e1b7405e22d70ed --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/fork_exec.py @@ -0,0 +1,43 @@ +############################################################################### +# Launch a subprocess using forkexec and make sure only the needed fd are +# shared in the two process. +# +# author: Thomas Moreau and Olivier Grisel +# +import os +import sys + + +def close_fds(keep_fds): # pragma: no cover + """Close all the file descriptors except those in keep_fds.""" + + # Make sure to keep stdout and stderr open for logging purpose + keep_fds = {*keep_fds, 1, 2} + + # We try to retrieve all the open fds + try: + open_fds = {int(fd) for fd in os.listdir("/proc/self/fd")} + except FileNotFoundError: + import resource + + max_nfds = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + open_fds = {*range(max_nfds)} + + for i in open_fds - keep_fds: + try: + os.close(i) + except OSError: + pass + + +def fork_exec(cmd, keep_fds, env=None): + # copy the environment variables to set in the child process + env = env or {} + child_env = {**os.environ, **env} + + pid = os.fork() + if pid == 0: # pragma: no cover + close_fds(keep_fds) + os.execve(sys.executable, cmd, child_env) + else: + return pid diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/popen_loky_posix.py b/testbed/joblib__joblib/joblib/externals/loky/backend/popen_loky_posix.py new file mode 100644 index 0000000000000000000000000000000000000000..74395be0757f0a07ef92a7b0efe1e1ea4ecdac77 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/popen_loky_posix.py @@ -0,0 +1,193 @@ +############################################################################### +# Popen for LokyProcess. +# +# author: Thomas Moreau and Olivier Grisel +# +import os +import sys +import signal +import pickle +from io import BytesIO +from multiprocessing import util, process +from multiprocessing.connection import wait +from multiprocessing.context import set_spawning_popen + +from . import reduction, resource_tracker, spawn + + +__all__ = ["Popen"] + + +# +# Wrapper for an fd used while launching a process +# + + +class _DupFd: + def __init__(self, fd): + self.fd = reduction._mk_inheritable(fd) + + def detach(self): + return self.fd + + +# +# Start child process using subprocess.Popen +# + + +class Popen: + method = "loky" + DupFd = _DupFd + + def __init__(self, process_obj): + sys.stdout.flush() + sys.stderr.flush() + self.returncode = None + self._fds = [] + self._launch(process_obj) + + def duplicate_for_child(self, fd): + self._fds.append(fd) + return reduction._mk_inheritable(fd) + + def poll(self, flag=os.WNOHANG): + if self.returncode is None: + while True: + try: + pid, sts = os.waitpid(self.pid, flag) + except OSError: + # Child process not yet created. See #1731717 + # e.errno == errno.ECHILD == 10 + return None + else: + break + if pid == self.pid: + if os.WIFSIGNALED(sts): + self.returncode = -os.WTERMSIG(sts) + else: + assert os.WIFEXITED(sts) + self.returncode = os.WEXITSTATUS(sts) + return self.returncode + + def wait(self, timeout=None): + if self.returncode is None: + if timeout is not None: + if not wait([self.sentinel], timeout): + return None + # This shouldn't block if wait() returned successfully. + return self.poll(os.WNOHANG if timeout == 0.0 else 0) + return self.returncode + + def terminate(self): + if self.returncode is None: + try: + os.kill(self.pid, signal.SIGTERM) + except ProcessLookupError: + pass + except OSError: + if self.wait(timeout=0.1) is None: + raise + + def _launch(self, process_obj): + + tracker_fd = resource_tracker._resource_tracker.getfd() + + fp = BytesIO() + set_spawning_popen(self) + try: + prep_data = spawn.get_preparation_data( + process_obj._name, + getattr(process_obj, "init_main_module", True), + ) + reduction.dump(prep_data, fp) + reduction.dump(process_obj, fp) + + finally: + set_spawning_popen(None) + + try: + parent_r, child_w = os.pipe() + child_r, parent_w = os.pipe() + # for fd in self._fds: + # _mk_inheritable(fd) + + cmd_python = [sys.executable] + cmd_python += ["-m", self.__module__] + cmd_python += ["--process-name", str(process_obj.name)] + cmd_python += ["--pipe", str(reduction._mk_inheritable(child_r))] + reduction._mk_inheritable(child_w) + reduction._mk_inheritable(tracker_fd) + self._fds += [child_r, child_w, tracker_fd] + if sys.version_info >= (3, 8) and os.name == "posix": + mp_tracker_fd = prep_data["mp_tracker_args"]["fd"] + self.duplicate_for_child(mp_tracker_fd) + + from .fork_exec import fork_exec + + pid = fork_exec(cmd_python, self._fds, env=process_obj.env) + util.debug( + f"launched python with pid {pid} and cmd:\n{cmd_python}" + ) + self.sentinel = parent_r + + method = "getbuffer" + if not hasattr(fp, method): + method = "getvalue" + with os.fdopen(parent_w, "wb") as f: + f.write(getattr(fp, method)()) + self.pid = pid + finally: + if parent_r is not None: + util.Finalize(self, os.close, (parent_r,)) + for fd in (child_r, child_w): + if fd is not None: + os.close(fd) + + @staticmethod + def thread_is_spawning(): + return True + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser("Command line parser") + parser.add_argument( + "--pipe", type=int, required=True, help="File handle for the pipe" + ) + parser.add_argument( + "--process-name", + type=str, + default=None, + help="Identifier for debugging purpose", + ) + + args = parser.parse_args() + + info = {} + exitcode = 1 + try: + with os.fdopen(args.pipe, "rb") as from_parent: + process.current_process()._inheriting = True + try: + prep_data = pickle.load(from_parent) + spawn.prepare(prep_data) + process_obj = pickle.load(from_parent) + finally: + del process.current_process()._inheriting + + exitcode = process_obj._bootstrap() + except Exception: + print("\n\n" + "-" * 80) + print(f"{args.process_name} failed with traceback: ") + print("-" * 80) + import traceback + + print(traceback.format_exc()) + print("\n" + "-" * 80) + finally: + if from_parent is not None: + from_parent.close() + + sys.exit(exitcode) diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/popen_loky_win32.py b/testbed/joblib__joblib/joblib/externals/loky/backend/popen_loky_win32.py new file mode 100644 index 0000000000000000000000000000000000000000..4f85f65df5e22bc2342f44c4a59b5e2ece63a81f --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/popen_loky_win32.py @@ -0,0 +1,173 @@ +import os +import sys +import msvcrt +import _winapi +from pickle import load +from multiprocessing import process, util +from multiprocessing.context import set_spawning_popen +from multiprocessing.popen_spawn_win32 import Popen as _Popen + +from . import reduction, spawn + + +__all__ = ["Popen"] + +# +# +# + + +def _path_eq(p1, p2): + return p1 == p2 or os.path.normcase(p1) == os.path.normcase(p2) + + +WINENV = hasattr(sys, "_base_executable") and not _path_eq( + sys.executable, sys._base_executable +) + + +def _close_handles(*handles): + for handle in handles: + _winapi.CloseHandle(handle) + + +# +# We define a Popen class similar to the one from subprocess, but +# whose constructor takes a process object as its argument. +# + + +class Popen(_Popen): + """ + Start a subprocess to run the code of a process object. + + We differ from cpython implementation with the way we handle environment + variables, in order to be able to modify then in the child processes before + importing any library, in order to control the number of threads in C-level + threadpools. + + We also use the loky preparation data, in particular to handle main_module + inits and the loky resource tracker. + """ + + method = "loky" + + def __init__(self, process_obj): + prep_data = spawn.get_preparation_data( + process_obj._name, getattr(process_obj, "init_main_module", True) + ) + + # read end of pipe will be duplicated by the child process + # -- see spawn_main() in spawn.py. + # + # bpo-33929: Previously, the read end of pipe was "stolen" by the child + # process, but it leaked a handle if the child process had been + # terminated before it could steal the handle from the parent process. + rhandle, whandle = _winapi.CreatePipe(None, 0) + wfd = msvcrt.open_osfhandle(whandle, 0) + cmd = get_command_line(parent_pid=os.getpid(), pipe_handle=rhandle) + + python_exe = spawn.get_executable() + + # copy the environment variables to set in the child process + child_env = {**os.environ, **process_obj.env} + + # bpo-35797: When running in a venv, we bypass the redirect + # executor and launch our base Python. + if WINENV and _path_eq(python_exe, sys.executable): + cmd[0] = python_exe = sys._base_executable + child_env["__PYVENV_LAUNCHER__"] = sys.executable + + cmd = " ".join(f'"{x}"' for x in cmd) + + with open(wfd, "wb") as to_child: + # start process + try: + hp, ht, pid, _ = _winapi.CreateProcess( + python_exe, + cmd, + None, + None, + False, + 0, + child_env, + None, + None, + ) + _winapi.CloseHandle(ht) + except BaseException: + _winapi.CloseHandle(rhandle) + raise + + # set attributes of self + self.pid = pid + self.returncode = None + self._handle = hp + self.sentinel = int(hp) + self.finalizer = util.Finalize( + self, _close_handles, (self.sentinel, int(rhandle)) + ) + + # send information to child + set_spawning_popen(self) + try: + reduction.dump(prep_data, to_child) + reduction.dump(process_obj, to_child) + finally: + set_spawning_popen(None) + + +def get_command_line(pipe_handle, parent_pid, **kwds): + """Returns prefix of command line used for spawning a child process.""" + if getattr(sys, "frozen", False): + return [sys.executable, "--multiprocessing-fork", pipe_handle] + else: + prog = ( + "from joblib.externals.loky.backend.popen_loky_win32 import main; " + f"main(pipe_handle={pipe_handle}, parent_pid={parent_pid})" + ) + opts = util._args_from_interpreter_flags() + return [ + spawn.get_executable(), + *opts, + "-c", + prog, + "--multiprocessing-fork", + ] + + +def is_forking(argv): + """Return whether commandline indicates we are forking.""" + if len(argv) >= 2 and argv[1] == "--multiprocessing-fork": + return True + else: + return False + + +def main(pipe_handle, parent_pid=None): + """Run code specified by data received over pipe.""" + assert is_forking(sys.argv), "Not forking" + + if parent_pid is not None: + source_process = _winapi.OpenProcess( + _winapi.SYNCHRONIZE | _winapi.PROCESS_DUP_HANDLE, False, parent_pid + ) + else: + source_process = None + new_handle = reduction.duplicate( + pipe_handle, source_process=source_process + ) + fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY) + parent_sentinel = source_process + + with os.fdopen(fd, "rb", closefd=True) as from_parent: + process.current_process()._inheriting = True + try: + preparation_data = load(from_parent) + spawn.prepare(preparation_data, parent_sentinel) + self = load(from_parent) + finally: + del process.current_process()._inheriting + + exitcode = self._bootstrap(parent_sentinel) + sys.exit(exitcode) diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/process.py b/testbed/joblib__joblib/joblib/externals/loky/backend/process.py new file mode 100644 index 0000000000000000000000000000000000000000..356255094b7647be8de6998a8752dd7807b25e10 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/process.py @@ -0,0 +1,85 @@ +############################################################################### +# LokyProcess implementation +# +# authors: Thomas Moreau and Olivier Grisel +# +# based on multiprocessing/process.py (17/02/2017) +# +import sys +from multiprocessing.context import assert_spawning +from multiprocessing.process import BaseProcess + + +class LokyProcess(BaseProcess): + _start_method = "loky" + + def __init__( + self, + group=None, + target=None, + name=None, + args=(), + kwargs={}, + daemon=None, + init_main_module=False, + env=None, + ): + super().__init__( + group=group, + target=target, + name=name, + args=args, + kwargs=kwargs, + daemon=daemon, + ) + self.env = {} if env is None else env + self.authkey = self.authkey + self.init_main_module = init_main_module + + @staticmethod + def _Popen(process_obj): + if sys.platform == "win32": + from .popen_loky_win32 import Popen + else: + from .popen_loky_posix import Popen + return Popen(process_obj) + + +class LokyInitMainProcess(LokyProcess): + _start_method = "loky_init_main" + + def __init__( + self, + group=None, + target=None, + name=None, + args=(), + kwargs={}, + daemon=None, + ): + super().__init__( + group=group, + target=target, + name=name, + args=args, + kwargs=kwargs, + daemon=daemon, + init_main_module=True, + ) + + +# +# We subclass bytes to avoid accidental transmission of auth keys over network +# + + +class AuthenticationKey(bytes): + def __reduce__(self): + try: + assert_spawning(self) + except RuntimeError: + raise TypeError( + "Pickling an AuthenticationKey object is " + "disallowed for security reasons" + ) + return AuthenticationKey, (bytes(self),) diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/queues.py b/testbed/joblib__joblib/joblib/externals/loky/backend/queues.py new file mode 100644 index 0000000000000000000000000000000000000000..5afd99b420fbc480ed5eb743333a687110a90e49 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/queues.py @@ -0,0 +1,236 @@ +############################################################################### +# Queue and SimpleQueue implementation for loky +# +# authors: Thomas Moreau, Olivier Grisel +# +# based on multiprocessing/queues.py (16/02/2017) +# * Add some custom reducers for the Queues/SimpleQueue to tweak the +# pickling process. (overload Queue._feed/SimpleQueue.put) +# +import os +import sys +import errno +import weakref +import threading +from multiprocessing import util +from multiprocessing.queues import ( + Full, + Queue as mp_Queue, + SimpleQueue as mp_SimpleQueue, + _sentinel, +) +from multiprocessing.context import assert_spawning + +from .reduction import dumps + + +__all__ = ["Queue", "SimpleQueue", "Full"] + + +class Queue(mp_Queue): + def __init__(self, maxsize=0, reducers=None, ctx=None): + super().__init__(maxsize=maxsize, ctx=ctx) + self._reducers = reducers + + # Use custom queue set/get state to be able to reduce the custom reducers + def __getstate__(self): + assert_spawning(self) + return ( + self._ignore_epipe, + self._maxsize, + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + self._sem, + self._opid, + ) + + def __setstate__(self, state): + ( + self._ignore_epipe, + self._maxsize, + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + self._sem, + self._opid, + ) = state + if sys.version_info >= (3, 9): + self._reset() + else: + self._after_fork() + + # Overload _start_thread to correctly call our custom _feed + def _start_thread(self): + util.debug("Queue._start_thread()") + + # Start thread which transfers data from buffer to pipe + self._buffer.clear() + self._thread = threading.Thread( + target=Queue._feed, + args=( + self._buffer, + self._notempty, + self._send_bytes, + self._wlock, + self._writer.close, + self._reducers, + self._ignore_epipe, + self._on_queue_feeder_error, + self._sem, + ), + name="QueueFeederThread", + ) + self._thread.daemon = True + + util.debug("doing self._thread.start()") + self._thread.start() + util.debug("... done self._thread.start()") + + # On process exit we will wait for data to be flushed to pipe. + # + # However, if this process created the queue then all + # processes which use the queue will be descendants of this + # process. Therefore waiting for the queue to be flushed + # is pointless once all the child processes have been joined. + created_by_this_process = self._opid == os.getpid() + if not self._joincancelled and not created_by_this_process: + self._jointhread = util.Finalize( + self._thread, + Queue._finalize_join, + [weakref.ref(self._thread)], + exitpriority=-5, + ) + + # Send sentinel to the thread queue object when garbage collected + self._close = util.Finalize( + self, + Queue._finalize_close, + [self._buffer, self._notempty], + exitpriority=10, + ) + + # Overload the _feed methods to use our custom pickling strategy. + @staticmethod + def _feed( + buffer, + notempty, + send_bytes, + writelock, + close, + reducers, + ignore_epipe, + onerror, + queue_sem, + ): + util.debug("starting thread to feed data to pipe") + nacquire = notempty.acquire + nrelease = notempty.release + nwait = notempty.wait + bpopleft = buffer.popleft + sentinel = _sentinel + if sys.platform != "win32": + wacquire = writelock.acquire + wrelease = writelock.release + else: + wacquire = None + + while True: + try: + nacquire() + try: + if not buffer: + nwait() + finally: + nrelease() + try: + while True: + obj = bpopleft() + if obj is sentinel: + util.debug("feeder thread got sentinel -- exiting") + close() + return + + # serialize the data before acquiring the lock + obj_ = dumps(obj, reducers=reducers) + if wacquire is None: + send_bytes(obj_) + else: + wacquire() + try: + send_bytes(obj_) + finally: + wrelease() + # Remove references early to avoid leaking memory + del obj, obj_ + except IndexError: + pass + except BaseException as e: + if ignore_epipe and getattr(e, "errno", 0) == errno.EPIPE: + return + # Since this runs in a daemon thread the resources it uses + # may be become unusable while the process is cleaning up. + # We ignore errors which happen after the process has + # started to cleanup. + if util.is_exiting(): + util.info(f"error in queue thread: {e}") + return + else: + queue_sem.release() + onerror(e, obj) + + def _on_queue_feeder_error(self, e, obj): + """ + Private API hook called when feeding data in the background thread + raises an exception. For overriding by concurrent.futures. + """ + import traceback + + traceback.print_exc() + + +class SimpleQueue(mp_SimpleQueue): + def __init__(self, reducers=None, ctx=None): + super().__init__(ctx=ctx) + + # Add possiblity to use custom reducers + self._reducers = reducers + + def close(self): + self._reader.close() + self._writer.close() + + # Use custom queue set/get state to be able to reduce the custom reducers + def __getstate__(self): + assert_spawning(self) + return ( + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + ) + + def __setstate__(self, state): + ( + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + ) = state + + # Overload put to use our customizable reducer + def put(self, obj): + # serialize the data before acquiring the lock + obj = dumps(obj, reducers=self._reducers) + if self._wlock is None: + # writes to a message oriented win32 pipe are atomic + self._writer.send_bytes(obj) + else: + with self._wlock: + self._writer.send_bytes(obj) diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/reduction.py b/testbed/joblib__joblib/joblib/externals/loky/backend/reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..bed32ba9e18f7d0fccab7ead6095996d27f448e2 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/reduction.py @@ -0,0 +1,224 @@ +############################################################################### +# Customizable Pickler with some basic reducers +# +# author: Thomas Moreau +# +# adapted from multiprocessing/reduction.py (17/02/2017) +# * Replace the ForkingPickler with a similar _LokyPickler, +# * Add CustomizableLokyPickler to allow customizing pickling process +# on the fly. +# +import copyreg +import io +import functools +import types +import sys +import os + +from multiprocessing import util +from pickle import loads, HIGHEST_PROTOCOL + +############################################################################### +# Enable custom pickling in Loky. + +_dispatch_table = {} + + +def register(type_, reduce_function): + _dispatch_table[type_] = reduce_function + + +############################################################################### +# Registers extra pickling routines to improve picklization for loky + + +# make methods picklable +def _reduce_method(m): + if m.__self__ is None: + return getattr, (m.__class__, m.__func__.__name__) + else: + return getattr, (m.__self__, m.__func__.__name__) + + +class _C: + def f(self): + pass + + @classmethod + def h(cls): + pass + + +register(type(_C().f), _reduce_method) +register(type(_C.h), _reduce_method) + + +if not hasattr(sys, "pypy_version_info"): + # PyPy uses functions instead of method_descriptors and wrapper_descriptors + def _reduce_method_descriptor(m): + return getattr, (m.__objclass__, m.__name__) + + register(type(list.append), _reduce_method_descriptor) + register(type(int.__add__), _reduce_method_descriptor) + + +# Make partial func pickable +def _reduce_partial(p): + return _rebuild_partial, (p.func, p.args, p.keywords or {}) + + +def _rebuild_partial(func, args, keywords): + return functools.partial(func, *args, **keywords) + + +register(functools.partial, _reduce_partial) + +if sys.platform != "win32": + from ._posix_reduction import _mk_inheritable # noqa: F401 +else: + from . import _win_reduction # noqa: F401 + +# global variable to change the pickler behavior +try: + from joblib.externals import cloudpickle # noqa: F401 + + DEFAULT_ENV = "cloudpickle" +except ImportError: + # If cloudpickle is not present, fallback to pickle + DEFAULT_ENV = "pickle" + +ENV_LOKY_PICKLER = os.environ.get("LOKY_PICKLER", DEFAULT_ENV) +_LokyPickler = None +_loky_pickler_name = None + + +def set_loky_pickler(loky_pickler=None): + global _LokyPickler, _loky_pickler_name + + if loky_pickler is None: + loky_pickler = ENV_LOKY_PICKLER + + loky_pickler_cls = None + + # The default loky_pickler is cloudpickle + if loky_pickler in ["", None]: + loky_pickler = "cloudpickle" + + if loky_pickler == _loky_pickler_name: + return + + if loky_pickler == "cloudpickle": + from joblib.externals.cloudpickle import CloudPickler as loky_pickler_cls + else: + try: + from importlib import import_module + + module_pickle = import_module(loky_pickler) + loky_pickler_cls = module_pickle.Pickler + except (ImportError, AttributeError) as e: + extra_info = ( + "\nThis error occurred while setting loky_pickler to" + f" '{loky_pickler}', as required by the env variable " + "LOKY_PICKLER or the function set_loky_pickler." + ) + e.args = (e.args[0] + extra_info,) + e.args[1:] + e.msg = e.args[0] + raise e + + util.debug( + f"Using '{loky_pickler if loky_pickler else 'cloudpickle'}' for " + "serialization." + ) + + class CustomizablePickler(loky_pickler_cls): + _loky_pickler_cls = loky_pickler_cls + + def _set_dispatch_table(self, dispatch_table): + for ancestor_class in self._loky_pickler_cls.mro(): + dt_attribute = getattr(ancestor_class, "dispatch_table", None) + if isinstance(dt_attribute, types.MemberDescriptorType): + # Ancestor class (typically _pickle.Pickler) has a + # member_descriptor for its "dispatch_table" attribute. Use + # it to set the dispatch_table as a member instead of a + # dynamic attribute in the __dict__ of the instance, + # otherwise it will not be taken into account by the C + # implementation of the dump method if a subclass defines a + # class-level dispatch_table attribute as was done in + # cloudpickle 1.6.0: + # https://github.com/joblib/loky/pull/260 + dt_attribute.__set__(self, dispatch_table) + break + + # On top of member descriptor set, also use setattr such that code + # that directly access self.dispatch_table gets a consistent view + # of the same table. + self.dispatch_table = dispatch_table + + def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL): + loky_pickler_cls.__init__(self, writer, protocol=protocol) + if reducers is None: + reducers = {} + + if hasattr(self, "dispatch_table"): + # Force a copy that we will update without mutating the + # any class level defined dispatch_table. + loky_dt = dict(self.dispatch_table) + else: + # Use standard reducers as bases + loky_dt = copyreg.dispatch_table.copy() + + # Register loky specific reducers + loky_dt.update(_dispatch_table) + + # Set the new dispatch table, taking care of the fact that we + # need to use the member_descriptor when we inherit from a + # subclass of the C implementation of the Pickler base class + # with an class level dispatch_table attribute. + self._set_dispatch_table(loky_dt) + + # Register the reducers + for type, reduce_func in reducers.items(): + self.register(type, reduce_func) + + def register(self, type, reduce_func): + """Attach a reducer function to a given type in the dispatch table.""" + self.dispatch_table[type] = reduce_func + + _LokyPickler = CustomizablePickler + _loky_pickler_name = loky_pickler + + +def get_loky_pickler_name(): + global _loky_pickler_name + return _loky_pickler_name + + +def get_loky_pickler(): + global _LokyPickler + return _LokyPickler + + +# Set it to its default value +set_loky_pickler() + + +def dump(obj, file, reducers=None, protocol=None): + """Replacement for pickle.dump() using _LokyPickler.""" + global _LokyPickler + _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj) + + +def dumps(obj, reducers=None, protocol=None): + global _LokyPickler + + buf = io.BytesIO() + dump(obj, buf, reducers=reducers, protocol=protocol) + return buf.getbuffer() + + +__all__ = ["dump", "dumps", "loads", "register", "set_loky_pickler"] + +if sys.platform == "win32": + from multiprocessing.reduction import duplicate + + __all__ += ["duplicate"] diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/resource_tracker.py b/testbed/joblib__joblib/joblib/externals/loky/backend/resource_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..25204a7a729d4d5f295070cd050c17a4ed9d49b7 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/resource_tracker.py @@ -0,0 +1,378 @@ +############################################################################### +# Server process to keep track of unlinked resources, like folders and +# semaphores and clean them. +# +# author: Thomas Moreau +# +# adapted from multiprocessing/semaphore_tracker.py (17/02/2017) +# * include custom spawnv_passfds to start the process +# * add some VERBOSE logging +# +# TODO: multiprocessing.resource_tracker was contributed to Python 3.8 so +# once loky drops support for Python 3.7 it might be possible to stop +# maintaining this loky-specific fork. As a consequence, it might also be +# possible to stop maintaining the loky.backend.synchronize fork of +# multiprocessing.synchronize. + +# +# On Unix we run a server process which keeps track of unlinked +# resources. The server ignores SIGINT and SIGTERM and reads from a +# pipe. The resource_tracker implements a reference counting scheme: each time +# a Python process anticipates the shared usage of a resource by another +# process, it signals the resource_tracker of this shared usage, and in return, +# the resource_tracker increments the resource's reference count by 1. +# Similarly, when access to a resource is closed by a Python process, the +# process notifies the resource_tracker by asking it to decrement the +# resource's reference count by 1. When the reference count drops to 0, the +# resource_tracker attempts to clean up the underlying resource. + +# Finally, every other process connected to the resource tracker has a copy of +# the writable end of the pipe used to communicate with it, so the resource +# tracker gets EOF when all other processes have exited. Then the +# resource_tracker process unlinks any remaining leaked resources (with +# reference count above 0) + +# For semaphores, this is important because the system only supports a limited +# number of named semaphores, and they will not be automatically removed till +# the next reboot. Without this resource tracker process, "killall python" +# would probably leave unlinked semaphores. + +# Note that this behavior differs from CPython's resource_tracker, which only +# implements list of shared resources, and not a proper refcounting scheme. +# Also, CPython's resource tracker will only attempt to cleanup those shared +# resources once all procsses connected to the resouce tracker have exited. + + +import os +import shutil +import sys +import signal +import warnings +import threading +from _multiprocessing import sem_unlink +from multiprocessing import util + +from . import spawn + +if sys.platform == "win32": + import _winapi + import msvcrt + from multiprocessing.reduction import duplicate + + +__all__ = ["ensure_running", "register", "unregister"] + +_HAVE_SIGMASK = hasattr(signal, "pthread_sigmask") +_IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM) + +_CLEANUP_FUNCS = {"folder": shutil.rmtree, "file": os.unlink} + +if os.name == "posix": + _CLEANUP_FUNCS["semlock"] = sem_unlink + + +VERBOSE = False + + +class ResourceTracker: + def __init__(self): + self._lock = threading.Lock() + self._fd = None + self._pid = None + + def getfd(self): + self.ensure_running() + return self._fd + + def ensure_running(self): + """Make sure that resource tracker process is running. + + This can be run from any process. Usually a child process will use + the resource created by its parent.""" + with self._lock: + if self._fd is not None: + # resource tracker was launched before, is it still running? + if self._check_alive(): + # => still alive + return + # => dead, launch it again + os.close(self._fd) + if os.name == "posix": + try: + # At this point, the resource_tracker process has been + # killed or crashed. Let's remove the process entry + # from the process table to avoid zombie processes. + os.waitpid(self._pid, 0) + except OSError: + # The process was terminated or is a child from an + # ancestor of the current process. + pass + self._fd = None + self._pid = None + + warnings.warn( + "resource_tracker: process died unexpectedly, " + "relaunching. Some folders/sempahores might " + "leak." + ) + + fds_to_pass = [] + try: + fds_to_pass.append(sys.stderr.fileno()) + except Exception: + pass + + r, w = os.pipe() + if sys.platform == "win32": + _r = duplicate(msvcrt.get_osfhandle(r), inheritable=True) + os.close(r) + r = _r + + cmd = f"from {main.__module__} import main; main({r}, {VERBOSE})" + try: + fds_to_pass.append(r) + # process will out live us, so no need to wait on pid + exe = spawn.get_executable() + args = [exe, *util._args_from_interpreter_flags(), "-c", cmd] + util.debug(f"launching resource tracker: {args}") + # bpo-33613: Register a signal mask that will block the + # signals. This signal mask will be inherited by the child + # that is going to be spawned and will protect the child from a + # race condition that can make the child die before it + # registers signal handlers for SIGINT and SIGTERM. The mask is + # unregistered after spawning the child. + try: + if _HAVE_SIGMASK: + signal.pthread_sigmask( + signal.SIG_BLOCK, _IGNORED_SIGNALS + ) + pid = spawnv_passfds(exe, args, fds_to_pass) + finally: + if _HAVE_SIGMASK: + signal.pthread_sigmask( + signal.SIG_UNBLOCK, _IGNORED_SIGNALS + ) + except BaseException: + os.close(w) + raise + else: + self._fd = w + self._pid = pid + finally: + if sys.platform == "win32": + _winapi.CloseHandle(r) + else: + os.close(r) + + def _check_alive(self): + """Check for the existence of the resource tracker process.""" + try: + self._send("PROBE", "", "") + except BrokenPipeError: + return False + else: + return True + + def register(self, name, rtype): + """Register a named resource, and increment its refcount.""" + self.ensure_running() + self._send("REGISTER", name, rtype) + + def unregister(self, name, rtype): + """Unregister a named resource with resource tracker.""" + self.ensure_running() + self._send("UNREGISTER", name, rtype) + + def maybe_unlink(self, name, rtype): + """Decrement the refcount of a resource, and delete it if it hits 0""" + self.ensure_running() + self._send("MAYBE_UNLINK", name, rtype) + + def _send(self, cmd, name, rtype): + if len(name) > 512: + # posix guarantees that writes to a pipe of less than PIPE_BUF + # bytes are atomic, and that PIPE_BUF >= 512 + raise ValueError("name too long") + msg = f"{cmd}:{name}:{rtype}\n".encode("ascii") + nbytes = os.write(self._fd, msg) + assert nbytes == len(msg) + + +_resource_tracker = ResourceTracker() +ensure_running = _resource_tracker.ensure_running +register = _resource_tracker.register +maybe_unlink = _resource_tracker.maybe_unlink +unregister = _resource_tracker.unregister +getfd = _resource_tracker.getfd + + +def main(fd, verbose=0): + """Run resource tracker.""" + # protect the process from ^C and "killall python" etc + if verbose: + util.log_to_stderr(level=util.DEBUG) + + signal.signal(signal.SIGINT, signal.SIG_IGN) + signal.signal(signal.SIGTERM, signal.SIG_IGN) + + if _HAVE_SIGMASK: + signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) + + for f in (sys.stdin, sys.stdout): + try: + f.close() + except Exception: + pass + + if verbose: + util.debug("Main resource tracker is running") + + registry = {rtype: {} for rtype in _CLEANUP_FUNCS.keys()} + try: + # keep track of registered/unregistered resources + if sys.platform == "win32": + fd = msvcrt.open_osfhandle(fd, os.O_RDONLY) + with open(fd, "rb") as f: + while True: + line = f.readline() + if line == b"": # EOF + break + try: + splitted = line.strip().decode("ascii").split(":") + # name can potentially contain separator symbols (for + # instance folders on Windows) + cmd, name, rtype = ( + splitted[0], + ":".join(splitted[1:-1]), + splitted[-1], + ) + + if cmd == "PROBE": + continue + + if rtype not in _CLEANUP_FUNCS: + raise ValueError( + f"Cannot register {name} for automatic cleanup: " + f"unknown resource type ({rtype}). Resource type " + "should be one of the following: " + f"{list(_CLEANUP_FUNCS.keys())}" + ) + + if cmd == "REGISTER": + if name not in registry[rtype]: + registry[rtype][name] = 1 + else: + registry[rtype][name] += 1 + + if verbose: + util.debug( + "[ResourceTracker] incremented refcount of " + f"{rtype} {name} " + f"(current {registry[rtype][name]})" + ) + elif cmd == "UNREGISTER": + del registry[rtype][name] + if verbose: + util.debug( + f"[ResourceTracker] unregister {name} {rtype}: " + f"registry({len(registry)})" + ) + elif cmd == "MAYBE_UNLINK": + registry[rtype][name] -= 1 + if verbose: + util.debug( + "[ResourceTracker] decremented refcount of " + f"{rtype} {name} " + f"(current {registry[rtype][name]})" + ) + + if registry[rtype][name] == 0: + del registry[rtype][name] + try: + if verbose: + util.debug( + f"[ResourceTracker] unlink {name}" + ) + _CLEANUP_FUNCS[rtype](name) + except Exception as e: + warnings.warn( + f"resource_tracker: {name}: {e!r}" + ) + + else: + raise RuntimeError(f"unrecognized command {cmd!r}") + except BaseException: + try: + sys.excepthook(*sys.exc_info()) + except BaseException: + pass + finally: + # all processes have terminated; cleanup any remaining resources + def _unlink_resources(rtype_registry, rtype): + if rtype_registry: + try: + warnings.warn( + "resource_tracker: There appear to be " + f"{len(rtype_registry)} leaked {rtype} objects to " + "clean up at shutdown" + ) + except Exception: + pass + for name in rtype_registry: + # For some reason the process which created and registered this + # resource has failed to unregister it. Presumably it has + # died. We therefore clean it up. + try: + _CLEANUP_FUNCS[rtype](name) + if verbose: + util.debug(f"[ResourceTracker] unlink {name}") + except Exception as e: + warnings.warn(f"resource_tracker: {name}: {e!r}") + + for rtype, rtype_registry in registry.items(): + if rtype == "folder": + continue + else: + _unlink_resources(rtype_registry, rtype) + + # The default cleanup routine for folders deletes everything inside + # those folders recursively, which can include other resources tracked + # by the resource tracker). To limit the risk of the resource tracker + # attempting to delete twice a resource (once as part of a tracked + # folder, and once as a resource), we delete the folders after all + # other resource types. + if "folder" in registry: + _unlink_resources(registry["folder"], "folder") + + if verbose: + util.debug("resource tracker shut down") + + +# +# Start a program with only specified fds kept open +# + + +def spawnv_passfds(path, args, passfds): + passfds = sorted(passfds) + if sys.platform != "win32": + errpipe_read, errpipe_write = os.pipe() + try: + from .reduction import _mk_inheritable + from .fork_exec import fork_exec + + _pass = [_mk_inheritable(fd) for fd in passfds] + return fork_exec(args, _pass) + finally: + os.close(errpipe_read) + os.close(errpipe_write) + else: + cmd = " ".join(f'"{x}"' for x in args) + try: + _, ht, pid, _ = _winapi.CreateProcess( + path, cmd, None, None, True, 0, None, None, None + ) + _winapi.CloseHandle(ht) + except BaseException: + pass + return pid diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/spawn.py b/testbed/joblib__joblib/joblib/externals/loky/backend/spawn.py new file mode 100644 index 0000000000000000000000000000000000000000..d011c398035f4e013ef36615a56e3bf0d8519d07 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/spawn.py @@ -0,0 +1,250 @@ +############################################################################### +# Prepares and processes the data to setup the new process environment +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from multiprocessing/spawn.py (17/02/2017) +# * Improve logging data +# +import os +import sys +import runpy +import textwrap +import types +from multiprocessing import process, util + + +if sys.platform != "win32": + WINEXE = False + WINSERVICE = False +else: + import msvcrt + from multiprocessing.reduction import duplicate + + WINEXE = sys.platform == "win32" and getattr(sys, "frozen", False) + WINSERVICE = sys.executable.lower().endswith("pythonservice.exe") + +if WINSERVICE: + _python_exe = os.path.join(sys.exec_prefix, "python.exe") +else: + _python_exe = sys.executable + + +def get_executable(): + return _python_exe + + +def _check_not_importing_main(): + if getattr(process.current_process(), "_inheriting", False): + raise RuntimeError( + textwrap.dedent( + """\ + An attempt has been made to start a new process before the + current process has finished its bootstrapping phase. + + This probably means that you are not using fork to start your + child processes and you have forgotten to use the proper idiom + in the main module: + + if __name__ == '__main__': + freeze_support() + ... + + The "freeze_support()" line can be omitted if the program + is not going to be frozen to produce an executable.""" + ) + ) + + +def get_preparation_data(name, init_main_module=True): + """Return info about parent needed by child to unpickle process object.""" + _check_not_importing_main() + d = dict( + log_to_stderr=util._log_to_stderr, + authkey=bytes(process.current_process().authkey), + name=name, + sys_argv=sys.argv, + orig_dir=process.ORIGINAL_DIR, + dir=os.getcwd(), + ) + + # Send sys_path and make sure the current directory will not be changed + d["sys_path"] = [p if p != "" else process.ORIGINAL_DIR for p in sys.path] + + # Make sure to pass the information if the multiprocessing logger is active + if util._logger is not None: + d["log_level"] = util._logger.getEffectiveLevel() + if util._logger.handlers: + h = util._logger.handlers[0] + d["log_fmt"] = h.formatter._fmt + + # Tell the child how to communicate with the resource_tracker + from .resource_tracker import _resource_tracker + + _resource_tracker.ensure_running() + d["tracker_args"] = {"pid": _resource_tracker._pid} + if sys.platform == "win32": + d["tracker_args"]["fh"] = msvcrt.get_osfhandle(_resource_tracker._fd) + else: + d["tracker_args"]["fd"] = _resource_tracker._fd + + if sys.version_info >= (3, 8) and os.name == "posix": + # joblib/loky#242: allow loky processes to retrieve the resource + # tracker of their parent in case the child processes depickles + # shared_memory objects, that are still tracked by multiprocessing's + # resource_tracker by default. + # XXX: this is a workaround that may be error prone: in the future, it + # would be better to have loky subclass multiprocessing's shared_memory + # to force registration of shared_memory segments via loky's + # resource_tracker. + from multiprocessing.resource_tracker import ( + _resource_tracker as mp_resource_tracker, + ) + + # multiprocessing's resource_tracker must be running before loky + # process is created (othewise the child won't be able to use it if it + # is created later on) + mp_resource_tracker.ensure_running() + d["mp_tracker_args"] = { + "fd": mp_resource_tracker._fd, + "pid": mp_resource_tracker._pid, + } + + # Figure out whether to initialise main in the subprocess as a module + # or through direct execution (or to leave it alone entirely) + if init_main_module: + main_module = sys.modules["__main__"] + try: + main_mod_name = getattr(main_module.__spec__, "name", None) + except BaseException: + main_mod_name = None + if main_mod_name is not None: + d["init_main_from_name"] = main_mod_name + elif sys.platform != "win32" or (not WINEXE and not WINSERVICE): + main_path = getattr(main_module, "__file__", None) + if main_path is not None: + if ( + not os.path.isabs(main_path) + and process.ORIGINAL_DIR is not None + ): + main_path = os.path.join(process.ORIGINAL_DIR, main_path) + d["init_main_from_path"] = os.path.normpath(main_path) + + return d + + +# +# Prepare current process +# +old_main_modules = [] + + +def prepare(data, parent_sentinel=None): + """Try to get current process ready to unpickle process object.""" + if "name" in data: + process.current_process().name = data["name"] + + if "authkey" in data: + process.current_process().authkey = data["authkey"] + + if "log_to_stderr" in data and data["log_to_stderr"]: + util.log_to_stderr() + + if "log_level" in data: + util.get_logger().setLevel(data["log_level"]) + + if "log_fmt" in data: + import logging + + util.get_logger().handlers[0].setFormatter( + logging.Formatter(data["log_fmt"]) + ) + + if "sys_path" in data: + sys.path = data["sys_path"] + + if "sys_argv" in data: + sys.argv = data["sys_argv"] + + if "dir" in data: + os.chdir(data["dir"]) + + if "orig_dir" in data: + process.ORIGINAL_DIR = data["orig_dir"] + + if "mp_tracker_args" in data: + from multiprocessing.resource_tracker import ( + _resource_tracker as mp_resource_tracker, + ) + + mp_resource_tracker._fd = data["mp_tracker_args"]["fd"] + mp_resource_tracker._pid = data["mp_tracker_args"]["pid"] + if "tracker_args" in data: + from .resource_tracker import _resource_tracker + + _resource_tracker._pid = data["tracker_args"]["pid"] + if sys.platform == "win32": + handle = data["tracker_args"]["fh"] + handle = duplicate(handle, source_process=parent_sentinel) + _resource_tracker._fd = msvcrt.open_osfhandle(handle, os.O_RDONLY) + else: + _resource_tracker._fd = data["tracker_args"]["fd"] + + if "init_main_from_name" in data: + _fixup_main_from_name(data["init_main_from_name"]) + elif "init_main_from_path" in data: + _fixup_main_from_path(data["init_main_from_path"]) + + +# Multiprocessing module helpers to fix up the main module in +# spawned subprocesses +def _fixup_main_from_name(mod_name): + # __main__.py files for packages, directories, zip archives, etc, run + # their "main only" code unconditionally, so we don't even try to + # populate anything in __main__, nor do we make any changes to + # __main__ attributes + current_main = sys.modules["__main__"] + if mod_name == "__main__" or mod_name.endswith(".__main__"): + return + + # If this process was forked, __main__ may already be populated + if getattr(current_main.__spec__, "name", None) == mod_name: + return + + # Otherwise, __main__ may contain some non-main code where we need to + # support unpickling it properly. We rerun it as __mp_main__ and make + # the normal __main__ an alias to that + old_main_modules.append(current_main) + main_module = types.ModuleType("__mp_main__") + main_content = runpy.run_module( + mod_name, run_name="__mp_main__", alter_sys=True + ) + main_module.__dict__.update(main_content) + sys.modules["__main__"] = sys.modules["__mp_main__"] = main_module + + +def _fixup_main_from_path(main_path): + # If this process was forked, __main__ may already be populated + current_main = sys.modules["__main__"] + + # Unfortunately, the main ipython launch script historically had no + # "if __name__ == '__main__'" guard, so we work around that + # by treating it like a __main__.py file + # See https://github.com/ipython/ipython/issues/4698 + main_name = os.path.splitext(os.path.basename(main_path))[0] + if main_name == "ipython": + return + + # Otherwise, if __file__ already has the setting we expect, + # there's nothing more to do + if getattr(current_main, "__file__", None) == main_path: + return + + # If the parent process has sent a path through rather than a module + # name we assume it is an executable script that may contain + # non-main code that needs to be executed + old_main_modules.append(current_main) + main_module = types.ModuleType("__mp_main__") + main_content = runpy.run_path(main_path, run_name="__mp_main__") + main_module.__dict__.update(main_content) + sys.modules["__main__"] = sys.modules["__mp_main__"] = main_module diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/synchronize.py b/testbed/joblib__joblib/joblib/externals/loky/backend/synchronize.py new file mode 100644 index 0000000000000000000000000000000000000000..18db3e34db979240b4a4a943ea6931db3091321d --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/synchronize.py @@ -0,0 +1,409 @@ +############################################################################### +# Synchronization primitives based on our SemLock implementation +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from multiprocessing/synchronize.py (17/02/2017) +# * Remove ctx argument for compatibility reason +# * Registers a cleanup function with the loky resource_tracker to remove the +# semaphore when the process dies instead. +# +# TODO: investigate which Python version is required to be able to use +# multiprocessing.resource_tracker and therefore multiprocessing.synchronize +# instead of a loky-specific fork. + +import os +import sys +import tempfile +import threading +import _multiprocessing +from time import time as _time +from multiprocessing import process, util +from multiprocessing.context import assert_spawning + +from . import resource_tracker + +__all__ = [ + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Condition", + "Event", +] +# Try to import the mp.synchronize module cleanly, if it fails +# raise ImportError for platforms lacking a working sem_open implementation. +# See issue 3770 +try: + from _multiprocessing import SemLock as _SemLock + from _multiprocessing import sem_unlink +except ImportError: + raise ImportError( + "This platform lacks a functioning sem_open" + " implementation, therefore, the required" + " synchronization primitives needed will not" + " function, see issue 3770." + ) + +# +# Constants +# + +RECURSIVE_MUTEX, SEMAPHORE = range(2) +SEM_VALUE_MAX = _multiprocessing.SemLock.SEM_VALUE_MAX + + +# +# Base class for semaphores and mutexes; wraps `_multiprocessing.SemLock` +# + + +class SemLock: + + _rand = tempfile._RandomNameSequence() + + def __init__(self, kind, value, maxvalue, name=None): + # unlink_now is only used on win32 or when we are using fork. + unlink_now = False + if name is None: + # Try to find an unused name for the SemLock instance. + for _ in range(100): + try: + self._semlock = _SemLock( + kind, value, maxvalue, SemLock._make_name(), unlink_now + ) + except FileExistsError: # pragma: no cover + pass + else: + break + else: # pragma: no cover + raise FileExistsError("cannot find name for semaphore") + else: + self._semlock = _SemLock(kind, value, maxvalue, name, unlink_now) + self.name = name + util.debug( + f"created semlock with handle {self._semlock.handle} and name " + f'"{self.name}"' + ) + + self._make_methods() + + def _after_fork(obj): + obj._semlock._after_fork() + + util.register_after_fork(self, _after_fork) + + # When the object is garbage collected or the + # process shuts down we unlink the semaphore name + resource_tracker.register(self._semlock.name, "semlock") + util.Finalize( + self, SemLock._cleanup, (self._semlock.name,), exitpriority=0 + ) + + @staticmethod + def _cleanup(name): + try: + sem_unlink(name) + except FileNotFoundError: + # Already unlinked, possibly by user code: ignore and make sure to + # unregister the semaphore from the resource tracker. + pass + finally: + resource_tracker.unregister(name, "semlock") + + def _make_methods(self): + self.acquire = self._semlock.acquire + self.release = self._semlock.release + + def __enter__(self): + return self._semlock.acquire() + + def __exit__(self, *args): + return self._semlock.release() + + def __getstate__(self): + assert_spawning(self) + sl = self._semlock + h = sl.handle + return (h, sl.kind, sl.maxvalue, sl.name) + + def __setstate__(self, state): + self._semlock = _SemLock._rebuild(*state) + util.debug( + f'recreated blocker with handle {state[0]!r} and name "{state[3]}"' + ) + self._make_methods() + + @staticmethod + def _make_name(): + # OSX does not support long names for semaphores + return f"/loky-{os.getpid()}-{next(SemLock._rand)}" + + +# +# Semaphore +# + + +class Semaphore(SemLock): + def __init__(self, value=1): + SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX) + + def get_value(self): + if sys.platform == "darwin": + raise NotImplementedError("OSX does not implement sem_getvalue") + return self._semlock._get_value() + + def __repr__(self): + try: + value = self._semlock._get_value() + except Exception: + value = "unknown" + return f"<{self.__class__.__name__}(value={value})>" + + +# +# Bounded semaphore +# + + +class BoundedSemaphore(Semaphore): + def __init__(self, value=1): + SemLock.__init__(self, SEMAPHORE, value, value) + + def __repr__(self): + try: + value = self._semlock._get_value() + except Exception: + value = "unknown" + return ( + f"<{self.__class__.__name__}(value={value}, " + f"maxvalue={self._semlock.maxvalue})>" + ) + + +# +# Non-recursive lock +# + + +class Lock(SemLock): + def __init__(self): + super().__init__(SEMAPHORE, 1, 1) + + def __repr__(self): + try: + if self._semlock._is_mine(): + name = process.current_process().name + if threading.current_thread().name != "MainThread": + name = f"{name}|{threading.current_thread().name}" + elif self._semlock._get_value() == 1: + name = "None" + elif self._semlock._count() > 0: + name = "SomeOtherThread" + else: + name = "SomeOtherProcess" + except Exception: + name = "unknown" + return f"<{self.__class__.__name__}(owner={name})>" + + +# +# Recursive lock +# + + +class RLock(SemLock): + def __init__(self): + super().__init__(RECURSIVE_MUTEX, 1, 1) + + def __repr__(self): + try: + if self._semlock._is_mine(): + name = process.current_process().name + if threading.current_thread().name != "MainThread": + name = f"{name}|{threading.current_thread().name}" + count = self._semlock._count() + elif self._semlock._get_value() == 1: + name, count = "None", 0 + elif self._semlock._count() > 0: + name, count = "SomeOtherThread", "nonzero" + else: + name, count = "SomeOtherProcess", "nonzero" + except Exception: + name, count = "unknown", "unknown" + return f"<{self.__class__.__name__}({name}, {count})>" + + +# +# Condition variable +# + + +class Condition: + def __init__(self, lock=None): + self._lock = lock or RLock() + self._sleeping_count = Semaphore(0) + self._woken_count = Semaphore(0) + self._wait_semaphore = Semaphore(0) + self._make_methods() + + def __getstate__(self): + assert_spawning(self) + return ( + self._lock, + self._sleeping_count, + self._woken_count, + self._wait_semaphore, + ) + + def __setstate__(self, state): + ( + self._lock, + self._sleeping_count, + self._woken_count, + self._wait_semaphore, + ) = state + self._make_methods() + + def __enter__(self): + return self._lock.__enter__() + + def __exit__(self, *args): + return self._lock.__exit__(*args) + + def _make_methods(self): + self.acquire = self._lock.acquire + self.release = self._lock.release + + def __repr__(self): + try: + num_waiters = ( + self._sleeping_count._semlock._get_value() + - self._woken_count._semlock._get_value() + ) + except Exception: + num_waiters = "unknown" + return f"<{self.__class__.__name__}({self._lock}, {num_waiters})>" + + def wait(self, timeout=None): + assert ( + self._lock._semlock._is_mine() + ), "must acquire() condition before using wait()" + + # indicate that this thread is going to sleep + self._sleeping_count.release() + + # release lock + count = self._lock._semlock._count() + for _ in range(count): + self._lock.release() + + try: + # wait for notification or timeout + return self._wait_semaphore.acquire(True, timeout) + finally: + # indicate that this thread has woken + self._woken_count.release() + + # reacquire lock + for _ in range(count): + self._lock.acquire() + + def notify(self): + assert self._lock._semlock._is_mine(), "lock is not owned" + assert not self._wait_semaphore.acquire(False) + + # to take account of timeouts since last notify() we subtract + # woken_count from sleeping_count and rezero woken_count + while self._woken_count.acquire(False): + res = self._sleeping_count.acquire(False) + assert res + + if self._sleeping_count.acquire(False): # try grabbing a sleeper + self._wait_semaphore.release() # wake up one sleeper + self._woken_count.acquire() # wait for the sleeper to wake + + # rezero _wait_semaphore in case a timeout just happened + self._wait_semaphore.acquire(False) + + def notify_all(self): + assert self._lock._semlock._is_mine(), "lock is not owned" + assert not self._wait_semaphore.acquire(False) + + # to take account of timeouts since last notify*() we subtract + # woken_count from sleeping_count and rezero woken_count + while self._woken_count.acquire(False): + res = self._sleeping_count.acquire(False) + assert res + + sleepers = 0 + while self._sleeping_count.acquire(False): + self._wait_semaphore.release() # wake up one sleeper + sleepers += 1 + + if sleepers: + for _ in range(sleepers): + self._woken_count.acquire() # wait for a sleeper to wake + + # rezero wait_semaphore in case some timeouts just happened + while self._wait_semaphore.acquire(False): + pass + + def wait_for(self, predicate, timeout=None): + result = predicate() + if result: + return result + if timeout is not None: + endtime = _time() + timeout + else: + endtime = None + waittime = None + while not result: + if endtime is not None: + waittime = endtime - _time() + if waittime <= 0: + break + self.wait(waittime) + result = predicate() + return result + + +# +# Event +# + + +class Event: + def __init__(self): + self._cond = Condition(Lock()) + self._flag = Semaphore(0) + + def is_set(self): + with self._cond: + if self._flag.acquire(False): + self._flag.release() + return True + return False + + def set(self): + with self._cond: + self._flag.acquire(False) + self._flag.release() + self._cond.notify_all() + + def clear(self): + with self._cond: + self._flag.acquire(False) + + def wait(self, timeout=None): + with self._cond: + if self._flag.acquire(False): + self._flag.release() + else: + self._cond.wait(timeout) + + if self._flag.acquire(False): + self._flag.release() + return True + return False diff --git a/testbed/joblib__joblib/joblib/externals/loky/backend/utils.py b/testbed/joblib__joblib/joblib/externals/loky/backend/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aa089f7a1bf9b577455775f6d6249baf4bd430de --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/backend/utils.py @@ -0,0 +1,181 @@ +import os +import sys +import time +import errno +import signal +import warnings +import subprocess +import traceback + +try: + import psutil +except ImportError: + psutil = None + + +def kill_process_tree(process, use_psutil=True): + """Terminate process and its descendants with SIGKILL""" + if use_psutil and psutil is not None: + _kill_process_tree_with_psutil(process) + else: + _kill_process_tree_without_psutil(process) + + +def recursive_terminate(process, use_psutil=True): + warnings.warn( + "recursive_terminate is deprecated in loky 3.2, use kill_process_tree" + "instead", + DeprecationWarning, + ) + kill_process_tree(process, use_psutil=use_psutil) + + +def _kill_process_tree_with_psutil(process): + try: + descendants = psutil.Process(process.pid).children(recursive=True) + except psutil.NoSuchProcess: + return + + # Kill the descendants in reverse order to avoid killing the parents before + # the descendant in cases where there are more processes nested. + for descendant in descendants[::-1]: + try: + descendant.kill() + except psutil.NoSuchProcess: + pass + + try: + psutil.Process(process.pid).kill() + except psutil.NoSuchProcess: + pass + process.join() + + +def _kill_process_tree_without_psutil(process): + """Terminate a process and its descendants.""" + try: + if sys.platform == "win32": + _windows_taskkill_process_tree(process.pid) + else: + _posix_recursive_kill(process.pid) + except Exception: # pragma: no cover + details = traceback.format_exc() + warnings.warn( + "Failed to kill subprocesses on this platform. Please install" + "psutil: https://github.com/giampaolo/psutil\n" + f"Details:\n{details}" + ) + # In case we cannot introspect or kill the descendants, we fall back to + # only killing the main process. + # + # Note: on Windows, process.kill() is an alias for process.terminate() + # which in turns calls the Win32 API function TerminateProcess(). + process.kill() + process.join() + + +def _windows_taskkill_process_tree(pid): + # On windows, the taskkill function with option `/T` terminate a given + # process pid and its children. + try: + subprocess.check_output( + ["taskkill", "/F", "/T", "/PID", str(pid)], stderr=None + ) + except subprocess.CalledProcessError as e: + # In Windows, taskkill returns 128, 255 for no process found. + if e.returncode not in [128, 255]: + # Let's raise to let the caller log the error details in a + # warning and only kill the root process. + raise # pragma: no cover + + +def _kill(pid): + # Not all systems (e.g. Windows) have a SIGKILL, but the C specification + # mandates a SIGTERM signal. While Windows is handled specifically above, + # let's try to be safe for other hypothetic platforms that only have + # SIGTERM without SIGKILL. + kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM) + try: + os.kill(pid, kill_signal) + except OSError as e: + # if OSError is raised with [Errno 3] no such process, the process + # is already terminated, else, raise the error and let the top + # level function raise a warning and retry to kill the process. + if e.errno != errno.ESRCH: + raise # pragma: no cover + + +def _posix_recursive_kill(pid): + """Recursively kill the descendants of a process before killing it.""" + try: + children_pids = subprocess.check_output( + ["pgrep", "-P", str(pid)], stderr=None, text=True + ) + except subprocess.CalledProcessError as e: + # `ps` returns 1 when no child process has been found + if e.returncode == 1: + children_pids = "" + else: + raise # pragma: no cover + + # Decode the result, split the cpid and remove the trailing line + for cpid in children_pids.splitlines(): + cpid = int(cpid) + _posix_recursive_kill(cpid) + + _kill(pid) + + +def get_exitcodes_terminated_worker(processes): + """Return a formatted string with the exitcodes of terminated workers. + + If necessary, wait (up to .25s) for the system to correctly set the + exitcode of one terminated worker. + """ + patience = 5 + + # Catch the exitcode of the terminated workers. There should at least be + # one. If not, wait a bit for the system to correctly set the exitcode of + # the terminated worker. + exitcodes = [ + p.exitcode for p in list(processes.values()) if p.exitcode is not None + ] + while not exitcodes and patience > 0: + patience -= 1 + exitcodes = [ + p.exitcode + for p in list(processes.values()) + if p.exitcode is not None + ] + time.sleep(0.05) + + return _format_exitcodes(exitcodes) + + +def _format_exitcodes(exitcodes): + """Format a list of exit code with names of the signals if possible""" + str_exitcodes = [ + f"{_get_exitcode_name(e)}({e})" for e in exitcodes if e is not None + ] + return "{" + ", ".join(str_exitcodes) + "}" + + +def _get_exitcode_name(exitcode): + if sys.platform == "win32": + # The exitcode are unreliable on windows (see bpo-31863). + # For this case, return UNKNOWN + return "UNKNOWN" + + if exitcode < 0: + try: + import signal + + return signal.Signals(-exitcode).name + except ValueError: + return "UNKNOWN" + elif exitcode != 255: + # The exitcode are unreliable on forkserver were 255 is always returned + # (see bpo-30589). For this case, return UNKNOWN + return "EXIT" + + return "UNKNOWN" diff --git a/testbed/joblib__joblib/joblib/externals/loky/cloudpickle_wrapper.py b/testbed/joblib__joblib/joblib/externals/loky/cloudpickle_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..099debcb711c6695f0570861293b198047bd6093 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/cloudpickle_wrapper.py @@ -0,0 +1,102 @@ +import inspect +from functools import partial +from joblib.externals.cloudpickle import dumps, loads + + +WRAP_CACHE = {} + + +class CloudpickledObjectWrapper: + def __init__(self, obj, keep_wrapper=False): + self._obj = obj + self._keep_wrapper = keep_wrapper + + def __reduce__(self): + _pickled_object = dumps(self._obj) + if not self._keep_wrapper: + return loads, (_pickled_object,) + + return _reconstruct_wrapper, (_pickled_object, self._keep_wrapper) + + def __getattr__(self, attr): + # Ensure that the wrapped object can be used seemlessly as the + # previous object. + if attr not in ["_obj", "_keep_wrapper"]: + return getattr(self._obj, attr) + return getattr(self, attr) + + +# Make sure the wrapped object conserves the callable property +class CallableObjectWrapper(CloudpickledObjectWrapper): + def __call__(self, *args, **kwargs): + return self._obj(*args, **kwargs) + + +def _wrap_non_picklable_objects(obj, keep_wrapper): + if callable(obj): + return CallableObjectWrapper(obj, keep_wrapper=keep_wrapper) + return CloudpickledObjectWrapper(obj, keep_wrapper=keep_wrapper) + + +def _reconstruct_wrapper(_pickled_object, keep_wrapper): + obj = loads(_pickled_object) + return _wrap_non_picklable_objects(obj, keep_wrapper) + + +def _wrap_objects_when_needed(obj): + # Function to introspect an object and decide if it should be wrapped or + # not. + need_wrap = "__main__" in getattr(obj, "__module__", "") + if isinstance(obj, partial): + return partial( + _wrap_objects_when_needed(obj.func), + *[_wrap_objects_when_needed(a) for a in obj.args], + **{ + k: _wrap_objects_when_needed(v) + for k, v in obj.keywords.items() + } + ) + if callable(obj): + # Need wrap if the object is a function defined in a local scope of + # another function. + func_code = getattr(obj, "__code__", "") + need_wrap |= getattr(func_code, "co_flags", 0) & inspect.CO_NESTED + + # Need wrap if the obj is a lambda expression + func_name = getattr(obj, "__name__", "") + need_wrap |= "" in func_name + + if not need_wrap: + return obj + + wrapped_obj = WRAP_CACHE.get(obj) + if wrapped_obj is None: + wrapped_obj = _wrap_non_picklable_objects(obj, keep_wrapper=False) + WRAP_CACHE[obj] = wrapped_obj + return wrapped_obj + + +def wrap_non_picklable_objects(obj, keep_wrapper=True): + """Wrapper for non-picklable object to use cloudpickle to serialize them. + + Note that this wrapper tends to slow down the serialization process as it + is done with cloudpickle which is typically slower compared to pickle. The + proper way to solve serialization issues is to avoid defining functions and + objects in the main scripts and to implement __reduce__ functions for + complex classes. + """ + # If obj is a class, create a CloudpickledClassWrapper which instantiates + # the object internally and wrap it directly in a CloudpickledObjectWrapper + if inspect.isclass(obj): + + class CloudpickledClassWrapper(CloudpickledObjectWrapper): + def __init__(self, *args, **kwargs): + self._obj = obj(*args, **kwargs) + self._keep_wrapper = keep_wrapper + + CloudpickledClassWrapper.__name__ = obj.__name__ + return CloudpickledClassWrapper + + # If obj is an instance of a class, just wrap it in a regular + # CloudpickledObjectWrapper + return _wrap_non_picklable_objects(obj, keep_wrapper=keep_wrapper) diff --git a/testbed/joblib__joblib/joblib/externals/loky/initializers.py b/testbed/joblib__joblib/joblib/externals/loky/initializers.py new file mode 100644 index 0000000000000000000000000000000000000000..aea0e56c25d0d74e04788493058549a1399f8342 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/initializers.py @@ -0,0 +1,80 @@ +import warnings + + +def _viztracer_init(init_kwargs): + """Initialize viztracer's profiler in worker processes""" + from viztracer import VizTracer + + tracer = VizTracer(**init_kwargs) + tracer.register_exit() + tracer.start() + + +def _make_viztracer_initializer_and_initargs(): + try: + import viztracer + + tracer = viztracer.get_tracer() + if tracer is not None and getattr(tracer, "enable", False): + # Profiler is active: introspect its configuration to + # initialize the workers with the same configuration. + return _viztracer_init, (tracer.init_kwargs,) + except ImportError: + # viztracer is not installed: nothing to do + pass + except Exception as e: + # In case viztracer's API evolve, we do not want to crash loky but + # we want to know about it to be able to update loky. + warnings.warn(f"Unable to introspect viztracer state: {e}") + return None, () + + +class _ChainedInitializer: + """Compound worker initializer + + This is meant to be used in conjunction with _chain_initializers to + produce the necessary chained_args list to be passed to __call__. + """ + + def __init__(self, initializers): + self._initializers = initializers + + def __call__(self, *chained_args): + for initializer, args in zip(self._initializers, chained_args): + initializer(*args) + + +def _chain_initializers(initializer_and_args): + """Convenience helper to combine a sequence of initializers. + + If some initializers are None, they are filtered out. + """ + filtered_initializers = [] + filtered_initargs = [] + for initializer, initargs in initializer_and_args: + if initializer is not None: + filtered_initializers.append(initializer) + filtered_initargs.append(initargs) + + if not filtered_initializers: + return None, () + elif len(filtered_initializers) == 1: + return filtered_initializers[0], filtered_initargs[0] + else: + return _ChainedInitializer(filtered_initializers), filtered_initargs + + +def _prepare_initializer(initializer, initargs): + if initializer is not None and not callable(initializer): + raise TypeError( + f"initializer must be a callable, got: {initializer!r}" + ) + + # Introspect runtime to determine if we need to propagate the viztracer + # profiler information to the workers: + return _chain_initializers( + [ + (initializer, initargs), + _make_viztracer_initializer_and_initargs(), + ] + ) diff --git a/testbed/joblib__joblib/joblib/externals/loky/process_executor.py b/testbed/joblib__joblib/joblib/externals/loky/process_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..1e08cc21f21dad4e9df4f547add59a8660395043 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/process_executor.py @@ -0,0 +1,1314 @@ +############################################################################### +# Re-implementation of the ProcessPoolExecutor more robust to faults +# +# author: Thomas Moreau and Olivier Grisel +# +# adapted from concurrent/futures/process_pool_executor.py (17/02/2017) +# * Add an extra management thread to detect executor_manager_thread failures, +# * Improve the shutdown process to avoid deadlocks, +# * Add timeout for workers, +# * More robust pickling process. +# +# Copyright 2009 Brian Quinlan. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Implements ProcessPoolExecutor. + +The follow diagram and text describe the data-flow through the system: + +|======================= In-process =====================|== Out-of-process ==| + ++----------+ +----------+ +--------+ +-----------+ +---------+ +| | => | Work Ids | | | | Call Q | | Process | +| | +----------+ | | +-----------+ | Pool | +| | | ... | | | | ... | +---------+ +| | | 6 | => | | => | 5, call() | => | | +| | | 7 | | | | ... | | | +| Process | | ... | | Local | +-----------+ | Process | +| Pool | +----------+ | Worker | | #1..n | +| Executor | | Thread | | | +| | +----------- + | | +-----------+ | | +| | <=> | Work Items | <=> | | <= | Result Q | <= | | +| | +------------+ | | +-----------+ | | +| | | 6: call() | | | | ... | | | +| | | future | +--------+ | 4, result | | | +| | | ... | | 3, except | | | ++----------+ +------------+ +-----------+ +---------+ + +Executor.submit() called: +- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict +- adds the id of the _WorkItem to the "Work Ids" queue + +Local worker thread: +- reads work ids from the "Work Ids" queue and looks up the corresponding + WorkItem from the "Work Items" dict: if the work item has been cancelled then + it is simply removed from the dict, otherwise it is repackaged as a + _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" + until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because + calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). +- reads _ResultItems from "Result Q", updates the future stored in the + "Work Items" dict and deletes the dict entry + +Process #1..n: +- reads _CallItems from "Call Q", executes the calls, and puts the resulting + _ResultItems in "Result Q" +""" + + +__author__ = "Thomas Moreau (thomas.moreau.2010@gmail.com)" + + +import os +import gc +import sys +import queue +import struct +import weakref +import warnings +import itertools +import traceback +import threading +from time import time, sleep +import multiprocessing as mp +from functools import partial +from pickle import PicklingError +from concurrent.futures import Executor +from concurrent.futures._base import LOGGER +from concurrent.futures.process import BrokenProcessPool as _BPPException +from multiprocessing.connection import wait + +from ._base import Future +from .backend import get_context +from .backend.context import cpu_count, _MAX_WINDOWS_WORKERS +from .backend.queues import Queue, SimpleQueue +from .backend.reduction import set_loky_pickler, get_loky_pickler_name +from .backend.utils import kill_process_tree, get_exitcodes_terminated_worker +from .initializers import _prepare_initializer + + +# Mechanism to prevent infinite process spawning. When a worker of a +# ProcessPoolExecutor nested in MAX_DEPTH Executor tries to create a new +# Executor, a LokyRecursionError is raised +MAX_DEPTH = int(os.environ.get("LOKY_MAX_DEPTH", 10)) +_CURRENT_DEPTH = 0 + +# Minimum time interval between two consecutive memory leak protection checks. +_MEMORY_LEAK_CHECK_DELAY = 1.0 + +# Number of bytes of memory usage allowed over the reference process size. +_MAX_MEMORY_LEAK_SIZE = int(3e8) + + +try: + from psutil import Process + + _USE_PSUTIL = True + + def _get_memory_usage(pid, force_gc=False): + if force_gc: + gc.collect() + + mem_size = Process(pid).memory_info().rss + mp.util.debug(f"psutil return memory size: {mem_size}") + return mem_size + +except ImportError: + _USE_PSUTIL = False + + +class _ThreadWakeup: + def __init__(self): + self._closed = False + self._reader, self._writer = mp.Pipe(duplex=False) + + def close(self): + if not self._closed: + self._closed = True + self._writer.close() + self._reader.close() + + def wakeup(self): + if not self._closed: + self._writer.send_bytes(b"") + + def clear(self): + if not self._closed: + while self._reader.poll(): + self._reader.recv_bytes() + + +class _ExecutorFlags: + """necessary references to maintain executor states without preventing gc + + It permits to keep the information needed by executor_manager_thread + and crash_detection_thread to maintain the pool without preventing the + garbage collection of unreferenced executors. + """ + + def __init__(self, shutdown_lock): + + self.shutdown = False + self.broken = None + self.kill_workers = False + self.shutdown_lock = shutdown_lock + + def flag_as_shutting_down(self, kill_workers=None): + with self.shutdown_lock: + self.shutdown = True + if kill_workers is not None: + self.kill_workers = kill_workers + + def flag_as_broken(self, broken): + with self.shutdown_lock: + self.shutdown = True + self.broken = broken + + +# Prior to 3.9, executor_manager_thread is created as daemon thread. This means +# that it is not joined automatically when the interpreter is shutting down. +# To work around this problem, an exit handler is installed to tell the +# thread to exit when the interpreter is shutting down and then waits until +# it finishes. The thread needs to be daemonized because the atexit hooks are +# called after all non daemonized threads are joined. +# +# Starting 3.9, there exists a specific atexit hook to be called before joining +# the threads so the executor_manager_thread does not need to be daemonized +# anymore. +# +# The atexit hooks are registered when starting the first ProcessPoolExecutor +# to avoid import having an effect on the interpreter. + +_global_shutdown = False +_global_shutdown_lock = threading.Lock() +_threads_wakeups = weakref.WeakKeyDictionary() + + +def _python_exit(): + global _global_shutdown + _global_shutdown = True + + # Materialize the list of items to avoid error due to iterating over + # changing size dictionary. + items = list(_threads_wakeups.items()) + if len(items) > 0: + mp.util.debug( + "Interpreter shutting down. Waking up {len(items)}" + f"executor_manager_thread:\n{items}" + ) + + # Wake up the executor_manager_thread's so they can detect the interpreter + # is shutting down and exit. + for _, (shutdown_lock, thread_wakeup) in items: + with shutdown_lock: + thread_wakeup.wakeup() + + # Collect the executor_manager_thread's to make sure we exit cleanly. + for thread, _ in items: + # This locks is to prevent situations where an executor is gc'ed in one + # thread while the atexit finalizer is running in another thread. This + # can happen when joblib is used in pypy for instance. + with _global_shutdown_lock: + thread.join() + + +# With the fork context, _thread_wakeups is propagated to children. +# Clear it after fork to avoid some situation that can cause some +# freeze when joining the workers. +mp.util.register_after_fork(_threads_wakeups, lambda obj: obj.clear()) + + +# Module variable to register the at_exit call +process_pool_executor_at_exit = None + +# Controls how many more calls than processes will be queued in the call queue. +# A smaller number will mean that processes spend more time idle waiting for +# work while a larger number will make Future.cancel() succeed less frequently +# (Futures in the call queue cannot be cancelled). +EXTRA_QUEUED_CALLS = 1 + + +class _RemoteTraceback(Exception): + """Embed stringification of remote traceback in local traceback""" + + def __init__(self, tb=None): + self.tb = f'\n"""\n{tb}"""' + + def __str__(self): + return self.tb + + +# Do not inherit from BaseException to mirror +# concurrent.futures.process._ExceptionWithTraceback +class _ExceptionWithTraceback: + def __init__(self, exc): + tb = getattr(exc, "__traceback__", None) + if tb is None: + _, _, tb = sys.exc_info() + tb = traceback.format_exception(type(exc), exc, tb) + tb = "".join(tb) + self.exc = exc + self.tb = tb + + def __reduce__(self): + return _rebuild_exc, (self.exc, self.tb) + + +def _rebuild_exc(exc, tb): + exc.__cause__ = _RemoteTraceback(tb) + return exc + + +class _WorkItem: + + __slots__ = ["future", "fn", "args", "kwargs"] + + def __init__(self, future, fn, args, kwargs): + self.future = future + self.fn = fn + self.args = args + self.kwargs = kwargs + + +class _ResultItem: + def __init__(self, work_id, exception=None, result=None): + self.work_id = work_id + self.exception = exception + self.result = result + + +class _CallItem: + def __init__(self, work_id, fn, args, kwargs): + self.work_id = work_id + self.fn = fn + self.args = args + self.kwargs = kwargs + + # Store the current loky_pickler so it is correctly set in the worker + self.loky_pickler = get_loky_pickler_name() + + def __call__(self): + set_loky_pickler(self.loky_pickler) + return self.fn(*self.args, **self.kwargs) + + def __repr__(self): + return ( + f"CallItem({self.work_id}, {self.fn}, {self.args}, {self.kwargs})" + ) + + +class _SafeQueue(Queue): + """Safe Queue set exception to the future object linked to a job""" + + def __init__( + self, + max_size=0, + ctx=None, + pending_work_items=None, + running_work_items=None, + thread_wakeup=None, + reducers=None, + ): + self.thread_wakeup = thread_wakeup + self.pending_work_items = pending_work_items + self.running_work_items = running_work_items + super().__init__(max_size, reducers=reducers, ctx=ctx) + + def _on_queue_feeder_error(self, e, obj): + if isinstance(obj, _CallItem): + # format traceback only works on python3 + if isinstance(e, struct.error): + raised_error = RuntimeError( + "The task could not be sent to the workers as it is too " + "large for `send_bytes`." + ) + else: + raised_error = PicklingError( + "Could not pickle the task to send it to the workers." + ) + tb = traceback.format_exception( + type(e), e, getattr(e, "__traceback__", None) + ) + raised_error.__cause__ = _RemoteTraceback("".join(tb)) + work_item = self.pending_work_items.pop(obj.work_id, None) + self.running_work_items.remove(obj.work_id) + # work_item can be None if another process terminated. In this + # case, the executor_manager_thread fails all work_items with + # BrokenProcessPool + if work_item is not None: + work_item.future.set_exception(raised_error) + del work_item + self.thread_wakeup.wakeup() + else: + super()._on_queue_feeder_error(e, obj) + + +def _get_chunks(chunksize, *iterables): + """Iterates over zip()ed iterables in chunks.""" + it = zip(*iterables) + while True: + chunk = tuple(itertools.islice(it, chunksize)) + if not chunk: + return + yield chunk + + +def _process_chunk(fn, chunk): + """Processes a chunk of an iterable passed to map. + + Runs the function passed to map() on a chunk of the + iterable passed to map. + + This function is run in a separate process. + + """ + return [fn(*args) for args in chunk] + + +def _sendback_result(result_queue, work_id, result=None, exception=None): + """Safely send back the given result or exception""" + try: + result_queue.put( + _ResultItem(work_id, result=result, exception=exception) + ) + except BaseException as e: + exc = _ExceptionWithTraceback(e) + result_queue.put(_ResultItem(work_id, exception=exc)) + + +def _process_worker( + call_queue, + result_queue, + initializer, + initargs, + processes_management_lock, + timeout, + worker_exit_lock, + current_depth, +): + """Evaluates calls from call_queue and places the results in result_queue. + + This worker is run in a separate process. + + Args: + call_queue: A ctx.Queue of _CallItems that will be read and + evaluated by the worker. + result_queue: A ctx.Queue of _ResultItems that will written + to by the worker. + initializer: A callable initializer, or None + initargs: A tuple of args for the initializer + processes_management_lock: A ctx.Lock avoiding worker timeout while + some workers are being spawned. + timeout: maximum time to wait for a new item in the call_queue. If that + time is expired, the worker will shutdown. + worker_exit_lock: Lock to avoid flagging the executor as broken on + workers timeout. + current_depth: Nested parallelism level, to avoid infinite spawning. + """ + if initializer is not None: + try: + initializer(*initargs) + except BaseException: + LOGGER.critical("Exception in initializer:", exc_info=True) + # The parent will notice that the process stopped and + # mark the pool broken + return + + # set the global _CURRENT_DEPTH mechanism to limit recursive call + global _CURRENT_DEPTH + _CURRENT_DEPTH = current_depth + _process_reference_size = None + _last_memory_leak_check = None + pid = os.getpid() + + mp.util.debug(f"Worker started with timeout={timeout}") + while True: + try: + call_item = call_queue.get(block=True, timeout=timeout) + if call_item is None: + mp.util.info("Shutting down worker on sentinel") + except queue.Empty: + mp.util.info(f"Shutting down worker after timeout {timeout:0.3f}s") + if processes_management_lock.acquire(block=False): + processes_management_lock.release() + call_item = None + else: + mp.util.info("Could not acquire processes_management_lock") + continue + except BaseException: + previous_tb = traceback.format_exc() + try: + result_queue.put(_RemoteTraceback(previous_tb)) + except BaseException: + # If we cannot format correctly the exception, at least print + # the traceback. + print(previous_tb) + mp.util.debug("Exiting with code 1") + sys.exit(1) + if call_item is None: + # Notify queue management thread about worker shutdown + result_queue.put(pid) + is_clean = worker_exit_lock.acquire(True, timeout=30) + + # Early notify any loky executor running in this worker process + # (nested parallelism) that this process is about to shutdown to + # avoid a deadlock waiting undifinitely for the worker to finish. + _python_exit() + + if is_clean: + mp.util.debug("Exited cleanly") + else: + mp.util.info("Main process did not release worker_exit") + return + try: + r = call_item() + except BaseException as e: + exc = _ExceptionWithTraceback(e) + result_queue.put(_ResultItem(call_item.work_id, exception=exc)) + else: + _sendback_result(result_queue, call_item.work_id, result=r) + del r + + # Free the resource as soon as possible, to avoid holding onto + # open files or shared memory that is not needed anymore + del call_item + + if _USE_PSUTIL: + if _process_reference_size is None: + # Make reference measurement after the first call + _process_reference_size = _get_memory_usage(pid, force_gc=True) + _last_memory_leak_check = time() + continue + if time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY: + mem_usage = _get_memory_usage(pid) + _last_memory_leak_check = time() + if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE: + # Memory usage stays within bounds: everything is fine. + continue + + # Check again memory usage; this time take the measurement + # after a forced garbage collection to break any reference + # cycles. + mem_usage = _get_memory_usage(pid, force_gc=True) + _last_memory_leak_check = time() + if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE: + # The GC managed to free the memory: everything is fine. + continue + + # The process is leaking memory: let the master process + # know that we need to start a new worker. + mp.util.info("Memory leak detected: shutting down worker") + result_queue.put(pid) + with worker_exit_lock: + mp.util.debug("Exit due to memory leak") + return + else: + # if psutil is not installed, trigger gc.collect events + # regularly to limit potential memory leaks due to reference cycles + if _last_memory_leak_check is None or ( + time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY + ): + gc.collect() + _last_memory_leak_check = time() + + +class _ExecutorManagerThread(threading.Thread): + """Manages the communication between this process and the worker processes. + + The manager is run in a local thread. + + Args: + executor: A reference to the ProcessPoolExecutor that owns + this thread. A weakref will be own by the manager as well as + references to internal objects used to introspect the state of + the executor. + """ + + def __init__(self, executor): + # Store references to necessary internals of the executor. + + # A _ThreadWakeup to allow waking up the executor_manager_thread from + # the main Thread and avoid deadlocks caused by permanently + # locked queues. + self.thread_wakeup = executor._executor_manager_thread_wakeup + self.shutdown_lock = executor._shutdown_lock + + # A weakref.ref to the ProcessPoolExecutor that owns this thread. Used + # to determine if the ProcessPoolExecutor has been garbage collected + # and that the manager can exit. + # When the executor gets garbage collected, the weakref callback + # will wake up the queue management thread so that it can terminate + # if there is no pending work item. + def weakref_cb( + _, + thread_wakeup=self.thread_wakeup, + shutdown_lock=self.shutdown_lock, + ): + if mp is not None: + # At this point, the multiprocessing module can already be + # garbage collected. We only log debug info when still + # possible. + mp.util.debug( + "Executor collected: triggering callback for" + " QueueManager wakeup" + ) + with shutdown_lock: + thread_wakeup.wakeup() + + self.executor_reference = weakref.ref(executor, weakref_cb) + + # The flags of the executor + self.executor_flags = executor._flags + + # A list of the ctx.Process instances used as workers. + self.processes = executor._processes + + # A ctx.Queue that will be filled with _CallItems derived from + # _WorkItems for processing by the process workers. + self.call_queue = executor._call_queue + + # A ctx.SimpleQueue of _ResultItems generated by the process workers. + self.result_queue = executor._result_queue + + # A queue.Queue of work ids e.g. Queue([5, 6, ...]). + self.work_ids_queue = executor._work_ids + + # A dict mapping work ids to _WorkItems e.g. + # {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + self.pending_work_items = executor._pending_work_items + + # A list of the work_ids that are currently running + self.running_work_items = executor._running_work_items + + # A lock to avoid concurrent shutdown of workers on timeout and spawn + # of new processes or shut down + self.processes_management_lock = executor._processes_management_lock + + super().__init__(name="ExecutorManagerThread") + if sys.version_info < (3, 9): + self.daemon = True + + def run(self): + # Main loop for the executor manager thread. + + while True: + self.add_call_item_to_queue() + + result_item, is_broken, bpe = self.wait_result_broken_or_wakeup() + + if is_broken: + self.terminate_broken(bpe) + return + if result_item is not None: + self.process_result_item(result_item) + # Delete reference to result_item to avoid keeping references + # while waiting on new results. + del result_item + + if self.is_shutting_down(): + self.flag_executor_shutting_down() + + # Since no new work items can be added, it is safe to shutdown + # this thread if there are no pending work items. + if not self.pending_work_items: + self.join_executor_internals() + return + + def add_call_item_to_queue(self): + # Fills call_queue with _WorkItems from pending_work_items. + # This function never blocks. + while True: + if self.call_queue.full(): + return + try: + work_id = self.work_ids_queue.get(block=False) + except queue.Empty: + return + else: + work_item = self.pending_work_items[work_id] + + if work_item.future.set_running_or_notify_cancel(): + self.running_work_items += [work_id] + self.call_queue.put( + _CallItem( + work_id, + work_item.fn, + work_item.args, + work_item.kwargs, + ), + block=True, + ) + else: + del self.pending_work_items[work_id] + continue + + def wait_result_broken_or_wakeup(self): + # Wait for a result to be ready in the result_queue while checking + # that all worker processes are still running, or for a wake up + # signal send. The wake up signals come either from new tasks being + # submitted, from the executor being shutdown/gc-ed, or from the + # shutdown of the python interpreter. + result_reader = self.result_queue._reader + wakeup_reader = self.thread_wakeup._reader + readers = [result_reader, wakeup_reader] + worker_sentinels = [p.sentinel for p in list(self.processes.values())] + ready = wait(readers + worker_sentinels) + + bpe = None + is_broken = True + result_item = None + if result_reader in ready: + try: + result_item = result_reader.recv() + if isinstance(result_item, _RemoteTraceback): + bpe = BrokenProcessPool( + "A task has failed to un-serialize. Please ensure that" + " the arguments of the function are all picklable." + ) + bpe.__cause__ = result_item + else: + is_broken = False + except BaseException as e: + bpe = BrokenProcessPool( + "A result has failed to un-serialize. Please ensure that " + "the objects returned by the function are always " + "picklable." + ) + tb = traceback.format_exception( + type(e), e, getattr(e, "__traceback__", None) + ) + bpe.__cause__ = _RemoteTraceback("".join(tb)) + + elif wakeup_reader in ready: + # This is simply a wake-up event that might either trigger putting + # more tasks in the queue or trigger the clean up of resources. + is_broken = False + else: + # A worker has terminated and we don't know why, set the state of + # the executor as broken + exit_codes = "" + if sys.platform != "win32": + # In Windows, introspecting terminated workers exitcodes seems + # unstable, therefore they are not appended in the exception + # message. + exit_codes = ( + "\nThe exit codes of the workers are " + f"{get_exitcodes_terminated_worker(self.processes)}" + ) + mp.util.debug( + "A worker unexpectedly terminated. Workers that " + "might have caused the breakage: " + + str( + { + p.name: p.exitcode + for p in list(self.processes.values()) + if p is not None and p.sentinel in ready + } + ) + ) + bpe = TerminatedWorkerError( + "A worker process managed by the executor was unexpectedly " + "terminated. This could be caused by a segmentation fault " + "while calling the function or by an excessive memory usage " + "causing the Operating System to kill the worker.\n" + f"{exit_codes}" + ) + + self.thread_wakeup.clear() + + return result_item, is_broken, bpe + + def process_result_item(self, result_item): + # Process the received a result_item. This can be either the PID of a + # worker that exited gracefully or a _ResultItem + + if isinstance(result_item, int): + # Clean shutdown of a worker using its PID, either on request + # by the executor.shutdown method or by the timeout of the worker + # itself: we should not mark the executor as broken. + with self.processes_management_lock: + p = self.processes.pop(result_item, None) + + # p can be None if the executor is concurrently shutting down. + if p is not None: + p._worker_exit_lock.release() + mp.util.debug( + f"joining {p.name} when processing {p.pid} as result_item" + ) + p.join() + del p + + # Make sure the executor have the right number of worker, even if a + # worker timeout while some jobs were submitted. If some work is + # pending or there is less processes than running items, we need to + # start a new Process and raise a warning. + n_pending = len(self.pending_work_items) + n_running = len(self.running_work_items) + if n_pending - n_running > 0 or n_running > len(self.processes): + executor = self.executor_reference() + if ( + executor is not None + and len(self.processes) < executor._max_workers + ): + warnings.warn( + "A worker stopped while some jobs were given to the " + "executor. This can be caused by a too short worker " + "timeout or by a memory leak.", + UserWarning, + ) + with executor._processes_management_lock: + executor._adjust_process_count() + executor = None + else: + # Received a _ResultItem so mark the future as completed. + work_item = self.pending_work_items.pop(result_item.work_id, None) + # work_item can be None if another process terminated (see above) + if work_item is not None: + if result_item.exception: + work_item.future.set_exception(result_item.exception) + else: + work_item.future.set_result(result_item.result) + self.running_work_items.remove(result_item.work_id) + + def is_shutting_down(self): + # Check whether we should start shutting down the executor. + executor = self.executor_reference() + # No more work items can be added if: + # - The interpreter is shutting down OR + # - The executor that owns this thread is not broken AND + # * The executor that owns this worker has been collected OR + # * The executor that owns this worker has been shutdown. + # If the executor is broken, it should be detected in the next loop. + return _global_shutdown or ( + (executor is None or self.executor_flags.shutdown) + and not self.executor_flags.broken + ) + + def terminate_broken(self, bpe): + # Terminate the executor because it is in a broken state. The bpe + # argument can be used to display more information on the error that + # lead the executor into becoming broken. + + # Mark the process pool broken so that submits fail right now. + self.executor_flags.flag_as_broken(bpe) + + # Mark pending tasks as failed. + for work_item in self.pending_work_items.values(): + work_item.future.set_exception(bpe) + # Delete references to object. See issue16284 + del work_item + self.pending_work_items.clear() + + # Terminate remaining workers forcibly: the queues or their + # locks may be in a dirty state and block forever. + self.kill_workers(reason="broken executor") + + # clean up resources + self.join_executor_internals() + + def flag_executor_shutting_down(self): + # Flag the executor as shutting down and cancel remaining tasks if + # requested as early as possible if it is not gc-ed yet. + self.executor_flags.flag_as_shutting_down() + + # Cancel pending work items if requested. + if self.executor_flags.kill_workers: + while self.pending_work_items: + _, work_item = self.pending_work_items.popitem() + work_item.future.set_exception( + ShutdownExecutorError( + "The Executor was shutdown with `kill_workers=True` " + "before this job could complete." + ) + ) + del work_item + + # Kill the remaining worker forcibly to no waste time joining them + self.kill_workers(reason="executor shutting down") + + def kill_workers(self, reason=""): + # Terminate the remaining workers using SIGKILL. This function also + # terminates descendant workers of the children in case there is some + # nested parallelism. + while self.processes: + _, p = self.processes.popitem() + mp.util.debug(f"terminate process {p.name}, reason: {reason}") + try: + kill_process_tree(p) + except ProcessLookupError: # pragma: no cover + pass + + def shutdown_workers(self): + # shutdown all workers in self.processes + + # Create a list to avoid RuntimeError due to concurrent modification of + # processes. nb_children_alive is thus an upper bound. Also release the + # processes' _worker_exit_lock to accelerate the shutdown procedure, as + # there is no need for hand-shake here. + with self.processes_management_lock: + n_children_to_stop = 0 + for p in list(self.processes.values()): + mp.util.debug(f"releasing worker exit lock on {p.name}") + p._worker_exit_lock.release() + n_children_to_stop += 1 + + mp.util.debug(f"found {n_children_to_stop} processes to stop") + + # Send the right number of sentinels, to make sure all children are + # properly terminated. Do it with a mechanism that avoid hanging on + # Full queue when all workers have already been shutdown. + n_sentinels_sent = 0 + cooldown_time = 0.001 + while ( + n_sentinels_sent < n_children_to_stop + and self.get_n_children_alive() > 0 + ): + for _ in range(n_children_to_stop - n_sentinels_sent): + try: + self.call_queue.put_nowait(None) + n_sentinels_sent += 1 + except queue.Full as e: + if cooldown_time > 5.0: + mp.util.info( + "failed to send all sentinels and exit with error." + f"\ncall_queue size={self.call_queue._maxsize}; " + f" full is {self.call_queue.full()}; " + ) + raise e + mp.util.info( + "full call_queue prevented to send all sentinels at " + "once, waiting..." + ) + sleep(cooldown_time) + cooldown_time *= 1.2 + break + + mp.util.debug(f"sent {n_sentinels_sent} sentinels to the call queue") + + def join_executor_internals(self): + self.shutdown_workers() + + # Release the queue's resources as soon as possible. Flag the feeder + # thread for clean exit to avoid having the crash detection thread flag + # the Executor as broken during the shutdown. This is safe as either: + # * We don't need to communicate with the workers anymore + # * There is nothing left in the Queue buffer except None sentinels + mp.util.debug("closing call_queue") + self.call_queue.close() + self.call_queue.join_thread() + + # Closing result_queue + mp.util.debug("closing result_queue") + self.result_queue.close() + + mp.util.debug("closing thread_wakeup") + with self.shutdown_lock: + self.thread_wakeup.close() + + # If .join() is not called on the created processes then + # some ctx.Queue methods may deadlock on macOS. + with self.processes_management_lock: + mp.util.debug(f"joining {len(self.processes)} processes") + n_joined_processes = 0 + while True: + try: + pid, p = self.processes.popitem() + mp.util.debug(f"joining process {p.name} with pid {pid}") + p.join() + n_joined_processes += 1 + except KeyError: + break + + mp.util.debug( + "executor management thread clean shutdown of " + f"{n_joined_processes} workers" + ) + + def get_n_children_alive(self): + # This is an upper bound on the number of children alive. + with self.processes_management_lock: + return sum(p.is_alive() for p in list(self.processes.values())) + + +_system_limits_checked = False +_system_limited = None + + +def _check_system_limits(): + global _system_limits_checked, _system_limited + if _system_limits_checked and _system_limited: + raise NotImplementedError(_system_limited) + _system_limits_checked = True + try: + nsems_max = os.sysconf("SC_SEM_NSEMS_MAX") + except (AttributeError, ValueError): + # sysconf not available or setting not available + return + if nsems_max == -1: + # undetermined limit, assume that limit is determined + # by available memory only + return + if nsems_max >= 256: + # minimum number of semaphores available + # according to POSIX + return + _system_limited = ( + f"system provides too few semaphores ({nsems_max} available, " + "256 necessary)" + ) + raise NotImplementedError(_system_limited) + + +def _chain_from_iterable_of_lists(iterable): + """ + Specialized implementation of itertools.chain.from_iterable. + Each item in *iterable* should be a list. This function is + careful not to keep references to yielded objects. + """ + for element in iterable: + element.reverse() + while element: + yield element.pop() + + +def _check_max_depth(context): + # Limit the maxmal recursion level + global _CURRENT_DEPTH + if context.get_start_method() == "fork" and _CURRENT_DEPTH > 0: + raise LokyRecursionError( + "Could not spawn extra nested processes at depth superior to " + "MAX_DEPTH=1. It is not possible to increase this limit when " + "using the 'fork' start method." + ) + + if 0 < MAX_DEPTH and _CURRENT_DEPTH + 1 > MAX_DEPTH: + raise LokyRecursionError( + "Could not spawn extra nested processes at depth superior to " + f"MAX_DEPTH={MAX_DEPTH}. If this is intendend, you can change " + "this limit with the LOKY_MAX_DEPTH environment variable." + ) + + +class LokyRecursionError(RuntimeError): + """A process tries to spawn too many levels of nested processes.""" + + +class BrokenProcessPool(_BPPException): + """ + Raised when the executor is broken while a future was in the running state. + The cause can an error raised when unpickling the task in the worker + process or when unpickling the result value in the parent process. It can + also be caused by a worker process being terminated unexpectedly. + """ + + +class TerminatedWorkerError(BrokenProcessPool): + """ + Raised when a process in a ProcessPoolExecutor terminated abruptly + while a future was in the running state. + """ + + +# Alias for backward compat (for code written for loky 1.1.4 and earlier). Do +# not use in new code. +BrokenExecutor = BrokenProcessPool + + +class ShutdownExecutorError(RuntimeError): + + """ + Raised when a ProcessPoolExecutor is shutdown while a future was in the + running or pending state. + """ + + +class ProcessPoolExecutor(Executor): + + _at_exit = None + + def __init__( + self, + max_workers=None, + job_reducers=None, + result_reducers=None, + timeout=None, + context=None, + initializer=None, + initargs=(), + env=None, + ): + """Initializes a new ProcessPoolExecutor instance. + + Args: + max_workers: int, optional (default: cpu_count()) + The maximum number of processes that can be used to execute the + given calls. If None or not given then as many worker processes + will be created as the number of CPUs the current process + can use. + job_reducers, result_reducers: dict(type: reducer_func) + Custom reducer for pickling the jobs and the results from the + Executor. If only `job_reducers` is provided, `result_reducer` + will use the same reducers + timeout: int, optional (default: None) + Idle workers exit after timeout seconds. If a new job is + submitted after the timeout, the executor will start enough + new Python processes to make sure the pool of workers is full. + context: A multiprocessing context to launch the workers. This + object should provide SimpleQueue, Queue and Process. + initializer: An callable used to initialize worker processes. + initargs: A tuple of arguments to pass to the initializer. + env: A dict of environment variable to overwrite in the child + process. The environment variables are set before any module is + loaded. Note that this only works with the loky context. + """ + _check_system_limits() + + if max_workers is None: + self._max_workers = cpu_count() + else: + if max_workers <= 0: + raise ValueError("max_workers must be greater than 0") + self._max_workers = max_workers + + if ( + sys.platform == "win32" + and self._max_workers > _MAX_WINDOWS_WORKERS + ): + warnings.warn( + f"On Windows, max_workers cannot exceed {_MAX_WINDOWS_WORKERS} " + "due to limitations of the operating system." + ) + self._max_workers = _MAX_WINDOWS_WORKERS + + if context is None: + context = get_context() + self._context = context + self._env = env + + self._initializer, self._initargs = _prepare_initializer( + initializer, initargs + ) + _check_max_depth(self._context) + + if result_reducers is None: + result_reducers = job_reducers + + # Timeout + self._timeout = timeout + + # Management thread + self._executor_manager_thread = None + + # Map of pids to processes + self._processes = {} + + # Internal variables of the ProcessPoolExecutor + self._processes = {} + self._queue_count = 0 + self._pending_work_items = {} + self._running_work_items = [] + self._work_ids = queue.Queue() + self._processes_management_lock = self._context.Lock() + self._executor_manager_thread = None + self._shutdown_lock = threading.Lock() + + # _ThreadWakeup is a communication channel used to interrupt the wait + # of the main loop of executor_manager_thread from another thread (e.g. + # when calling executor.submit or executor.shutdown). We do not use the + # _result_queue to send wakeup signals to the executor_manager_thread + # as it could result in a deadlock if a worker process dies with the + # _result_queue write lock still acquired. + # + # _shutdown_lock must be locked to access _ThreadWakeup.wakeup. + self._executor_manager_thread_wakeup = _ThreadWakeup() + + # Flag to hold the state of the Executor. This permits to introspect + # the Executor state even once it has been garbage collected. + self._flags = _ExecutorFlags(self._shutdown_lock) + + # Finally setup the queues for interprocess communication + self._setup_queues(job_reducers, result_reducers) + + mp.util.debug("ProcessPoolExecutor is setup") + + def _setup_queues(self, job_reducers, result_reducers, queue_size=None): + # Make the call queue slightly larger than the number of processes to + # prevent the worker processes from idling. But don't make it too big + # because futures in the call queue cannot be cancelled. + if queue_size is None: + queue_size = 2 * self._max_workers + EXTRA_QUEUED_CALLS + self._call_queue = _SafeQueue( + max_size=queue_size, + pending_work_items=self._pending_work_items, + running_work_items=self._running_work_items, + thread_wakeup=self._executor_manager_thread_wakeup, + reducers=job_reducers, + ctx=self._context, + ) + # Killed worker processes can produce spurious "broken pipe" + # tracebacks in the queue's own worker thread. But we detect killed + # processes anyway, so silence the tracebacks. + self._call_queue._ignore_epipe = True + + self._result_queue = SimpleQueue( + reducers=result_reducers, ctx=self._context + ) + + def _start_executor_manager_thread(self): + if self._executor_manager_thread is None: + mp.util.debug("_start_executor_manager_thread called") + + # Start the processes so that their sentinels are known. + self._executor_manager_thread = _ExecutorManagerThread(self) + self._executor_manager_thread.start() + + # register this executor in a mechanism that ensures it will wakeup + # when the interpreter is exiting. + _threads_wakeups[self._executor_manager_thread] = ( + self._shutdown_lock, + self._executor_manager_thread_wakeup, + ) + + global process_pool_executor_at_exit + if process_pool_executor_at_exit is None: + # Ensure that the _python_exit function will be called before + # the multiprocessing.Queue._close finalizers which have an + # exitpriority of 10. + + if sys.version_info < (3, 9): + process_pool_executor_at_exit = mp.util.Finalize( + None, _python_exit, exitpriority=20 + ) + else: + process_pool_executor_at_exit = threading._register_atexit( + _python_exit + ) + + def _adjust_process_count(self): + while len(self._processes) < self._max_workers: + worker_exit_lock = self._context.BoundedSemaphore(1) + args = ( + self._call_queue, + self._result_queue, + self._initializer, + self._initargs, + self._processes_management_lock, + self._timeout, + worker_exit_lock, + _CURRENT_DEPTH + 1, + ) + worker_exit_lock.acquire() + try: + # Try to spawn the process with some environment variable to + # overwrite but it only works with the loky context for now. + p = self._context.Process( + target=_process_worker, args=args, env=self._env + ) + except TypeError: + p = self._context.Process(target=_process_worker, args=args) + p._worker_exit_lock = worker_exit_lock + p.start() + self._processes[p.pid] = p + mp.util.debug( + f"Adjusted process count to {self._max_workers}: " + f"{[(p.name, pid) for pid, p in self._processes.items()]}" + ) + + def _ensure_executor_running(self): + """ensures all workers and management thread are running""" + with self._processes_management_lock: + if len(self._processes) != self._max_workers: + self._adjust_process_count() + self._start_executor_manager_thread() + + def submit(self, fn, *args, **kwargs): + with self._flags.shutdown_lock: + if self._flags.broken is not None: + raise self._flags.broken + if self._flags.shutdown: + raise ShutdownExecutorError( + "cannot schedule new futures after shutdown" + ) + + # Cannot submit a new calls once the interpreter is shutting down. + # This check avoids spawning new processes at exit. + if _global_shutdown: + raise RuntimeError( + "cannot schedule new futures after " "interpreter shutdown" + ) + + f = Future() + w = _WorkItem(f, fn, args, kwargs) + + self._pending_work_items[self._queue_count] = w + self._work_ids.put(self._queue_count) + self._queue_count += 1 + # Wake up queue management thread + self._executor_manager_thread_wakeup.wakeup() + + self._ensure_executor_running() + return f + + submit.__doc__ = Executor.submit.__doc__ + + def map(self, fn, *iterables, **kwargs): + """Returns an iterator equivalent to map(fn, iter). + + Args: + fn: A callable that will take as many arguments as there are + passed iterables. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + chunksize: If greater than one, the iterables will be chopped into + chunks of size chunksize and submitted to the process pool. + If set to one, the items in the list will be sent one at a + time. + + Returns: + An iterator equivalent to: map(func, *iterables) but the calls may + be evaluated out-of-order. + + Raises: + TimeoutError: If the entire result iterator could not be generated + before the given timeout. + Exception: If fn(*args) raises for any values. + """ + timeout = kwargs.get("timeout", None) + chunksize = kwargs.get("chunksize", 1) + if chunksize < 1: + raise ValueError("chunksize must be >= 1.") + + results = super().map( + partial(_process_chunk, fn), + _get_chunks(chunksize, *iterables), + timeout=timeout, + ) + return _chain_from_iterable_of_lists(results) + + def shutdown(self, wait=True, kill_workers=False): + mp.util.debug(f"shutting down executor {self}") + + self._flags.flag_as_shutting_down(kill_workers) + executor_manager_thread = self._executor_manager_thread + executor_manager_thread_wakeup = self._executor_manager_thread_wakeup + + if executor_manager_thread_wakeup is not None: + # Wake up queue management thread + with self._shutdown_lock: + self._executor_manager_thread_wakeup.wakeup() + + if executor_manager_thread is not None and wait: + # This locks avoids concurrent join if the interpreter + # is shutting down. + with _global_shutdown_lock: + executor_manager_thread.join() + _threads_wakeups.pop(executor_manager_thread, None) + + # To reduce the risk of opening too many files, remove references to + # objects that use file descriptors. + self._executor_manager_thread = None + self._executor_manager_thread_wakeup = None + self._call_queue = None + self._result_queue = None + self._processes_management_lock = None + + shutdown.__doc__ = Executor.shutdown.__doc__ diff --git a/testbed/joblib__joblib/joblib/externals/loky/reusable_executor.py b/testbed/joblib__joblib/joblib/externals/loky/reusable_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..ad016fd389762a1c458200ffe7b310239da3a3f3 --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/loky/reusable_executor.py @@ -0,0 +1,285 @@ +############################################################################### +# Reusable ProcessPoolExecutor +# +# author: Thomas Moreau and Olivier Grisel +# +import time +import warnings +import threading +import multiprocessing as mp + +from .process_executor import ProcessPoolExecutor, EXTRA_QUEUED_CALLS +from .backend.context import cpu_count +from .backend import get_context + +__all__ = ["get_reusable_executor"] + +# Singleton executor and id management +_executor_lock = threading.RLock() +_next_executor_id = 0 +_executor = None +_executor_kwargs = None + + +def _get_next_executor_id(): + """Ensure that each successive executor instance has a unique, monotonic id. + + The purpose of this monotonic id is to help debug and test automated + instance creation. + """ + global _next_executor_id + with _executor_lock: + executor_id = _next_executor_id + _next_executor_id += 1 + return executor_id + + +def get_reusable_executor( + max_workers=None, + context=None, + timeout=10, + kill_workers=False, + reuse="auto", + job_reducers=None, + result_reducers=None, + initializer=None, + initargs=(), + env=None, +): + """Return the current ReusableExectutor instance. + + Start a new instance if it has not been started already or if the previous + instance was left in a broken state. + + If the previous instance does not have the requested number of workers, the + executor is dynamically resized to adjust the number of workers prior to + returning. + + Reusing a singleton instance spares the overhead of starting new worker + processes and importing common python packages each time. + + ``max_workers`` controls the maximum number of tasks that can be running in + parallel in worker processes. By default this is set to the number of + CPUs on the host. + + Setting ``timeout`` (in seconds) makes idle workers automatically shutdown + so as to release system resources. New workers are respawn upon submission + of new tasks so that ``max_workers`` are available to accept the newly + submitted tasks. Setting ``timeout`` to around 100 times the time required + to spawn new processes and import packages in them (on the order of 100ms) + ensures that the overhead of spawning workers is negligible. + + Setting ``kill_workers=True`` makes it possible to forcibly interrupt + previously spawned jobs to get a new instance of the reusable executor + with new constructor argument values. + + The ``job_reducers`` and ``result_reducers`` are used to customize the + pickling of tasks and results send to the executor. + + When provided, the ``initializer`` is run first in newly spawned + processes with argument ``initargs``. + + The environment variable in the child process are a copy of the values in + the main process. One can provide a dict ``{ENV: VAL}`` where ``ENV`` and + ``VAL`` are string literals to overwrite the environment variable ``ENV`` + in the child processes to value ``VAL``. The environment variables are set + in the children before any module is loaded. This only works with the + ``loky`` context. + """ + _executor, _ = _ReusablePoolExecutor.get_reusable_executor( + max_workers=max_workers, + context=context, + timeout=timeout, + kill_workers=kill_workers, + reuse=reuse, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, + initargs=initargs, + env=env, + ) + return _executor + + +class _ReusablePoolExecutor(ProcessPoolExecutor): + def __init__( + self, + submit_resize_lock, + max_workers=None, + context=None, + timeout=None, + executor_id=0, + job_reducers=None, + result_reducers=None, + initializer=None, + initargs=(), + env=None, + ): + super().__init__( + max_workers=max_workers, + context=context, + timeout=timeout, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, + initargs=initargs, + env=env, + ) + self.executor_id = executor_id + self._submit_resize_lock = submit_resize_lock + + @classmethod + def get_reusable_executor( + cls, + max_workers=None, + context=None, + timeout=10, + kill_workers=False, + reuse="auto", + job_reducers=None, + result_reducers=None, + initializer=None, + initargs=(), + env=None, + ): + with _executor_lock: + global _executor, _executor_kwargs + executor = _executor + + if max_workers is None: + if reuse is True and executor is not None: + max_workers = executor._max_workers + else: + max_workers = cpu_count() + elif max_workers <= 0: + raise ValueError( + f"max_workers must be greater than 0, got {max_workers}." + ) + + if isinstance(context, str): + context = get_context(context) + if context is not None and context.get_start_method() == "fork": + raise ValueError( + "Cannot use reusable executor with the 'fork' context" + ) + + kwargs = dict( + context=context, + timeout=timeout, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, + initargs=initargs, + env=env, + ) + if executor is None: + is_reused = False + mp.util.debug( + f"Create a executor with max_workers={max_workers}." + ) + executor_id = _get_next_executor_id() + _executor_kwargs = kwargs + _executor = executor = cls( + _executor_lock, + max_workers=max_workers, + executor_id=executor_id, + **kwargs, + ) + else: + if reuse == "auto": + reuse = kwargs == _executor_kwargs + if ( + executor._flags.broken + or executor._flags.shutdown + or not reuse + ): + if executor._flags.broken: + reason = "broken" + elif executor._flags.shutdown: + reason = "shutdown" + else: + reason = "arguments have changed" + mp.util.debug( + "Creating a new executor with max_workers=" + f"{max_workers} as the previous instance cannot be " + f"reused ({reason})." + ) + executor.shutdown(wait=True, kill_workers=kill_workers) + _executor = executor = _executor_kwargs = None + # Recursive call to build a new instance + return cls.get_reusable_executor( + max_workers=max_workers, **kwargs + ) + else: + mp.util.debug( + "Reusing existing executor with " + f"max_workers={executor._max_workers}." + ) + is_reused = True + executor._resize(max_workers) + + return executor, is_reused + + def submit(self, fn, *args, **kwargs): + with self._submit_resize_lock: + return super().submit(fn, *args, **kwargs) + + def _resize(self, max_workers): + with self._submit_resize_lock: + if max_workers is None: + raise ValueError("Trying to resize with max_workers=None") + elif max_workers == self._max_workers: + return + + if self._executor_manager_thread is None: + # If the executor_manager_thread has not been started + # then no processes have been spawned and we can just + # update _max_workers and return + self._max_workers = max_workers + return + + self._wait_job_completion() + + # Some process might have returned due to timeout so check how many + # children are still alive. Use the _process_management_lock to + # ensure that no process are spawned or timeout during the resize. + with self._processes_management_lock: + processes = list(self._processes.values()) + nb_children_alive = sum(p.is_alive() for p in processes) + self._max_workers = max_workers + for _ in range(max_workers, nb_children_alive): + self._call_queue.put(None) + while ( + len(self._processes) > max_workers and not self._flags.broken + ): + time.sleep(1e-3) + + self._adjust_process_count() + processes = list(self._processes.values()) + while not all(p.is_alive() for p in processes): + time.sleep(1e-3) + + def _wait_job_completion(self): + """Wait for the cache to be empty before resizing the pool.""" + # Issue a warning to the user about the bad effect of this usage. + if self._pending_work_items: + warnings.warn( + "Trying to resize an executor with running jobs: " + "waiting for jobs completion before resizing.", + UserWarning, + ) + mp.util.debug( + f"Executor {self.executor_id} waiting for jobs completion " + "before resizing" + ) + # Wait for the completion of the jobs + while self._pending_work_items: + time.sleep(1e-3) + + def _setup_queues(self, job_reducers, result_reducers): + # As this executor can be resized, use a large queue size to avoid + # underestimating capacity and introducing overhead + queue_size = 2 * cpu_count() + EXTRA_QUEUED_CALLS + super()._setup_queues( + job_reducers, result_reducers, queue_size=queue_size + ) diff --git a/testbed/joblib__joblib/joblib/externals/vendor_cloudpickle.sh b/testbed/joblib__joblib/joblib/externals/vendor_cloudpickle.sh new file mode 100644 index 0000000000000000000000000000000000000000..74ec9ca94c0ec9e7790ff62014c1b0d36491966a --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/vendor_cloudpickle.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Script to do a local install of cloudpickle +export LC_ALL=C +INSTALL_FOLDER=tmp/cloudpickle_install +rm -rf cloudpickle $INSTALL_FOLDER 2> /dev/null +if [ -z "$1" ] +then + # Grab the latest stable release from PyPI + CLOUDPICKLE=cloudpickle +else + CLOUDPICKLE=$1 +fi +pip install $CLOUDPICKLE --target $INSTALL_FOLDER +cp -r $INSTALL_FOLDER/cloudpickle . +rm -rf $INSTALL_FOLDER + +# Needed to rewrite the doctests +# Note: BSD sed -i needs an argument unders OSX +# so first renaming to .bak and then deleting backup files +sed -i.bak "s/from cloudpickle.cloudpickle/from .cloudpickle/" cloudpickle/__init__.py +find cloudpickle -name "*.bak" | xargs rm + +rm -r tmp diff --git a/testbed/joblib__joblib/joblib/externals/vendor_loky.sh b/testbed/joblib__joblib/joblib/externals/vendor_loky.sh new file mode 100644 index 0000000000000000000000000000000000000000..da57b52681209986bf8e9a0c2e98a214de51f19f --- /dev/null +++ b/testbed/joblib__joblib/joblib/externals/vendor_loky.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Script to do a local install of loky +set +x +export LC_ALL=C +INSTALL_FOLDER=tmp/loky_install +rm -rf loky $INSTALL_FOLDER 2> /dev/null +if [ -z "$1" ] +then + # Grab the latest stable release from PyPI + LOKY=loky +else + LOKY=$1 +fi +pip install --no-cache $LOKY --target $INSTALL_FOLDER +cp -r $INSTALL_FOLDER/loky . +rm -rf $INSTALL_FOLDER + +# Needed to rewrite the doctests +# Note: BSD sed -i needs an argument unders OSX +# so first renaming to .bak and then deleting backup files +find loky -name "*.py" | xargs sed -i.bak "s/from loky/from joblib.externals.loky/" + +for f in $(git grep -l "cloudpickle" loky); do + echo $f; + sed -i.bak 's/import cloudpickle/from joblib.externals import cloudpickle/' $f + sed -i.bak 's/from cloudpickle import/from joblib.externals.cloudpickle import/' $f +done + +sed -i.bak "s/loky.backend.popen_loky/joblib.externals.loky.backend.popen_loky/" loky/backend/popen_loky_posix.py + +find loky -name "*.bak" | xargs rm diff --git a/testbed/joblib__joblib/joblib/func_inspect.py b/testbed/joblib__joblib/joblib/func_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8094614b90abed5804723908ddf5eb109901b1 --- /dev/null +++ b/testbed/joblib__joblib/joblib/func_inspect.py @@ -0,0 +1,369 @@ +""" +My own variation on function-specific inspect-like features. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import inspect +import warnings +import re +import os +import collections + +from itertools import islice +from tokenize import open as open_py_source + +from .logger import pformat + +full_argspec_fields = ('args varargs varkw defaults kwonlyargs ' + 'kwonlydefaults annotations') +full_argspec_type = collections.namedtuple('FullArgSpec', full_argspec_fields) + + +def get_func_code(func): + """ Attempts to retrieve a reliable function code hash. + + The reason we don't use inspect.getsource is that it caches the + source, whereas we want this to be modified on the fly when the + function is modified. + + Returns + ------- + func_code: string + The function code + source_file: string + The path to the file in which the function is defined. + first_line: int + The first line of the code in the source file. + + Notes + ------ + This function does a bit more magic than inspect, and is thus + more robust. + """ + source_file = None + try: + code = func.__code__ + source_file = code.co_filename + if not os.path.exists(source_file): + # Use inspect for lambda functions and functions defined in an + # interactive shell, or in doctests + source_code = ''.join(inspect.getsourcelines(func)[0]) + line_no = 1 + if source_file.startswith('', source_file).groups() + line_no = int(line_no) + source_file = '' % source_file + return source_code, source_file, line_no + # Try to retrieve the source code. + with open_py_source(source_file) as source_file_obj: + first_line = code.co_firstlineno + # All the lines after the function definition: + source_lines = list(islice(source_file_obj, first_line - 1, None)) + return ''.join(inspect.getblock(source_lines)), source_file, first_line + except: # noqa: E722 + # If the source code fails, we use the hash. This is fragile and + # might change from one session to another. + if hasattr(func, '__code__'): + # Python 3.X + return str(func.__code__.__hash__()), source_file, -1 + else: + # Weird objects like numpy ufunc don't have __code__ + # This is fragile, as quite often the id of the object is + # in the repr, so it might not persist across sessions, + # however it will work for ufuncs. + return repr(func), source_file, -1 + + +def _clean_win_chars(string): + """Windows cannot encode some characters in filename.""" + import urllib + if hasattr(urllib, 'quote'): + quote = urllib.quote + else: + # In Python 3, quote is elsewhere + import urllib.parse + quote = urllib.parse.quote + for char in ('<', '>', '!', ':', '\\'): + string = string.replace(char, quote(char)) + return string + + +def get_func_name(func, resolv_alias=True, win_characters=True): + """ Return the function import path (as a list of module names), and + a name for the function. + + Parameters + ---------- + func: callable + The func to inspect + resolv_alias: boolean, optional + If true, possible local aliases are indicated. + win_characters: boolean, optional + If true, substitute special characters using urllib.quote + This is useful in Windows, as it cannot encode some filenames + """ + if hasattr(func, '__module__'): + module = func.__module__ + else: + try: + module = inspect.getmodule(func) + except TypeError: + if hasattr(func, '__class__'): + module = func.__class__.__module__ + else: + module = 'unknown' + if module is None: + # Happens in doctests, eg + module = '' + if module == '__main__': + try: + filename = os.path.abspath(inspect.getsourcefile(func)) + except: # noqa: E722 + filename = None + if filename is not None: + # mangling of full path to filename + parts = filename.split(os.sep) + if parts[-1].startswith(', where: + # - N is the cell number where the function was defined + # - XYZ is a hash representing the function's code (and name). + # It will be consistent across sessions and kernel restarts, + # and will change if the function's code/name changes + # We remove N so that cache is properly hit if the cell where + # the func is defined is re-exectuted. + # The XYZ hash should avoid collisions between functions with + # the same name, both within the same notebook but also across + # notebooks + splitted = parts[-1].split('-') + parts[-1] = '-'.join(splitted[:2] + splitted[3:]) + elif len(parts) > 2 and parts[-2].startswith('ipykernel_'): + # In a notebook session (ipykernel). Filename seems to be 'xyz' + # of above. parts[-2] has the structure ipykernel_XXXXXX where + # XXXXXX is a six-digit number identifying the current run (?). + # If we split it off, the function again has the same + # identifier across runs. + parts[-2] = 'ipykernel' + filename = '-'.join(parts) + if filename.endswith('.py'): + filename = filename[:-3] + module = module + '-' + filename + module = module.split('.') + if hasattr(func, 'func_name'): + name = func.func_name + elif hasattr(func, '__name__'): + name = func.__name__ + else: + name = 'unknown' + # Hack to detect functions not defined at the module-level + if resolv_alias: + # TODO: Maybe add a warning here? + if hasattr(func, 'func_globals') and name in func.func_globals: + if not func.func_globals[name] is func: + name = '%s-alias' % name + if hasattr(func, '__qualname__') and func.__qualname__ != name: + # Extend the module name in case of nested functions to avoid + # (module, name) collisions + module.extend(func.__qualname__.split(".")[:-1]) + if inspect.ismethod(func): + # We need to add the name of the class + if hasattr(func, 'im_class'): + klass = func.im_class + module.append(klass.__name__) + if os.name == 'nt' and win_characters: + # Windows can't encode certain characters in filenames + name = _clean_win_chars(name) + module = [_clean_win_chars(s) for s in module] + return module, name + + +def _signature_str(function_name, arg_sig): + """Helper function to output a function signature""" + return '{}{}'.format(function_name, arg_sig) + + +def _function_called_str(function_name, args, kwargs): + """Helper function to output a function call""" + template_str = '{0}({1}, {2})' + + args_str = repr(args)[1:-1] + kwargs_str = ', '.join('%s=%s' % (k, v) + for k, v in kwargs.items()) + return template_str.format(function_name, args_str, + kwargs_str) + + +def filter_args(func, ignore_lst, args=(), kwargs=dict()): + """ Filters the given args and kwargs using a list of arguments to + ignore, and a function specification. + + Parameters + ---------- + func: callable + Function giving the argument specification + ignore_lst: list of strings + List of arguments to ignore (either a name of an argument + in the function spec, or '*', or '**') + *args: list + Positional arguments passed to the function. + **kwargs: dict + Keyword arguments passed to the function + + Returns + ------- + filtered_args: list + List of filtered positional and keyword arguments. + """ + args = list(args) + if isinstance(ignore_lst, str): + # Catch a common mistake + raise ValueError( + 'ignore_lst must be a list of parameters to ignore ' + '%s (type %s) was given' % (ignore_lst, type(ignore_lst))) + # Special case for functools.partial objects + if (not inspect.ismethod(func) and not inspect.isfunction(func)): + if ignore_lst: + warnings.warn('Cannot inspect object %s, ignore list will ' + 'not work.' % func, stacklevel=2) + return {'*': args, '**': kwargs} + arg_sig = inspect.signature(func) + arg_names = [] + arg_defaults = [] + arg_kwonlyargs = [] + arg_varargs = None + arg_varkw = None + for param in arg_sig.parameters.values(): + if param.kind is param.POSITIONAL_OR_KEYWORD: + arg_names.append(param.name) + elif param.kind is param.KEYWORD_ONLY: + arg_names.append(param.name) + arg_kwonlyargs.append(param.name) + elif param.kind is param.VAR_POSITIONAL: + arg_varargs = param.name + elif param.kind is param.VAR_KEYWORD: + arg_varkw = param.name + if param.default is not param.empty: + arg_defaults.append(param.default) + if inspect.ismethod(func): + # First argument is 'self', it has been removed by Python + # we need to add it back: + args = [func.__self__, ] + args + # func is an instance method, inspect.signature(func) does not + # include self, we need to fetch it from the class method, i.e + # func.__func__ + class_method_sig = inspect.signature(func.__func__) + self_name = next(iter(class_method_sig.parameters)) + arg_names = [self_name] + arg_names + # XXX: Maybe I need an inspect.isbuiltin to detect C-level methods, such + # as on ndarrays. + + _, name = get_func_name(func, resolv_alias=False) + arg_dict = dict() + arg_position = -1 + for arg_position, arg_name in enumerate(arg_names): + if arg_position < len(args): + # Positional argument or keyword argument given as positional + if arg_name not in arg_kwonlyargs: + arg_dict[arg_name] = args[arg_position] + else: + raise ValueError( + "Keyword-only parameter '%s' was passed as " + 'positional parameter for %s:\n' + ' %s was called.' + % (arg_name, + _signature_str(name, arg_sig), + _function_called_str(name, args, kwargs)) + ) + + else: + position = arg_position - len(arg_names) + if arg_name in kwargs: + arg_dict[arg_name] = kwargs[arg_name] + else: + try: + arg_dict[arg_name] = arg_defaults[position] + except (IndexError, KeyError) as e: + # Missing argument + raise ValueError( + 'Wrong number of arguments for %s:\n' + ' %s was called.' + % (_signature_str(name, arg_sig), + _function_called_str(name, args, kwargs)) + ) from e + + varkwargs = dict() + for arg_name, arg_value in sorted(kwargs.items()): + if arg_name in arg_dict: + arg_dict[arg_name] = arg_value + elif arg_varkw is not None: + varkwargs[arg_name] = arg_value + else: + raise TypeError("Ignore list for %s() contains an unexpected " + "keyword argument '%s'" % (name, arg_name)) + + if arg_varkw is not None: + arg_dict['**'] = varkwargs + if arg_varargs is not None: + varargs = args[arg_position + 1:] + arg_dict['*'] = varargs + + # Now remove the arguments to be ignored + for item in ignore_lst: + if item in arg_dict: + arg_dict.pop(item) + else: + raise ValueError("Ignore list: argument '%s' is not defined for " + "function %s" + % (item, + _signature_str(name, arg_sig)) + ) + # XXX: Return a sorted list of pairs? + return arg_dict + + +def _format_arg(arg): + formatted_arg = pformat(arg, indent=2) + if len(formatted_arg) > 1500: + formatted_arg = '%s...' % formatted_arg[:700] + return formatted_arg + + +def format_signature(func, *args, **kwargs): + # XXX: Should this use inspect.formatargvalues/formatargspec? + module, name = get_func_name(func) + module = [m for m in module if m] + if module: + module.append(name) + module_path = '.'.join(module) + else: + module_path = name + arg_str = list() + previous_length = 0 + for arg in args: + formatted_arg = _format_arg(arg) + if previous_length > 80: + formatted_arg = '\n%s' % formatted_arg + previous_length = len(formatted_arg) + arg_str.append(formatted_arg) + arg_str.extend(['%s=%s' % (v, _format_arg(i)) for v, i in kwargs.items()]) + arg_str = ', '.join(arg_str) + + signature = '%s(%s)' % (name, arg_str) + return module_path, signature + + +def format_call(func, args, kwargs, object_name="Memory"): + """ Returns a nicely formatted statement displaying the function + call with the given arguments. + """ + path, signature = format_signature(func, *args, **kwargs) + msg = '%s\n[%s] Calling %s...\n%s' % (80 * '_', object_name, + path, signature) + return msg + # XXX: Not using logging framework + # self.debug(msg) diff --git a/testbed/joblib__joblib/joblib/hashing.py b/testbed/joblib__joblib/joblib/hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..6c081f06997ae3b6c18fc76b286ef95e008f23cc --- /dev/null +++ b/testbed/joblib__joblib/joblib/hashing.py @@ -0,0 +1,265 @@ +""" +Fast cryptographic hash of Python objects, with a special case for fast +hashing of numpy arrays. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import pickle +import hashlib +import sys +import types +import struct +import io +import decimal + + +Pickler = pickle._Pickler + + +class _ConsistentSet(object): + """ Class used to ensure the hash of Sets is preserved + whatever the order of its items. + """ + def __init__(self, set_sequence): + # Forces order of elements in set to ensure consistent hash. + try: + # Trying first to order the set assuming the type of elements is + # consistent and orderable. + # This fails on python 3 when elements are unorderable + # but we keep it in a try as it's faster. + self._sequence = sorted(set_sequence) + except (TypeError, decimal.InvalidOperation): + # If elements are unorderable, sorting them using their hash. + # This is slower but works in any case. + self._sequence = sorted((hash(e) for e in set_sequence)) + + +class _MyHash(object): + """ Class used to hash objects that won't normally pickle """ + + def __init__(self, *args): + self.args = args + + +class Hasher(Pickler): + """ A subclass of pickler, to do cryptographic hashing, rather than + pickling. + """ + + def __init__(self, hash_name='md5'): + self.stream = io.BytesIO() + # By default we want a pickle protocol that only changes with + # the major python version and not the minor one + protocol = 3 + Pickler.__init__(self, self.stream, protocol=protocol) + # Initialise the hash obj + self._hash = hashlib.new(hash_name) + + def hash(self, obj, return_digest=True): + try: + self.dump(obj) + except pickle.PicklingError as e: + e.args += ('PicklingError while hashing %r: %r' % (obj, e),) + raise + dumps = self.stream.getvalue() + self._hash.update(dumps) + if return_digest: + return self._hash.hexdigest() + + def save(self, obj): + if isinstance(obj, (types.MethodType, type({}.pop))): + # the Pickler cannot pickle instance methods; here we decompose + # them into components that make them uniquely identifiable + if hasattr(obj, '__func__'): + func_name = obj.__func__.__name__ + else: + func_name = obj.__name__ + inst = obj.__self__ + if type(inst) is type(pickle): + obj = _MyHash(func_name, inst.__name__) + elif inst is None: + # type(None) or type(module) do not pickle + obj = _MyHash(func_name, inst) + else: + cls = obj.__self__.__class__ + obj = _MyHash(func_name, inst, cls) + Pickler.save(self, obj) + + def memoize(self, obj): + # We want hashing to be sensitive to value instead of reference. + # For example we want ['aa', 'aa'] and ['aa', 'aaZ'[:2]] + # to hash to the same value and that's why we disable memoization + # for strings + if isinstance(obj, (bytes, str)): + return + Pickler.memoize(self, obj) + + # The dispatch table of the pickler is not accessible in Python + # 3, as these lines are only bugware for IPython, we skip them. + def save_global(self, obj, name=None, pack=struct.pack): + # We have to override this method in order to deal with objects + # defined interactively in IPython that are not injected in + # __main__ + kwargs = dict(name=name, pack=pack) + del kwargs['pack'] + try: + Pickler.save_global(self, obj, **kwargs) + except pickle.PicklingError: + Pickler.save_global(self, obj, **kwargs) + module = getattr(obj, "__module__", None) + if module == '__main__': + my_name = name + if my_name is None: + my_name = obj.__name__ + mod = sys.modules[module] + if not hasattr(mod, my_name): + # IPython doesn't inject the variables define + # interactively in __main__ + setattr(mod, my_name, obj) + + dispatch = Pickler.dispatch.copy() + # builtin + dispatch[type(len)] = save_global + # type + dispatch[type(object)] = save_global + # classobj + dispatch[type(Pickler)] = save_global + # function + dispatch[type(pickle.dump)] = save_global + + def _batch_setitems(self, items): + # forces order of keys in dict to ensure consistent hash. + try: + # Trying first to compare dict assuming the type of keys is + # consistent and orderable. + # This fails on python 3 when keys are unorderable + # but we keep it in a try as it's faster. + Pickler._batch_setitems(self, iter(sorted(items))) + except TypeError: + # If keys are unorderable, sorting them using their hash. This is + # slower but works in any case. + Pickler._batch_setitems(self, iter(sorted((hash(k), v) + for k, v in items))) + + def save_set(self, set_items): + # forces order of items in Set to ensure consistent hash + Pickler.save(self, _ConsistentSet(set_items)) + + dispatch[type(set())] = save_set + + +class NumpyHasher(Hasher): + """ Special case the hasher for when numpy is loaded. + """ + + def __init__(self, hash_name='md5', coerce_mmap=False): + """ + Parameters + ---------- + hash_name: string + The hash algorithm to be used + coerce_mmap: boolean + Make no difference between np.memmap and np.ndarray + objects. + """ + self.coerce_mmap = coerce_mmap + Hasher.__init__(self, hash_name=hash_name) + # delayed import of numpy, to avoid tight coupling + import numpy as np + self.np = np + if hasattr(np, 'getbuffer'): + self._getbuffer = np.getbuffer + else: + self._getbuffer = memoryview + + def save(self, obj): + """ Subclass the save method, to hash ndarray subclass, rather + than pickling them. Off course, this is a total abuse of + the Pickler class. + """ + if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject: + # Compute a hash of the object + # The update function of the hash requires a c_contiguous buffer. + if obj.shape == (): + # 0d arrays need to be flattened because viewing them as bytes + # raises a ValueError exception. + obj_c_contiguous = obj.flatten() + elif obj.flags.c_contiguous: + obj_c_contiguous = obj + elif obj.flags.f_contiguous: + obj_c_contiguous = obj.T + else: + # Cater for non-single-segment arrays: this creates a + # copy, and thus alleviates this issue. + # XXX: There might be a more efficient way of doing this + obj_c_contiguous = obj.flatten() + + # memoryview is not supported for some dtypes, e.g. datetime64, see + # https://github.com/numpy/numpy/issues/4983. The + # workaround is to view the array as bytes before + # taking the memoryview. + self._hash.update( + self._getbuffer(obj_c_contiguous.view(self.np.uint8))) + + # We store the class, to be able to distinguish between + # Objects with the same binary content, but different + # classes. + if self.coerce_mmap and isinstance(obj, self.np.memmap): + # We don't make the difference between memmap and + # normal ndarrays, to be able to reload previously + # computed results with memmap. + klass = self.np.ndarray + else: + klass = obj.__class__ + # We also return the dtype and the shape, to distinguish + # different views on the same data with different dtypes. + + # The object will be pickled by the pickler hashed at the end. + obj = (klass, ('HASHED', obj.dtype, obj.shape, obj.strides)) + elif isinstance(obj, self.np.dtype): + # numpy.dtype consistent hashing is tricky to get right. This comes + # from the fact that atomic np.dtype objects are interned: + # ``np.dtype('f4') is np.dtype('f4')``. The situation is + # complicated by the fact that this interning does not resist a + # simple pickle.load/dump roundtrip: + # ``pickle.loads(pickle.dumps(np.dtype('f4'))) is not + # np.dtype('f4') Because pickle relies on memoization during + # pickling, it is easy to + # produce different hashes for seemingly identical objects, such as + # ``[np.dtype('f4'), np.dtype('f4')]`` + # and ``[np.dtype('f4'), pickle.loads(pickle.dumps('f4'))]``. + # To prevent memoization from interfering with hashing, we isolate + # the serialization (and thus the pickle memoization) of each dtype + # using each time a different ``pickle.dumps`` call unrelated to + # the current Hasher instance. + self._hash.update("_HASHED_DTYPE".encode('utf-8')) + self._hash.update(pickle.dumps(obj)) + return + Hasher.save(self, obj) + + +def hash(obj, hash_name='md5', coerce_mmap=False): + """ Quick calculation of a hash to identify uniquely Python objects + containing numpy arrays. + + Parameters + ---------- + hash_name: 'md5' or 'sha1' + Hashing algorithm used. sha1 is supposedly safer, but md5 is + faster. + coerce_mmap: boolean + Make no difference between np.memmap and np.ndarray + """ + valid_hash_names = ('md5', 'sha1') + if hash_name not in valid_hash_names: + raise ValueError("Valid options for 'hash_name' are {}. " + "Got hash_name={!r} instead." + .format(valid_hash_names, hash_name)) + if 'numpy' in sys.modules: + hasher = NumpyHasher(hash_name=hash_name, coerce_mmap=coerce_mmap) + else: + hasher = Hasher(hash_name=hash_name) + return hasher.hash(obj) diff --git a/testbed/joblib__joblib/joblib/logger.py b/testbed/joblib__joblib/joblib/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..cf9d258011f3c581334a93ef3ccdac7dfb19b25e --- /dev/null +++ b/testbed/joblib__joblib/joblib/logger.py @@ -0,0 +1,162 @@ +""" +Helpers for logging. + +This module needs much love to become useful. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2008 Gael Varoquaux +# License: BSD Style, 3 clauses. + +from __future__ import print_function + +import time +import sys +import os +import shutil +import logging +import pprint + +from .disk import mkdirp + + +def _squeeze_time(t): + """Remove .1s to the time under Windows: this is the time it take to + stat files. This is needed to make results similar to timings under + Unix, for tests + """ + if sys.platform.startswith('win'): + return max(0, t - .1) + else: + return t + + +def format_time(t): + t = _squeeze_time(t) + return "%.1fs, %.1fmin" % (t, t / 60.) + + +def short_format_time(t): + t = _squeeze_time(t) + if t > 60: + return "%4.1fmin" % (t / 60.) + else: + return " %5.1fs" % (t) + + +def pformat(obj, indent=0, depth=3): + if 'numpy' in sys.modules: + import numpy as np + print_options = np.get_printoptions() + np.set_printoptions(precision=6, threshold=64, edgeitems=1) + else: + print_options = None + out = pprint.pformat(obj, depth=depth, indent=indent) + if print_options: + np.set_printoptions(**print_options) + return out + + +############################################################################### +# class `Logger` +############################################################################### +class Logger(object): + """ Base class for logging messages. + """ + + def __init__(self, depth=3, name=None): + """ + Parameters + ---------- + depth: int, optional + The depth of objects printed. + name: str, optional + The namespace to log to. If None, defaults to joblib. + """ + self.depth = depth + self._name = name if name else 'joblib' + + def warn(self, msg): + logging.getLogger(self._name).warning("[%s]: %s" % (self, msg)) + + def info(self, msg): + logging.info("[%s]: %s" % (self, msg)) + + def debug(self, msg): + # XXX: This conflicts with the debug flag used in children class + logging.getLogger(self._name).debug("[%s]: %s" % (self, msg)) + + def format(self, obj, indent=0): + """Return the formatted representation of the object.""" + return pformat(obj, indent=indent, depth=self.depth) + + +############################################################################### +# class `PrintTime` +############################################################################### +class PrintTime(object): + """ Print and log messages while keeping track of time. + """ + + def __init__(self, logfile=None, logdir=None): + if logfile is not None and logdir is not None: + raise ValueError('Cannot specify both logfile and logdir') + # XXX: Need argument docstring + self.last_time = time.time() + self.start_time = self.last_time + if logdir is not None: + logfile = os.path.join(logdir, 'joblib.log') + self.logfile = logfile + if logfile is not None: + mkdirp(os.path.dirname(logfile)) + if os.path.exists(logfile): + # Rotate the logs + for i in range(1, 9): + try: + shutil.move(logfile + '.%i' % i, + logfile + '.%i' % (i + 1)) + except: # noqa: E722 + "No reason failing here" + # Use a copy rather than a move, so that a process + # monitoring this file does not get lost. + try: + shutil.copy(logfile, logfile + '.1') + except: # noqa: E722 + "No reason failing here" + try: + with open(logfile, 'w') as logfile: + logfile.write('\nLogging joblib python script\n') + logfile.write('\n---%s---\n' % time.ctime(self.last_time)) + except: # noqa: E722 + """ Multiprocessing writing to files can create race + conditions. Rather fail silently than crash the + computation. + """ + # XXX: We actually need a debug flag to disable this + # silent failure. + + def __call__(self, msg='', total=False): + """ Print the time elapsed between the last call and the current + call, with an optional message. + """ + if not total: + time_lapse = time.time() - self.last_time + full_msg = "%s: %s" % (msg, format_time(time_lapse)) + else: + # FIXME: Too much logic duplicated + time_lapse = time.time() - self.start_time + full_msg = "%s: %.2fs, %.1f min" % (msg, time_lapse, + time_lapse / 60) + print(full_msg, file=sys.stderr) + if self.logfile is not None: + try: + with open(self.logfile, 'a') as f: + print(full_msg, file=f) + except: # noqa: E722 + """ Multiprocessing writing to files can create race + conditions. Rather fail silently than crash the + calculation. + """ + # XXX: We actually need a debug flag to disable this + # silent failure. + self.last_time = time.time() diff --git a/testbed/joblib__joblib/joblib/memory.py b/testbed/joblib__joblib/joblib/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..8171d24cb789c6ca445fdbee7af8a8ae9b494c32 --- /dev/null +++ b/testbed/joblib__joblib/joblib/memory.py @@ -0,0 +1,1199 @@ +""" +A context object for caching a function's return value each time it +is called with the same input arguments. + +""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + + +from __future__ import with_statement +import logging +import os +from textwrap import dedent +import time +import pathlib +import pydoc +import re +import functools +import traceback +import warnings +import inspect +import weakref +from datetime import timedelta + +from tokenize import open as open_py_source + +# Local imports +from . import hashing +from .func_inspect import get_func_code, get_func_name, filter_args +from .func_inspect import format_call +from .func_inspect import format_signature +from .logger import Logger, format_time, pformat +from ._store_backends import StoreBackendBase, FileSystemStoreBackend +from ._store_backends import CacheWarning # noqa + + +FIRST_LINE_TEXT = "# first line:" + +# TODO: The following object should have a data store object as a sub +# object, and the interface to persist and query should be separated in +# the data store. +# +# This would enable creating 'Memory' objects with a different logic for +# pickling that would simply span a MemorizedFunc with the same +# store (or do we want to copy it to avoid cross-talks?), for instance to +# implement HDF5 pickling. + +# TODO: Same remark for the logger, and probably use the Python logging +# mechanism. + + +def extract_first_line(func_code): + """ Extract the first line information from the function code + text if available. + """ + if func_code.startswith(FIRST_LINE_TEXT): + func_code = func_code.split('\n') + first_line = int(func_code[0][len(FIRST_LINE_TEXT):]) + func_code = '\n'.join(func_code[1:]) + else: + first_line = -1 + return func_code, first_line + + +class JobLibCollisionWarning(UserWarning): + """ Warn that there might be a collision between names of functions. + """ + + +_STORE_BACKENDS = {'local': FileSystemStoreBackend} + + +def register_store_backend(backend_name, backend): + """Extend available store backends. + + The Memory, MemorizeResult and MemorizeFunc objects are designed to be + agnostic to the type of store used behind. By default, the local file + system is used but this function gives the possibility to extend joblib's + memory pattern with other types of storage such as cloud storage (S3, GCS, + OpenStack, HadoopFS, etc) or blob DBs. + + Parameters + ---------- + backend_name: str + The name identifying the store backend being registered. For example, + 'local' is used with FileSystemStoreBackend. + backend: StoreBackendBase subclass + The name of a class that implements the StoreBackendBase interface. + + """ + if not isinstance(backend_name, str): + raise ValueError("Store backend name should be a string, " + "'{0}' given.".format(backend_name)) + if backend is None or not issubclass(backend, StoreBackendBase): + raise ValueError("Store backend should inherit " + "StoreBackendBase, " + "'{0}' given.".format(backend)) + + _STORE_BACKENDS[backend_name] = backend + + +def _store_backend_factory(backend, location, verbose=0, backend_options=None): + """Return the correct store object for the given location.""" + if backend_options is None: + backend_options = {} + + if isinstance(location, pathlib.Path): + location = str(location) + + if isinstance(location, StoreBackendBase): + return location + elif isinstance(location, str): + obj = None + location = os.path.expanduser(location) + # The location is not a local file system, we look in the + # registered backends if there's one matching the given backend + # name. + for backend_key, backend_obj in _STORE_BACKENDS.items(): + if backend == backend_key: + obj = backend_obj() + + # By default, we assume the FileSystemStoreBackend can be used if no + # matching backend could be found. + if obj is None: + raise TypeError('Unknown location {0} or backend {1}'.format( + location, backend)) + + # The store backend is configured with the extra named parameters, + # some of them are specific to the underlying store backend. + obj.configure(location, verbose=verbose, + backend_options=backend_options) + return obj + elif location is not None: + warnings.warn( + "Instantiating a backend using a {} as a location is not " + "supported by joblib. Returning None instead.".format( + location.__class__.__name__), UserWarning) + + return None + + +def _get_func_fullname(func): + """Compute the part of part associated with a function.""" + modules, funcname = get_func_name(func) + modules.append(funcname) + return os.path.join(*modules) + + +def _build_func_identifier(func): + """Build a roughly unique identifier for the cached function.""" + parts = [] + if isinstance(func, str): + parts.append(func) + else: + parts.append(_get_func_fullname(func)) + + # We reuse historical fs-like way of building a function identifier + return os.path.join(*parts) + + +def _format_load_msg(func_id, args_id, timestamp=None, metadata=None): + """ Helper function to format the message when loading the results. + """ + signature = "" + try: + if metadata is not None: + args = ", ".join(['%s=%s' % (name, value) + for name, value + in metadata['input_args'].items()]) + signature = "%s(%s)" % (os.path.basename(func_id), args) + else: + signature = os.path.basename(func_id) + except KeyError: + pass + + if timestamp is not None: + ts_string = "{0: <16}".format(format_time(time.time() - timestamp)) + else: + ts_string = "" + return '[Memory]{0}: Loading {1}'.format(ts_string, str(signature)) + + +# An in-memory store to avoid looking at the disk-based function +# source code to check if a function definition has changed +_FUNCTION_HASHES = weakref.WeakKeyDictionary() + + +############################################################################### +# class `MemorizedResult` +############################################################################### +class MemorizedResult(Logger): + """Object representing a cached value. + + Attributes + ---------- + location: str + The location of joblib cache. Depends on the store backend used. + + func: function or str + function whose output is cached. The string case is intended only for + instantiation based on the output of repr() on another instance. + (namely eval(repr(memorized_instance)) works). + + argument_hash: str + hash of the function arguments. + + backend: str + Type of store backend for reading/writing cache files. + Default is 'local'. + + mmap_mode: {None, 'r+', 'r', 'w+', 'c'} + The memmapping mode used when loading from cache numpy arrays. See + numpy.load for the meaning of the different values. + + verbose: int + verbosity level (0 means no message). + + timestamp, metadata: string + for internal use only. + """ + def __init__(self, location, func, args_id, backend='local', + mmap_mode=None, verbose=0, timestamp=None, metadata=None): + Logger.__init__(self) + self.func_id = _build_func_identifier(func) + if isinstance(func, str): + self.func = func + else: + self.func = self.func_id + self.args_id = args_id + self.store_backend = _store_backend_factory(backend, location, + verbose=verbose) + self.mmap_mode = mmap_mode + + if metadata is not None: + self.metadata = metadata + else: + self.metadata = self.store_backend.get_metadata( + [self.func_id, self.args_id]) + + self.duration = self.metadata.get('duration', None) + self.verbose = verbose + self.timestamp = timestamp + + @property + def argument_hash(self): + warnings.warn( + "The 'argument_hash' attribute has been deprecated in version " + "0.12 and will be removed in version 0.14.\n" + "Use `args_id` attribute instead.", + DeprecationWarning, stacklevel=2) + return self.args_id + + def get(self): + """Read value from cache and return it.""" + if self.verbose: + msg = _format_load_msg(self.func_id, self.args_id, + timestamp=self.timestamp, + metadata=self.metadata) + else: + msg = None + + try: + return self.store_backend.load_item( + [self.func_id, self.args_id], msg=msg, verbose=self.verbose) + except ValueError as exc: + new_exc = KeyError( + "Error while trying to load a MemorizedResult's value. " + "It seems that this folder is corrupted : {}".format( + os.path.join( + self.store_backend.location, self.func_id, + self.args_id) + )) + raise new_exc from exc + + def clear(self): + """Clear value from cache""" + self.store_backend.clear_item([self.func_id, self.args_id]) + + def __repr__(self): + return ('{class_name}(location="{location}", func="{func}", ' + 'args_id="{args_id}")' + .format(class_name=self.__class__.__name__, + location=self.store_backend.location, + func=self.func, + args_id=self.args_id + )) + + def __getstate__(self): + state = self.__dict__.copy() + state['timestamp'] = None + return state + + +class NotMemorizedResult(object): + """Class representing an arbitrary value. + + This class is a replacement for MemorizedResult when there is no cache. + """ + __slots__ = ('value', 'valid') + + def __init__(self, value): + self.value = value + self.valid = True + + def get(self): + if self.valid: + return self.value + else: + raise KeyError("No value stored.") + + def clear(self): + self.valid = False + self.value = None + + def __repr__(self): + if self.valid: + return ('{class_name}({value})' + .format(class_name=self.__class__.__name__, + value=pformat(self.value))) + else: + return self.__class__.__name__ + ' with no value' + + # __getstate__ and __setstate__ are required because of __slots__ + def __getstate__(self): + return {"valid": self.valid, "value": self.value} + + def __setstate__(self, state): + self.valid = state["valid"] + self.value = state["value"] + + +############################################################################### +# class `NotMemorizedFunc` +############################################################################### +class NotMemorizedFunc(object): + """No-op object decorating a function. + + This class replaces MemorizedFunc when there is no cache. It provides an + identical API but does not write anything on disk. + + Attributes + ---------- + func: callable + Original undecorated function. + """ + # Should be a light as possible (for speed) + def __init__(self, func): + self.func = func + + def __call__(self, *args, **kwargs): + return self.func(*args, **kwargs) + + def call_and_shelve(self, *args, **kwargs): + return NotMemorizedResult(self.func(*args, **kwargs)) + + def __repr__(self): + return '{0}(func={1})'.format(self.__class__.__name__, self.func) + + def clear(self, warn=True): + # Argument "warn" is for compatibility with MemorizedFunc.clear + pass + + def call(self, *args, **kwargs): + return self.func(*args, **kwargs) + + def check_call_in_cache(self, *args, **kwargs): + return False + + +############################################################################### +# class `MemorizedFunc` +############################################################################### +class MemorizedFunc(Logger): + """Callable object decorating a function for caching its return value + each time it is called. + + Methods are provided to inspect the cache or clean it. + + Attributes + ---------- + func: callable + The original, undecorated, function. + + location: string + The location of joblib cache. Depends on the store backend used. + + backend: str + Type of store backend for reading/writing cache files. + Default is 'local', in which case the location is the path to a + disk storage. + + ignore: list or None + List of variable names to ignore when choosing whether to + recompute. + + mmap_mode: {None, 'r+', 'r', 'w+', 'c'} + The memmapping mode used when loading from cache + numpy arrays. See numpy.load for the meaning of the different + values. + + compress: boolean, or integer + Whether to zip the stored data on disk. If an integer is + given, it should be between 1 and 9, and sets the amount + of compression. Note that compressed arrays cannot be + read by memmapping. + + verbose: int, optional + The verbosity flag, controls messages that are issued as + the function is evaluated. + + cache_validation_callback: callable, optional + Callable to check if a result in cache is valid or is to be recomputed. + When the function is called with arguments for which a cache exists, + the callback is called with the cache entry's metadata as its sole + argument. If it returns True, the cached result is returned, else the + cache for these arguments is cleared and the result is recomputed. + """ + # ------------------------------------------------------------------------ + # Public interface + # ------------------------------------------------------------------------ + + def __init__(self, func, location, backend='local', ignore=None, + mmap_mode=None, compress=False, verbose=1, timestamp=None, + cache_validation_callback=None): + Logger.__init__(self) + self.mmap_mode = mmap_mode + self.compress = compress + self.func = func + self.cache_validation_callback = cache_validation_callback + + if ignore is None: + ignore = [] + self.ignore = ignore + self._verbose = verbose + + # retrieve store object from backend type and location. + self.store_backend = _store_backend_factory(backend, location, + verbose=verbose, + backend_options=dict( + compress=compress, + mmap_mode=mmap_mode), + ) + if self.store_backend is not None: + # Create func directory on demand. + self.store_backend.store_cached_func_code([ + _build_func_identifier(self.func) + ]) + + if timestamp is None: + timestamp = time.time() + self.timestamp = timestamp + try: + functools.update_wrapper(self, func) + except Exception: + " Objects like ufunc don't like that " + if inspect.isfunction(func): + doc = pydoc.TextDoc().document(func) + # Remove blank line + doc = doc.replace('\n', '\n\n', 1) + # Strip backspace-overprints for compatibility with autodoc + doc = re.sub('\x08.', '', doc) + else: + # Pydoc does a poor job on other objects + doc = func.__doc__ + self.__doc__ = 'Memoized version of %s' % doc + + self._func_code_info = None + self._func_code_id = None + + def _is_in_cache_and_valid(self, path): + """Check if the function call is cached and valid for given arguments. + + - Compare the function code with the one from the cached function, + asserting if it has changed. + - Check if the function call is present in the cache. + - Call `cache_validation_callback` for user define cache validation. + + Returns True if the function call is in cache and can be used, and + returns False otherwise. + """ + # Check if the code of the function has changed + if not self._check_previous_func_code(stacklevel=4): + return False + + # Check if this specific call is in the cache + if not self.store_backend.contains_item(path): + return False + + # Call the user defined cache validation callback + metadata = self.store_backend.get_metadata(path) + if (self.cache_validation_callback is not None and + not self.cache_validation_callback(metadata)): + self.store_backend.clear_item(path) + return False + + return True + + def _cached_call(self, args, kwargs, shelving=False): + """Call wrapped function and cache result, or read cache if available. + + This function returns the wrapped function output and some metadata. + + Arguments: + ---------- + + args, kwargs: list and dict + input arguments for wrapped function + + shelving: bool + True when called via the call_and_shelve function. + + + Returns + ------- + output: value or tuple or None + Output of the wrapped function. + If shelving is True and the call has been already cached, + output is None. + + argument_hash: string + Hash of function arguments. + + metadata: dict + Some metadata about wrapped function call (see _persist_input()). + """ + func_id, args_id = self._get_output_identifiers(*args, **kwargs) + metadata = None + msg = None + + # Whether or not the memorized function must be called + must_call = False + + if self._verbose >= 20: + logging.basicConfig(level=logging.INFO) + _, name = get_func_name(self.func) + location = self.store_backend.get_cached_func_info([func_id])[ + 'location'] + _, signature = format_signature(self.func, *args, **kwargs) + + self.info( + dedent( + f""" + Querying {name} with signature + {signature}. + + (argument hash {args_id}) + + The store location is {location}. + """ + ) + ) + + # Compare the function code with the previous to see if the + # function code has changed and check if the results are present in + # the cache. + if self._is_in_cache_and_valid([func_id, args_id]): + try: + t0 = time.time() + if self._verbose: + msg = _format_load_msg(func_id, args_id, + timestamp=self.timestamp, + metadata=metadata) + + if not shelving: + # When shelving, we do not need to load the output + out = self.store_backend.load_item( + [func_id, args_id], + msg=msg, + verbose=self._verbose) + else: + out = None + + if self._verbose > 4: + t = time.time() - t0 + _, name = get_func_name(self.func) + msg = '%s cache loaded - %s' % (name, format_time(t)) + print(max(0, (80 - len(msg))) * '_' + msg) + except Exception: + # XXX: Should use an exception logger + _, signature = format_signature(self.func, *args, **kwargs) + self.warn('Exception while loading results for ' + '{}\n {}'.format(signature, traceback.format_exc())) + + must_call = True + else: + if self._verbose > 10: + _, name = get_func_name(self.func) + self.warn('Computing func {0}, argument hash {1} ' + 'in location {2}' + .format(name, args_id, + self.store_backend. + get_cached_func_info([func_id])['location'])) + must_call = True + + if must_call: + out, metadata = self.call(*args, **kwargs) + if self.mmap_mode is not None: + # Memmap the output at the first call to be consistent with + # later calls + if self._verbose: + msg = _format_load_msg(func_id, args_id, + timestamp=self.timestamp, + metadata=metadata) + out = self.store_backend.load_item([func_id, args_id], msg=msg, + verbose=self._verbose) + + return (out, args_id, metadata) + + @property + def func_code_info(self): + # 3-tuple property containing: the function source code, source file, + # and first line of the code inside the source file + if hasattr(self.func, '__code__'): + if self._func_code_id is None: + self._func_code_id = id(self.func.__code__) + elif id(self.func.__code__) != self._func_code_id: + # Be robust to dynamic reassignments of self.func.__code__ + self._func_code_info = None + + if self._func_code_info is None: + # Cache the source code of self.func . Provided that get_func_code + # (which should be called once on self) gets called in the process + # in which self.func was defined, this caching mechanism prevents + # undesired cache clearing when the cached function is called in + # an environment where the introspection utilities get_func_code + # relies on do not work (typically, in joblib child processes). + # See #1035 for more info + # TODO (pierreglaser): do the same with get_func_name? + self._func_code_info = get_func_code(self.func) + return self._func_code_info + + def call_and_shelve(self, *args, **kwargs): + """Call wrapped function, cache result and return a reference. + + This method returns a reference to the cached result instead of the + result itself. The reference object is small and pickeable, allowing + to send or store it easily. Call .get() on reference object to get + result. + + Returns + ------- + cached_result: MemorizedResult or NotMemorizedResult + reference to the value returned by the wrapped function. The + class "NotMemorizedResult" is used when there is no cache + activated (e.g. location=None in Memory). + """ + _, args_id, metadata = self._cached_call(args, kwargs, shelving=True) + return MemorizedResult(self.store_backend, self.func, args_id, + metadata=metadata, verbose=self._verbose - 1, + timestamp=self.timestamp) + + def __call__(self, *args, **kwargs): + return self._cached_call(args, kwargs)[0] + + def __getstate__(self): + # Make sure self.func's source is introspected prior to being pickled - + # code introspection utilities typically do not work inside child + # processes + _ = self.func_code_info + + # We don't store the timestamp when pickling, to avoid the hash + # depending from it. + state = self.__dict__.copy() + state['timestamp'] = None + + # Invalidate the code id as id(obj) will be different in the child + state['_func_code_id'] = None + + return state + + def check_call_in_cache(self, *args, **kwargs): + """Check if function call is in the memory cache. + + Does not call the function or do any work besides func inspection + and arg hashing. + + Returns + ------- + is_call_in_cache: bool + Whether or not the result of the function has been cached + for the input arguments that have been passed. + """ + func_id, args_id = self._get_output_identifiers(*args, **kwargs) + return self.store_backend.contains_item((func_id, args_id)) + + # ------------------------------------------------------------------------ + # Private interface + # ------------------------------------------------------------------------ + + def _get_argument_hash(self, *args, **kwargs): + return hashing.hash(filter_args(self.func, self.ignore, args, kwargs), + coerce_mmap=(self.mmap_mode is not None)) + + def _get_output_identifiers(self, *args, **kwargs): + """Return the func identifier and input parameter hash of a result.""" + func_id = _build_func_identifier(self.func) + argument_hash = self._get_argument_hash(*args, **kwargs) + return func_id, argument_hash + + def _hash_func(self): + """Hash a function to key the online cache""" + func_code_h = hash(getattr(self.func, '__code__', None)) + return id(self.func), hash(self.func), func_code_h + + def _write_func_code(self, func_code, first_line): + """ Write the function code and the filename to a file. + """ + # We store the first line because the filename and the function + # name is not always enough to identify a function: people + # sometimes have several functions named the same way in a + # file. This is bad practice, but joblib should be robust to bad + # practice. + func_id = _build_func_identifier(self.func) + func_code = u'%s %i\n%s' % (FIRST_LINE_TEXT, first_line, func_code) + self.store_backend.store_cached_func_code([func_id], func_code) + + # Also store in the in-memory store of function hashes + is_named_callable = False + is_named_callable = (hasattr(self.func, '__name__') and + self.func.__name__ != '') + if is_named_callable: + # Don't do this for lambda functions or strange callable + # objects, as it ends up being too fragile + func_hash = self._hash_func() + try: + _FUNCTION_HASHES[self.func] = func_hash + except TypeError: + # Some callable are not hashable + pass + + def _check_previous_func_code(self, stacklevel=2): + """ + stacklevel is the depth a which this function is called, to + issue useful warnings to the user. + """ + # First check if our function is in the in-memory store. + # Using the in-memory store not only makes things faster, but it + # also renders us robust to variations of the files when the + # in-memory version of the code does not vary + try: + if self.func in _FUNCTION_HASHES: + # We use as an identifier the id of the function and its + # hash. This is more likely to falsely change than have hash + # collisions, thus we are on the safe side. + func_hash = self._hash_func() + if func_hash == _FUNCTION_HASHES[self.func]: + return True + except TypeError: + # Some callables are not hashable + pass + + # Here, we go through some effort to be robust to dynamically + # changing code and collision. We cannot inspect.getsource + # because it is not reliable when using IPython's magic "%run". + func_code, source_file, first_line = self.func_code_info + func_id = _build_func_identifier(self.func) + + try: + old_func_code, old_first_line =\ + extract_first_line( + self.store_backend.get_cached_func_code([func_id])) + except (IOError, OSError): # some backend can also raise OSError + self._write_func_code(func_code, first_line) + return False + if old_func_code == func_code: + return True + + # We have differing code, is this because we are referring to + # different functions, or because the function we are referring to has + # changed? + + _, func_name = get_func_name(self.func, resolv_alias=False, + win_characters=False) + if old_first_line == first_line == -1 or func_name == '': + if not first_line == -1: + func_description = ("{0} ({1}:{2})" + .format(func_name, source_file, + first_line)) + else: + func_description = func_name + warnings.warn(JobLibCollisionWarning( + "Cannot detect name collisions for function '{0}'" + .format(func_description)), stacklevel=stacklevel) + + # Fetch the code at the old location and compare it. If it is the + # same than the code store, we have a collision: the code in the + # file has not changed, but the name we have is pointing to a new + # code block. + if not old_first_line == first_line and source_file is not None: + possible_collision = False + if os.path.exists(source_file): + _, func_name = get_func_name(self.func, resolv_alias=False) + num_lines = len(func_code.split('\n')) + with open_py_source(source_file) as f: + on_disk_func_code = f.readlines()[ + old_first_line - 1:old_first_line - 1 + num_lines - 1] + on_disk_func_code = ''.join(on_disk_func_code) + possible_collision = (on_disk_func_code.rstrip() == + old_func_code.rstrip()) + else: + possible_collision = source_file.startswith(' 10: + _, func_name = get_func_name(self.func, resolv_alias=False) + self.warn("Function {0} (identified by {1}) has changed" + ".".format(func_name, func_id)) + self.clear(warn=True) + return False + + def clear(self, warn=True): + """Empty the function's cache.""" + func_id = _build_func_identifier(self.func) + + if self._verbose > 0 and warn: + self.warn("Clearing function cache identified by %s" % func_id) + self.store_backend.clear_path([func_id, ]) + + func_code, _, first_line = self.func_code_info + self._write_func_code(func_code, first_line) + + def call(self, *args, **kwargs): + """Force the execution of the function with the given arguments. + + The output values will be persisted, i.e., the cache will be updated + with any new values. + + Parameters + ---------- + *args: arguments + The arguments. + **kwargs: keyword arguments + Keyword arguments. + + Returns + ------- + output : object + The output of the function call. + metadata : dict + The metadata associated with the call. + """ + start_time = time.time() + func_id, args_id = self._get_output_identifiers(*args, **kwargs) + if self._verbose > 0: + print(format_call(self.func, args, kwargs)) + output = self.func(*args, **kwargs) + self.store_backend.dump_item( + [func_id, args_id], output, verbose=self._verbose) + + duration = time.time() - start_time + metadata = self._persist_input(duration, args, kwargs) + + if self._verbose > 0: + _, name = get_func_name(self.func) + msg = '%s - %s' % (name, format_time(duration)) + print(max(0, (80 - len(msg))) * '_' + msg) + return output, metadata + + def _persist_input(self, duration, args, kwargs, this_duration_limit=0.5): + """ Save a small summary of the call using json format in the + output directory. + + output_dir: string + directory where to write metadata. + + duration: float + time taken by hashing input arguments, calling the wrapped + function and persisting its output. + + args, kwargs: list and dict + input arguments for wrapped function + + this_duration_limit: float + Max execution time for this function before issuing a warning. + """ + start_time = time.time() + argument_dict = filter_args(self.func, self.ignore, + args, kwargs) + + input_repr = dict((k, repr(v)) for k, v in argument_dict.items()) + # This can fail due to race-conditions with multiple + # concurrent joblibs removing the file or the directory + metadata = { + "duration": duration, "input_args": input_repr, "time": start_time, + } + + func_id, args_id = self._get_output_identifiers(*args, **kwargs) + self.store_backend.store_metadata([func_id, args_id], metadata) + + this_duration = time.time() - start_time + if this_duration > this_duration_limit: + # This persistence should be fast. It will not be if repr() takes + # time and its output is large, because json.dump will have to + # write a large file. This should not be an issue with numpy arrays + # for which repr() always output a short representation, but can + # be with complex dictionaries. Fixing the problem should be a + # matter of replacing repr() above by something smarter. + warnings.warn("Persisting input arguments took %.2fs to run." + "If this happens often in your code, it can cause " + "performance problems " + "(results will be correct in all cases). " + "The reason for this is probably some large input " + "arguments for a wrapped function." + % this_duration, stacklevel=5) + return metadata + + # ------------------------------------------------------------------------ + # Private `object` interface + # ------------------------------------------------------------------------ + + def __repr__(self): + return '{class_name}(func={func}, location={location})'.format( + class_name=self.__class__.__name__, + func=self.func, + location=self.store_backend.location,) + + +############################################################################### +# class `Memory` +############################################################################### +class Memory(Logger): + """ A context object for caching a function's return value each time it + is called with the same input arguments. + + All values are cached on the filesystem, in a deep directory + structure. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + location: str, pathlib.Path or None + The path of the base directory to use as a data store + or None. If None is given, no caching is done and + the Memory object is completely transparent. This option + replaces cachedir since version 0.12. + + backend: str, optional + Type of store backend for reading/writing cache files. + Default: 'local'. + The 'local' backend is using regular filesystem operations to + manipulate data (open, mv, etc) in the backend. + + mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional + The memmapping mode used when loading from cache + numpy arrays. See numpy.load for the meaning of the + arguments. + + compress: boolean, or integer, optional + Whether to zip the stored data on disk. If an integer is + given, it should be between 1 and 9, and sets the amount + of compression. Note that compressed arrays cannot be + read by memmapping. + + verbose: int, optional + Verbosity flag, controls the debug messages that are issued + as functions are evaluated. + + bytes_limit: int | str, optional + Limit in bytes of the size of the cache. By default, the size of + the cache is unlimited. When reducing the size of the cache, + ``joblib`` keeps the most recently accessed items first. If a + str is passed, it is converted to a number of bytes using units + { K | M | G} for kilo, mega, giga. + + **Note:** You need to call :meth:`joblib.Memory.reduce_size` to + actually reduce the cache size to be less than ``bytes_limit``. + + **Note:** This argument has been deprecated. One should give the + value of ``bytes_limit`` directly in + :meth:`joblib.Memory.reduce_size`. + + backend_options: dict, optional + Contains a dictionary of named parameters used to configure + the store backend. + """ + # ------------------------------------------------------------------------ + # Public interface + # ------------------------------------------------------------------------ + + def __init__(self, location=None, backend='local', + mmap_mode=None, compress=False, verbose=1, bytes_limit=None, + backend_options=None): + Logger.__init__(self) + self._verbose = verbose + self.mmap_mode = mmap_mode + self.timestamp = time.time() + if bytes_limit is not None: + warnings.warn( + "bytes_limit argument has been deprecated. It will be removed " + "in version 1.5. Please pass its value directly to " + "Memory.reduce_size.", + category=DeprecationWarning + ) + self.bytes_limit = bytes_limit + self.backend = backend + self.compress = compress + if backend_options is None: + backend_options = {} + self.backend_options = backend_options + + if compress and mmap_mode is not None: + warnings.warn('Compressed results cannot be memmapped', + stacklevel=2) + + self.location = location + if isinstance(location, str): + location = os.path.join(location, 'joblib') + + self.store_backend = _store_backend_factory( + backend, location, verbose=self._verbose, + backend_options=dict(compress=compress, mmap_mode=mmap_mode, + **backend_options)) + + def cache(self, func=None, ignore=None, verbose=None, mmap_mode=False, + cache_validation_callback=None): + """ Decorates the given function func to only compute its return + value for input arguments not cached on disk. + + Parameters + ---------- + func: callable, optional + The function to be decorated + ignore: list of strings + A list of arguments name to ignore in the hashing + verbose: integer, optional + The verbosity mode of the function. By default that + of the memory object is used. + mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional + The memmapping mode used when loading from cache + numpy arrays. See numpy.load for the meaning of the + arguments. By default that of the memory object is used. + cache_validation_callback: callable, optional + Callable to validate whether or not the cache is valid. When + the cached function is called with arguments for which a cache + exists, this callable is called with the metadata of the cached + result as its sole argument. If it returns True, then the + cached result is returned, else the cache for these arguments + is cleared and recomputed. + + Returns + ------- + decorated_func: MemorizedFunc object + The returned object is a MemorizedFunc object, that is + callable (behaves like a function), but offers extra + methods for cache lookup and management. See the + documentation for :class:`joblib.memory.MemorizedFunc`. + """ + if (cache_validation_callback is not None and + not callable(cache_validation_callback)): + raise ValueError( + "cache_validation_callback needs to be callable. " + f"Got {cache_validation_callback}." + ) + if func is None: + # Partial application, to be able to specify extra keyword + # arguments in decorators + return functools.partial( + self.cache, ignore=ignore, + mmap_mode=mmap_mode, + verbose=verbose, + cache_validation_callback=cache_validation_callback + ) + if self.store_backend is None: + return NotMemorizedFunc(func) + if verbose is None: + verbose = self._verbose + if mmap_mode is False: + mmap_mode = self.mmap_mode + if isinstance(func, MemorizedFunc): + func = func.func + return MemorizedFunc( + func, location=self.store_backend, backend=self.backend, + ignore=ignore, mmap_mode=mmap_mode, compress=self.compress, + verbose=verbose, timestamp=self.timestamp, + cache_validation_callback=cache_validation_callback + ) + + def clear(self, warn=True): + """ Erase the complete cache directory. + """ + if warn: + self.warn('Flushing completely the cache') + if self.store_backend is not None: + self.store_backend.clear() + + # As the cache is completely clear, make sure the _FUNCTION_HASHES + # cache is also reset. Else, for a function that is present in this + # table, results cached after this clear will be have cache miss + # as the function code is not re-written. + _FUNCTION_HASHES.clear() + + def reduce_size(self, bytes_limit=None, items_limit=None, age_limit=None): + """Remove cache elements to make the cache fit its limits. + + The limitation can impose that the cache size fits in ``bytes_limit``, + that the number of cache items is no more than ``items_limit``, and + that all files in cache are not older than ``age_limit``. + + Parameters + ---------- + bytes_limit: int | str, optional + Limit in bytes of the size of the cache. By default, the size of + the cache is unlimited. When reducing the size of the cache, + ``joblib`` keeps the most recently accessed items first. If a + str is passed, it is converted to a number of bytes using units + { K | M | G} for kilo, mega, giga. + + items_limit: int, optional + Number of items to limit the cache to. By default, the number of + items in the cache is unlimited. When reducing the size of the + cache, ``joblib`` keeps the most recently accessed items first. + + age_limit: datetime.timedelta, optional + Maximum age of items to limit the cache to. When reducing the size + of the cache, any items last accessed more than the given length of + time ago are deleted. + """ + if bytes_limit is None: + bytes_limit = self.bytes_limit + + if self.store_backend is None: + # No cached results, this function does nothing. + return + + if bytes_limit is None and items_limit is None and age_limit is None: + # No limitation to impose, returning + return + + # Defers the actual limits enforcing to the store backend. + self.store_backend.enforce_store_limits( + bytes_limit, items_limit, age_limit + ) + + def eval(self, func, *args, **kwargs): + """ Eval function func with arguments `*args` and `**kwargs`, + in the context of the memory. + + This method works similarly to the builtin `apply`, except + that the function is called only if the cache is not + up to date. + + """ + if self.store_backend is None: + return func(*args, **kwargs) + return self.cache(func)(*args, **kwargs) + + # ------------------------------------------------------------------------ + # Private `object` interface + # ------------------------------------------------------------------------ + + def __repr__(self): + return '{class_name}(location={location})'.format( + class_name=self.__class__.__name__, + location=(None if self.store_backend is None + else self.store_backend.location)) + + def __getstate__(self): + """ We don't store the timestamp when pickling, to avoid the hash + depending from it. + """ + state = self.__dict__.copy() + state['timestamp'] = None + return state + + +############################################################################### +# cache_validation_callback helpers +############################################################################### + +def expires_after(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, + hours=0, weeks=0): + """Helper cache_validation_callback to force recompute after a duration. + + Parameters + ---------- + days, seconds, microseconds, milliseconds, minutes, hours, weeks: numbers + argument passed to a timedelta. + """ + delta = timedelta( + days=days, seconds=seconds, microseconds=microseconds, + milliseconds=milliseconds, minutes=minutes, hours=hours, weeks=weeks + ) + + def cache_validation_callback(metadata): + computation_age = time.time() - metadata['time'] + return computation_age < delta.total_seconds() + + return cache_validation_callback diff --git a/testbed/joblib__joblib/joblib/numpy_pickle.py b/testbed/joblib__joblib/joblib/numpy_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..bf83bb0914571dfa978bbe41a6d0e3a44a9cb947 --- /dev/null +++ b/testbed/joblib__joblib/joblib/numpy_pickle.py @@ -0,0 +1,659 @@ +"""Utilities for fast persistence of big data, with optional compression.""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import pickle +import os +import warnings +import io +from pathlib import Path + +from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR +from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile +from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper, + BZ2CompressorWrapper, LZMACompressorWrapper, + XZCompressorWrapper, LZ4CompressorWrapper) +from .numpy_pickle_utils import Unpickler, Pickler +from .numpy_pickle_utils import _read_fileobject, _write_fileobject +from .numpy_pickle_utils import _read_bytes, BUFFER_SIZE +from .numpy_pickle_utils import _ensure_native_byte_order +from .numpy_pickle_compat import load_compatibility +from .numpy_pickle_compat import NDArrayWrapper +# For compatibility with old versions of joblib, we need ZNDArrayWrapper +# to be visible in the current namespace. +# Explicitly skipping next line from flake8 as it triggers an F401 warning +# which we don't care. +from .numpy_pickle_compat import ZNDArrayWrapper # noqa +from .backports import make_memmap + +# Register supported compressors +register_compressor('zlib', ZlibCompressorWrapper()) +register_compressor('gzip', GzipCompressorWrapper()) +register_compressor('bz2', BZ2CompressorWrapper()) +register_compressor('lzma', LZMACompressorWrapper()) +register_compressor('xz', XZCompressorWrapper()) +register_compressor('lz4', LZ4CompressorWrapper()) + + +############################################################################### +# Utility objects for persistence. + +# For convenience, 16 bytes are used to be sure to cover all the possible +# dtypes' alignments. For reference, see: +# https://numpy.org/devdocs/dev/alignment.html +NUMPY_ARRAY_ALIGNMENT_BYTES = 16 + + +class NumpyArrayWrapper(object): + """An object to be persisted instead of numpy arrays. + + This object is used to hack into the pickle machinery and read numpy + array data from our custom persistence format. + More precisely, this object is used for: + * carrying the information of the persisted array: subclass, shape, order, + dtype. Those ndarray metadata are used to correctly reconstruct the array + with low level numpy functions. + * determining if memmap is allowed on the array. + * reading the array bytes from a file. + * reading the array using memorymap from a file. + * writing the array bytes to a file. + + Attributes + ---------- + subclass: numpy.ndarray subclass + Determine the subclass of the wrapped array. + shape: numpy.ndarray shape + Determine the shape of the wrapped array. + order: {'C', 'F'} + Determine the order of wrapped array data. 'C' is for C order, 'F' is + for fortran order. + dtype: numpy.ndarray dtype + Determine the data type of the wrapped array. + allow_mmap: bool + Determine if memory mapping is allowed on the wrapped array. + Default: False. + """ + + def __init__(self, subclass, shape, order, dtype, allow_mmap=False, + numpy_array_alignment_bytes=NUMPY_ARRAY_ALIGNMENT_BYTES): + """Constructor. Store the useful information for later.""" + self.subclass = subclass + self.shape = shape + self.order = order + self.dtype = dtype + self.allow_mmap = allow_mmap + # We make numpy_array_alignment_bytes an instance attribute to allow us + # to change our mind about the default alignment and still load the old + # pickles (with the previous alignment) correctly + self.numpy_array_alignment_bytes = numpy_array_alignment_bytes + + def safe_get_numpy_array_alignment_bytes(self): + # NumpyArrayWrapper instances loaded from joblib <= 1.1 pickles don't + # have an numpy_array_alignment_bytes attribute + return getattr(self, 'numpy_array_alignment_bytes', None) + + def write_array(self, array, pickler): + """Write array bytes to pickler file handle. + + This function is an adaptation of the numpy write_array function + available in version 1.10.1 in numpy/lib/format.py. + """ + # Set buffer size to 16 MiB to hide the Python loop overhead. + buffersize = max(16 * 1024 ** 2 // array.itemsize, 1) + if array.dtype.hasobject: + # We contain Python objects so we cannot write out the data + # directly. Instead, we will pickle it out with version 2 of the + # pickle protocol. + pickle.dump(array, pickler.file_handle, protocol=2) + else: + numpy_array_alignment_bytes = \ + self.safe_get_numpy_array_alignment_bytes() + if numpy_array_alignment_bytes is not None: + current_pos = pickler.file_handle.tell() + pos_after_padding_byte = current_pos + 1 + padding_length = numpy_array_alignment_bytes - ( + pos_after_padding_byte % numpy_array_alignment_bytes) + # A single byte is written that contains the padding length in + # bytes + padding_length_byte = int.to_bytes( + padding_length, length=1, byteorder='little') + pickler.file_handle.write(padding_length_byte) + + if padding_length != 0: + padding = b'\xff' * padding_length + pickler.file_handle.write(padding) + + for chunk in pickler.np.nditer(array, + flags=['external_loop', + 'buffered', + 'zerosize_ok'], + buffersize=buffersize, + order=self.order): + pickler.file_handle.write(chunk.tobytes('C')) + + def read_array(self, unpickler): + """Read array from unpickler file handle. + + This function is an adaptation of the numpy read_array function + available in version 1.10.1 in numpy/lib/format.py. + """ + if len(self.shape) == 0: + count = 1 + else: + # joblib issue #859: we cast the elements of self.shape to int64 to + # prevent a potential overflow when computing their product. + shape_int64 = [unpickler.np.int64(x) for x in self.shape] + count = unpickler.np.multiply.reduce(shape_int64) + # Now read the actual data. + if self.dtype.hasobject: + # The array contained Python objects. We need to unpickle the data. + array = pickle.load(unpickler.file_handle) + else: + numpy_array_alignment_bytes = \ + self.safe_get_numpy_array_alignment_bytes() + if numpy_array_alignment_bytes is not None: + padding_byte = unpickler.file_handle.read(1) + padding_length = int.from_bytes( + padding_byte, byteorder='little') + if padding_length != 0: + unpickler.file_handle.read(padding_length) + + # This is not a real file. We have to read it the + # memory-intensive way. + # crc32 module fails on reads greater than 2 ** 32 bytes, + # breaking large reads from gzip streams. Chunk reads to + # BUFFER_SIZE bytes to avoid issue and reduce memory overhead + # of the read. In non-chunked case count < max_read_count, so + # only one read is performed. + max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, + self.dtype.itemsize) + + array = unpickler.np.empty(count, dtype=self.dtype) + for i in range(0, count, max_read_count): + read_count = min(max_read_count, count - i) + read_size = int(read_count * self.dtype.itemsize) + data = _read_bytes(unpickler.file_handle, + read_size, "array data") + array[i:i + read_count] = \ + unpickler.np.frombuffer(data, dtype=self.dtype, + count=read_count) + del data + + if self.order == 'F': + array.shape = self.shape[::-1] + array = array.transpose() + else: + array.shape = self.shape + + # Detect byte order mismatch and swap as needed. + return _ensure_native_byte_order(array) + + def read_mmap(self, unpickler): + """Read an array using numpy memmap.""" + current_pos = unpickler.file_handle.tell() + offset = current_pos + numpy_array_alignment_bytes = \ + self.safe_get_numpy_array_alignment_bytes() + + if numpy_array_alignment_bytes is not None: + padding_byte = unpickler.file_handle.read(1) + padding_length = int.from_bytes(padding_byte, byteorder='little') + # + 1 is for the padding byte + offset += padding_length + 1 + + if unpickler.mmap_mode == 'w+': + unpickler.mmap_mode = 'r+' + + marray = make_memmap(unpickler.filename, + dtype=self.dtype, + shape=self.shape, + order=self.order, + mode=unpickler.mmap_mode, + offset=offset) + # update the offset so that it corresponds to the end of the read array + unpickler.file_handle.seek(offset + marray.nbytes) + + if (numpy_array_alignment_bytes is None and + current_pos % NUMPY_ARRAY_ALIGNMENT_BYTES != 0): + message = ( + f'The memmapped array {marray} loaded from the file ' + f'{unpickler.file_handle.name} is not byte aligned. ' + 'This may cause segmentation faults if this memmapped array ' + 'is used in some libraries like BLAS or PyTorch. ' + 'To get rid of this warning, regenerate your pickle file ' + 'with joblib >= 1.2.0. ' + 'See https://github.com/joblib/joblib/issues/563 ' + 'for more details' + ) + warnings.warn(message) + + return _ensure_native_byte_order(marray) + + def read(self, unpickler): + """Read the array corresponding to this wrapper. + + Use the unpickler to get all information to correctly read the array. + + Parameters + ---------- + unpickler: NumpyUnpickler + + Returns + ------- + array: numpy.ndarray + + """ + # When requested, only use memmap mode if allowed. + if unpickler.mmap_mode is not None and self.allow_mmap: + array = self.read_mmap(unpickler) + else: + array = self.read_array(unpickler) + + # Manage array subclass case + if (hasattr(array, '__array_prepare__') and + self.subclass not in (unpickler.np.ndarray, + unpickler.np.memmap)): + # We need to reconstruct another subclass + new_array = unpickler.np.core.multiarray._reconstruct( + self.subclass, (0,), 'b') + return new_array.__array_prepare__(array) + else: + return array + +############################################################################### +# Pickler classes + + +class NumpyPickler(Pickler): + """A pickler to persist big data efficiently. + + The main features of this object are: + * persistence of numpy arrays in a single file. + * optional compression with a special care on avoiding memory copies. + + Attributes + ---------- + fp: file + File object handle used for serializing the input object. + protocol: int, optional + Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL. + """ + + dispatch = Pickler.dispatch.copy() + + def __init__(self, fp, protocol=None): + self.file_handle = fp + self.buffered = isinstance(self.file_handle, BinaryZlibFile) + + # By default we want a pickle protocol that only changes with + # the major python version and not the minor one + if protocol is None: + protocol = pickle.DEFAULT_PROTOCOL + + Pickler.__init__(self, self.file_handle, protocol=protocol) + # delayed import of numpy, to avoid tight coupling + try: + import numpy as np + except ImportError: + np = None + self.np = np + + def _create_array_wrapper(self, array): + """Create and returns a numpy array wrapper from a numpy array.""" + order = 'F' if (array.flags.f_contiguous and + not array.flags.c_contiguous) else 'C' + allow_mmap = not self.buffered and not array.dtype.hasobject + + kwargs = {} + try: + self.file_handle.tell() + except io.UnsupportedOperation: + kwargs = {'numpy_array_alignment_bytes': None} + + wrapper = NumpyArrayWrapper(type(array), + array.shape, order, array.dtype, + allow_mmap=allow_mmap, + **kwargs) + + return wrapper + + def save(self, obj): + """Subclass the Pickler `save` method. + + This is a total abuse of the Pickler class in order to use the numpy + persistence function `save` instead of the default pickle + implementation. The numpy array is replaced by a custom wrapper in the + pickle persistence stack and the serialized array is written right + after in the file. Warning: the file produced does not follow the + pickle format. As such it can not be read with `pickle.load`. + """ + if self.np is not None and type(obj) in (self.np.ndarray, + self.np.matrix, + self.np.memmap): + if type(obj) is self.np.memmap: + # Pickling doesn't work with memmapped arrays + obj = self.np.asanyarray(obj) + + # The array wrapper is pickled instead of the real array. + wrapper = self._create_array_wrapper(obj) + Pickler.save(self, wrapper) + + # A framer was introduced with pickle protocol 4 and we want to + # ensure the wrapper object is written before the numpy array + # buffer in the pickle file. + # See https://www.python.org/dev/peps/pep-3154/#framing to get + # more information on the framer behavior. + if self.proto >= 4: + self.framer.commit_frame(force=True) + + # And then array bytes are written right after the wrapper. + wrapper.write_array(obj, self) + return + + return Pickler.save(self, obj) + + +class NumpyUnpickler(Unpickler): + """A subclass of the Unpickler to unpickle our numpy pickles. + + Attributes + ---------- + mmap_mode: str + The memorymap mode to use for reading numpy arrays. + file_handle: file_like + File object to unpickle from. + filename: str + Name of the file to unpickle from. It should correspond to file_handle. + This parameter is required when using mmap_mode. + np: module + Reference to numpy module if numpy is installed else None. + + """ + + dispatch = Unpickler.dispatch.copy() + + def __init__(self, filename, file_handle, mmap_mode=None): + # The next line is for backward compatibility with pickle generated + # with joblib versions less than 0.10. + self._dirname = os.path.dirname(filename) + + self.mmap_mode = mmap_mode + self.file_handle = file_handle + # filename is required for numpy mmap mode. + self.filename = filename + self.compat_mode = False + Unpickler.__init__(self, self.file_handle) + try: + import numpy as np + except ImportError: + np = None + self.np = np + + def load_build(self): + """Called to set the state of a newly created object. + + We capture it to replace our place-holder objects, NDArrayWrapper or + NumpyArrayWrapper, by the array we are interested in. We + replace them directly in the stack of pickler. + NDArrayWrapper is used for backward compatibility with joblib <= 0.9. + """ + Unpickler.load_build(self) + + # For backward compatibility, we support NDArrayWrapper objects. + if isinstance(self.stack[-1], (NDArrayWrapper, NumpyArrayWrapper)): + if self.np is None: + raise ImportError("Trying to unpickle an ndarray, " + "but numpy didn't import correctly") + array_wrapper = self.stack.pop() + # If any NDArrayWrapper is found, we switch to compatibility mode, + # this will be used to raise a DeprecationWarning to the user at + # the end of the unpickling. + if isinstance(array_wrapper, NDArrayWrapper): + self.compat_mode = True + self.stack.append(array_wrapper.read(self)) + + # Be careful to register our new method. + dispatch[pickle.BUILD[0]] = load_build + + +############################################################################### +# Utility functions + +def dump(value, filename, compress=0, protocol=None, cache_size=None): + """Persist an arbitrary Python object into one file. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + value: any Python object + The object to store to disk. + filename: str, pathlib.Path, or file object. + The file object or path of the file in which it is to be stored. + The compression method corresponding to one of the supported filename + extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used + automatically. + compress: int from 0 to 9 or bool or 2-tuple, optional + Optional compression level for the data. 0 or False is no compression. + Higher value means more compression, but also slower read and + write times. Using a value of 3 is often a good compromise. + See the notes for more details. + If compress is True, the compression level used is 3. + If compress is a 2-tuple, the first element must correspond to a string + between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma' + 'xz'), the second element must be an integer from 0 to 9, corresponding + to the compression level. + protocol: int, optional + Pickle protocol, see pickle.dump documentation for more details. + cache_size: positive int, optional + This option is deprecated in 0.10 and has no effect. + + Returns + ------- + filenames: list of strings + The list of file names in which the data is stored. If + compress is false, each array is stored in a different file. + + See Also + -------- + joblib.load : corresponding loader + + Notes + ----- + Memmapping on load cannot be used for compressed files. Thus + using compression can significantly slow down loading. In + addition, compressed files take up extra memory during + dump and load. + + """ + + if Path is not None and isinstance(filename, Path): + filename = str(filename) + + is_filename = isinstance(filename, str) + is_fileobj = hasattr(filename, "write") + + compress_method = 'zlib' # zlib is the default compression method. + if compress is True: + # By default, if compress is enabled, we want the default compress + # level of the compressor. + compress_level = None + elif isinstance(compress, tuple): + # a 2-tuple was set in compress + if len(compress) != 2: + raise ValueError( + 'Compress argument tuple should contain exactly 2 elements: ' + '(compress method, compress level), you passed {}' + .format(compress)) + compress_method, compress_level = compress + elif isinstance(compress, str): + compress_method = compress + compress_level = None # Use default compress level + compress = (compress_method, compress_level) + else: + compress_level = compress + + if compress_method == 'lz4' and lz4 is None: + raise ValueError(LZ4_NOT_INSTALLED_ERROR) + + if (compress_level is not None and + compress_level is not False and + compress_level not in range(10)): + # Raising an error if a non valid compress level is given. + raise ValueError( + 'Non valid compress level given: "{}". Possible values are ' + '{}.'.format(compress_level, list(range(10)))) + + if compress_method not in _COMPRESSORS: + # Raising an error if an unsupported compression method is given. + raise ValueError( + 'Non valid compression method given: "{}". Possible values are ' + '{}.'.format(compress_method, _COMPRESSORS)) + + if not is_filename and not is_fileobj: + # People keep inverting arguments, and the resulting error is + # incomprehensible + raise ValueError( + 'Second argument should be a filename or a file-like object, ' + '%s (type %s) was given.' + % (filename, type(filename)) + ) + + if is_filename and not isinstance(compress, tuple): + # In case no explicit compression was requested using both compression + # method and level in a tuple and the filename has an explicit + # extension, we select the corresponding compressor. + + # unset the variable to be sure no compression level is set afterwards. + compress_method = None + for name, compressor in _COMPRESSORS.items(): + if filename.endswith(compressor.extension): + compress_method = name + + if compress_method in _COMPRESSORS and compress_level == 0: + # we choose the default compress_level in case it was not given + # as an argument (using compress). + compress_level = None + + if cache_size is not None: + # Cache size is deprecated starting from version 0.10 + warnings.warn("Please do not set 'cache_size' in joblib.dump, " + "this parameter has no effect and will be removed. " + "You used 'cache_size={}'".format(cache_size), + DeprecationWarning, stacklevel=2) + + if compress_level != 0: + with _write_fileobject(filename, compress=(compress_method, + compress_level)) as f: + NumpyPickler(f, protocol=protocol).dump(value) + elif is_filename: + with open(filename, 'wb') as f: + NumpyPickler(f, protocol=protocol).dump(value) + else: + NumpyPickler(filename, protocol=protocol).dump(value) + + # If the target container is a file object, nothing is returned. + if is_fileobj: + return + + # For compatibility, the list of created filenames (e.g with one element + # after 0.10.0) is returned by default. + return [filename] + + +def _unpickle(fobj, filename="", mmap_mode=None): + """Internal unpickling function.""" + # We are careful to open the file handle early and keep it open to + # avoid race-conditions on renames. + # That said, if data is stored in companion files, which can be + # the case with the old persistence format, moving the directory + # will create a race when joblib tries to access the companion + # files. + unpickler = NumpyUnpickler(filename, fobj, mmap_mode=mmap_mode) + obj = None + try: + obj = unpickler.load() + if unpickler.compat_mode: + warnings.warn("The file '%s' has been generated with a " + "joblib version less than 0.10. " + "Please regenerate this pickle file." + % filename, + DeprecationWarning, stacklevel=3) + except UnicodeDecodeError as exc: + # More user-friendly error message + new_exc = ValueError( + 'You may be trying to read with ' + 'python 3 a joblib pickle generated with python 2. ' + 'This feature is not supported by joblib.') + new_exc.__cause__ = exc + raise new_exc + return obj + + +def load_temporary_memmap(filename, mmap_mode, unlink_on_gc_collect): + from ._memmapping_reducer import JOBLIB_MMAPS, add_maybe_unlink_finalizer + obj = load(filename, mmap_mode) + JOBLIB_MMAPS.add(obj.filename) + if unlink_on_gc_collect: + add_maybe_unlink_finalizer(obj) + return obj + + +def load(filename, mmap_mode=None): + """Reconstruct a Python object from a file persisted with joblib.dump. + + Read more in the :ref:`User Guide `. + + WARNING: joblib.load relies on the pickle module and can therefore + execute arbitrary Python code. It should therefore never be used + to load files from untrusted sources. + + Parameters + ---------- + filename: str, pathlib.Path, or file object. + The file object or path of the file from which to load the object + mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional + If not None, the arrays are memory-mapped from the disk. This + mode has no effect for compressed files. Note that in this + case the reconstructed object might no longer match exactly + the originally pickled object. + + Returns + ------- + result: any Python object + The object stored in the file. + + See Also + -------- + joblib.dump : function to save an object + + Notes + ----- + + This function can load numpy array files saved separately during the + dump. If the mmap_mode argument is given, it is passed to np.load and + arrays are loaded as memmaps. As a consequence, the reconstructed + object might not match the original pickled object. Note that if the + file was saved with compression, the arrays cannot be memmapped. + """ + if Path is not None and isinstance(filename, Path): + filename = str(filename) + + if hasattr(filename, "read"): + fobj = filename + filename = getattr(fobj, 'name', '') + with _read_fileobject(fobj, filename, mmap_mode) as fobj: + obj = _unpickle(fobj) + else: + with open(filename, 'rb') as f: + with _read_fileobject(f, filename, mmap_mode) as fobj: + if isinstance(fobj, str): + # if the returned file object is a string, this means we + # try to load a pickle file generated with an version of + # Joblib so we load it with joblib compatibility function. + return load_compatibility(fobj) + + obj = _unpickle(fobj, filename, mmap_mode) + return obj diff --git a/testbed/joblib__joblib/joblib/numpy_pickle_compat.py b/testbed/joblib__joblib/joblib/numpy_pickle_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..32612849bdb8320990f0433d3ded42898046c913 --- /dev/null +++ b/testbed/joblib__joblib/joblib/numpy_pickle_compat.py @@ -0,0 +1,244 @@ +"""Numpy pickle compatibility functions.""" + +import pickle +import os +import zlib +import inspect + +from io import BytesIO + +from .numpy_pickle_utils import _ZFILE_PREFIX +from .numpy_pickle_utils import Unpickler +from .numpy_pickle_utils import _ensure_native_byte_order + + +def hex_str(an_int): + """Convert an int to an hexadecimal string.""" + return '{:#x}'.format(an_int) + + +def asbytes(s): + if isinstance(s, bytes): + return s + return s.encode('latin1') + + +_MAX_LEN = len(hex_str(2 ** 64)) +_CHUNK_SIZE = 64 * 1024 + + +def read_zfile(file_handle): + """Read the z-file and return the content as a string. + + Z-files are raw data compressed with zlib used internally by joblib + for persistence. Backward compatibility is not guaranteed. Do not + use for external purposes. + """ + file_handle.seek(0) + header_length = len(_ZFILE_PREFIX) + _MAX_LEN + length = file_handle.read(header_length) + length = length[len(_ZFILE_PREFIX):] + length = int(length, 16) + + # With python2 and joblib version <= 0.8.4 compressed pickle header is one + # character wider so we need to ignore an additional space if present. + # Note: the first byte of the zlib data is guaranteed not to be a + # space according to + # https://tools.ietf.org/html/rfc6713#section-2.1 + next_byte = file_handle.read(1) + if next_byte != b' ': + # The zlib compressed data has started and we need to go back + # one byte + file_handle.seek(header_length) + + # We use the known length of the data to tell Zlib the size of the + # buffer to allocate. + data = zlib.decompress(file_handle.read(), 15, length) + assert len(data) == length, ( + "Incorrect data length while decompressing %s." + "The file could be corrupted." % file_handle) + return data + + +def write_zfile(file_handle, data, compress=1): + """Write the data in the given file as a Z-file. + + Z-files are raw data compressed with zlib used internally by joblib + for persistence. Backward compatibility is not guaranteed. Do not + use for external purposes. + """ + file_handle.write(_ZFILE_PREFIX) + length = hex_str(len(data)) + # Store the length of the data + file_handle.write(asbytes(length.ljust(_MAX_LEN))) + file_handle.write(zlib.compress(asbytes(data), compress)) + +############################################################################### +# Utility objects for persistence. + + +class NDArrayWrapper(object): + """An object to be persisted instead of numpy arrays. + + The only thing this object does, is to carry the filename in which + the array has been persisted, and the array subclass. + """ + + def __init__(self, filename, subclass, allow_mmap=True): + """Constructor. Store the useful information for later.""" + self.filename = filename + self.subclass = subclass + self.allow_mmap = allow_mmap + + def read(self, unpickler): + """Reconstruct the array.""" + filename = os.path.join(unpickler._dirname, self.filename) + # Load the array from the disk + # use getattr instead of self.allow_mmap to ensure backward compat + # with NDArrayWrapper instances pickled with joblib < 0.9.0 + allow_mmap = getattr(self, 'allow_mmap', True) + kwargs = {} + if allow_mmap: + kwargs['mmap_mode'] = unpickler.mmap_mode + if "allow_pickle" in inspect.signature(unpickler.np.load).parameters: + # Required in numpy 1.16.3 and later to aknowledge the security + # risk. + kwargs["allow_pickle"] = True + array = unpickler.np.load(filename, **kwargs) + + # Detect byte order mismatch and swap as needed. + array = _ensure_native_byte_order(array) + + # Reconstruct subclasses. This does not work with old + # versions of numpy + if (hasattr(array, '__array_prepare__') and + self.subclass not in (unpickler.np.ndarray, + unpickler.np.memmap)): + # We need to reconstruct another subclass + new_array = unpickler.np.core.multiarray._reconstruct( + self.subclass, (0,), 'b') + return new_array.__array_prepare__(array) + else: + return array + + +class ZNDArrayWrapper(NDArrayWrapper): + """An object to be persisted instead of numpy arrays. + + This object store the Zfile filename in which + the data array has been persisted, and the meta information to + retrieve it. + The reason that we store the raw buffer data of the array and + the meta information, rather than array representation routine + (tobytes) is that it enables us to use completely the strided + model to avoid memory copies (a and a.T store as fast). In + addition saving the heavy information separately can avoid + creating large temporary buffers when unpickling data with + large arrays. + """ + + def __init__(self, filename, init_args, state): + """Constructor. Store the useful information for later.""" + self.filename = filename + self.state = state + self.init_args = init_args + + def read(self, unpickler): + """Reconstruct the array from the meta-information and the z-file.""" + # Here we a simply reproducing the unpickling mechanism for numpy + # arrays + filename = os.path.join(unpickler._dirname, self.filename) + array = unpickler.np.core.multiarray._reconstruct(*self.init_args) + with open(filename, 'rb') as f: + data = read_zfile(f) + state = self.state + (data,) + array.__setstate__(state) + return array + + +class ZipNumpyUnpickler(Unpickler): + """A subclass of the Unpickler to unpickle our numpy pickles.""" + + dispatch = Unpickler.dispatch.copy() + + def __init__(self, filename, file_handle, mmap_mode=None): + """Constructor.""" + self._filename = os.path.basename(filename) + self._dirname = os.path.dirname(filename) + self.mmap_mode = mmap_mode + self.file_handle = self._open_pickle(file_handle) + Unpickler.__init__(self, self.file_handle) + try: + import numpy as np + except ImportError: + np = None + self.np = np + + def _open_pickle(self, file_handle): + return BytesIO(read_zfile(file_handle)) + + def load_build(self): + """Set the state of a newly created object. + + We capture it to replace our place-holder objects, + NDArrayWrapper, by the array we are interested in. We + replace them directly in the stack of pickler. + """ + Unpickler.load_build(self) + if isinstance(self.stack[-1], NDArrayWrapper): + if self.np is None: + raise ImportError("Trying to unpickle an ndarray, " + "but numpy didn't import correctly") + nd_array_wrapper = self.stack.pop() + array = nd_array_wrapper.read(self) + self.stack.append(array) + + dispatch[pickle.BUILD[0]] = load_build + + +def load_compatibility(filename): + """Reconstruct a Python object from a file persisted with joblib.dump. + + This function ensures the compatibility with joblib old persistence format + (<= 0.9.3). + + Parameters + ---------- + filename: string + The name of the file from which to load the object + + Returns + ------- + result: any Python object + The object stored in the file. + + See Also + -------- + joblib.dump : function to save an object + + Notes + ----- + + This function can load numpy array files saved separately during the + dump. + """ + with open(filename, 'rb') as file_handle: + # We are careful to open the file handle early and keep it open to + # avoid race-conditions on renames. That said, if data is stored in + # companion files, moving the directory will create a race when + # joblib tries to access the companion files. + unpickler = ZipNumpyUnpickler(filename, file_handle=file_handle) + try: + obj = unpickler.load() + except UnicodeDecodeError as exc: + # More user-friendly error message + new_exc = ValueError( + 'You may be trying to read with ' + 'python 3 a joblib pickle generated with python 2. ' + 'This feature is not supported by joblib.') + new_exc.__cause__ = exc + raise new_exc + finally: + if hasattr(unpickler, 'file_handle'): + unpickler.file_handle.close() + return obj diff --git a/testbed/joblib__joblib/joblib/numpy_pickle_utils.py b/testbed/joblib__joblib/joblib/numpy_pickle_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23cfb34ecb19161a2eca6bc85f29c3996162572c --- /dev/null +++ b/testbed/joblib__joblib/joblib/numpy_pickle_utils.py @@ -0,0 +1,253 @@ +"""Utilities for fast persistence of big data, with optional compression.""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import pickle +import io +import sys +import warnings +import contextlib + +from .compressor import _ZFILE_PREFIX +from .compressor import _COMPRESSORS + +try: + import numpy as np +except ImportError: + np = None + +Unpickler = pickle._Unpickler +Pickler = pickle._Pickler +xrange = range + + +try: + # The python standard library can be built without bz2 so we make bz2 + # usage optional. + # see https://github.com/scikit-learn/scikit-learn/issues/7526 for more + # details. + import bz2 +except ImportError: + bz2 = None + +# Buffer size used in io.BufferedReader and io.BufferedWriter +_IO_BUFFER_SIZE = 1024 ** 2 + + +def _is_raw_file(fileobj): + """Check if fileobj is a raw file object, e.g created with open.""" + fileobj = getattr(fileobj, 'raw', fileobj) + return isinstance(fileobj, io.FileIO) + + +def _get_prefixes_max_len(): + # Compute the max prefix len of registered compressors. + prefixes = [len(compressor.prefix) for compressor in _COMPRESSORS.values()] + prefixes += [len(_ZFILE_PREFIX)] + return max(prefixes) + + +def _is_numpy_array_byte_order_mismatch(array): + """Check if numpy array is having byte order mismatch""" + return ((sys.byteorder == 'big' and + (array.dtype.byteorder == '<' or + (array.dtype.byteorder == '|' and array.dtype.fields and + all(e[0].byteorder == '<' + for e in array.dtype.fields.values())))) or + (sys.byteorder == 'little' and + (array.dtype.byteorder == '>' or + (array.dtype.byteorder == '|' and array.dtype.fields and + all(e[0].byteorder == '>' + for e in array.dtype.fields.values()))))) + + +def _ensure_native_byte_order(array): + """Use the byte order of the host while preserving values + + Does nothing if array already uses the system byte order. + """ + if _is_numpy_array_byte_order_mismatch(array): + array = array.byteswap().view(array.dtype.newbyteorder('=')) + return array + + +############################################################################### +# Cache file utilities +def _detect_compressor(fileobj): + """Return the compressor matching fileobj. + + Parameters + ---------- + fileobj: file object + + Returns + ------- + str in {'zlib', 'gzip', 'bz2', 'lzma', 'xz', 'compat', 'not-compressed'} + """ + # Read the magic number in the first bytes of the file. + max_prefix_len = _get_prefixes_max_len() + if hasattr(fileobj, 'peek'): + # Peek allows to read those bytes without moving the cursor in the + # file whic. + first_bytes = fileobj.peek(max_prefix_len) + else: + # Fallback to seek if the fileobject is not peekable. + first_bytes = fileobj.read(max_prefix_len) + fileobj.seek(0) + + if first_bytes.startswith(_ZFILE_PREFIX): + return "compat" + else: + for name, compressor in _COMPRESSORS.items(): + if first_bytes.startswith(compressor.prefix): + return name + + return "not-compressed" + + +def _buffered_read_file(fobj): + """Return a buffered version of a read file object.""" + return io.BufferedReader(fobj, buffer_size=_IO_BUFFER_SIZE) + + +def _buffered_write_file(fobj): + """Return a buffered version of a write file object.""" + return io.BufferedWriter(fobj, buffer_size=_IO_BUFFER_SIZE) + + +@contextlib.contextmanager +def _read_fileobject(fileobj, filename, mmap_mode=None): + """Utility function opening the right fileobject from a filename. + + The magic number is used to choose between the type of file object to open: + * regular file object (default) + * zlib file object + * gzip file object + * bz2 file object + * lzma file object (for xz and lzma compressor) + + Parameters + ---------- + fileobj: file object + compressor: str in {'zlib', 'gzip', 'bz2', 'lzma', 'xz', 'compat', + 'not-compressed'} + filename: str + filename path corresponding to the fileobj parameter. + mmap_mode: str + memory map mode that should be used to open the pickle file. This + parameter is useful to verify that the user is not trying to one with + compression. Default: None. + + Returns + ------- + a file like object + + """ + # Detect if the fileobj contains compressed data. + compressor = _detect_compressor(fileobj) + + if compressor == 'compat': + # Compatibility with old pickle mode: simply return the input + # filename "as-is" and let the compatibility function be called by the + # caller. + warnings.warn("The file '%s' has been generated with a joblib " + "version less than 0.10. " + "Please regenerate this pickle file." % filename, + DeprecationWarning, stacklevel=2) + yield filename + else: + if compressor in _COMPRESSORS: + # based on the compressor detected in the file, we open the + # correct decompressor file object, wrapped in a buffer. + compressor_wrapper = _COMPRESSORS[compressor] + inst = compressor_wrapper.decompressor_file(fileobj) + fileobj = _buffered_read_file(inst) + + # Checking if incompatible load parameters with the type of file: + # mmap_mode cannot be used with compressed file or in memory buffers + # such as io.BytesIO. + if mmap_mode is not None: + if isinstance(fileobj, io.BytesIO): + warnings.warn('In memory persistence is not compatible with ' + 'mmap_mode "%(mmap_mode)s" flag passed. ' + 'mmap_mode option will be ignored.' + % locals(), stacklevel=2) + elif compressor != 'not-compressed': + warnings.warn('mmap_mode "%(mmap_mode)s" is not compatible ' + 'with compressed file %(filename)s. ' + '"%(mmap_mode)s" flag will be ignored.' + % locals(), stacklevel=2) + elif not _is_raw_file(fileobj): + warnings.warn('"%(fileobj)r" is not a raw file, mmap_mode ' + '"%(mmap_mode)s" flag will be ignored.' + % locals(), stacklevel=2) + + yield fileobj + + +def _write_fileobject(filename, compress=("zlib", 3)): + """Return the right compressor file object in write mode.""" + compressmethod = compress[0] + compresslevel = compress[1] + + if compressmethod in _COMPRESSORS.keys(): + file_instance = _COMPRESSORS[compressmethod].compressor_file( + filename, compresslevel=compresslevel) + return _buffered_write_file(file_instance) + else: + file_instance = _COMPRESSORS['zlib'].compressor_file( + filename, compresslevel=compresslevel) + return _buffered_write_file(file_instance) + + +# Utility functions/variables from numpy required for writing arrays. +# We need at least the functions introduced in version 1.9 of numpy. Here, +# we use the ones from numpy 1.10.2. +BUFFER_SIZE = 2 ** 18 # size of buffer for reading npz files in bytes + + +def _read_bytes(fp, size, error_template="ran out of data"): + """Read from file-like object until size bytes are read. + + TODO python2_drop: is it still needed? The docstring mentions python 2.6 + and it looks like this can be at least simplified ... + + Raises ValueError if not EOF is encountered before size bytes are read. + Non-blocking objects only supported if they derive from io objects. + + Required as e.g. ZipExtFile in python 2.6 can return less data than + requested. + + This function was taken from numpy/lib/format.py in version 1.10.2. + + Parameters + ---------- + fp: file-like object + size: int + error_template: str + + Returns + ------- + a bytes object + The data read in bytes. + + """ + data = bytes() + while True: + # io files (default in python3) return None or raise on + # would-block, python2 file will truncate, probably nothing can be + # done about that. note that regular files can't be non-blocking + try: + r = fp.read(size - len(data)) + data += r + if len(r) == 0 or len(data) == size: + break + except io.BlockingIOError: + pass + if len(data) != size: + msg = "EOF: reading %s, expected %d bytes got %d" + raise ValueError(msg % (error_template, size, len(data))) + else: + return data diff --git a/testbed/joblib__joblib/joblib/parallel.py b/testbed/joblib__joblib/joblib/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..91cc03adff03a8690057bf9975f58ce8f1c336cf --- /dev/null +++ b/testbed/joblib__joblib/joblib/parallel.py @@ -0,0 +1,2011 @@ +""" +Helpers for embarrassingly parallel code. +""" +# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org > +# Copyright: 2010, Gael Varoquaux +# License: BSD 3 clause + +from __future__ import division + +import os +import sys +from math import sqrt +import functools +import collections +import time +import threading +import itertools +from uuid import uuid4 +from numbers import Integral +import warnings +import queue +import weakref +from contextlib import nullcontext + +from multiprocessing import TimeoutError + +from ._multiprocessing_helpers import mp + +from .logger import Logger, short_format_time +from .disk import memstr_to_bytes +from ._parallel_backends import (FallbackToBackend, MultiprocessingBackend, + ThreadingBackend, SequentialBackend, + LokyBackend) +from ._utils import eval_expr, _Sentinel + +# Make sure that those two classes are part of the public joblib.parallel API +# so that 3rd party backend implementers can import them from here. +from ._parallel_backends import AutoBatchingMixin # noqa +from ._parallel_backends import ParallelBackendBase # noqa + + +IS_PYPY = hasattr(sys, "pypy_version_info") + + +BACKENDS = { + 'threading': ThreadingBackend, + 'sequential': SequentialBackend, +} +# name of the backend used by default by Parallel outside of any context +# managed by ``parallel_config`` or ``parallel_backend``. + +# threading is the only backend that is always everywhere +DEFAULT_BACKEND = 'threading' + +MAYBE_AVAILABLE_BACKENDS = {'multiprocessing', 'loky'} + +# if multiprocessing is available, so is loky, we set it as the default +# backend +if mp is not None: + BACKENDS['multiprocessing'] = MultiprocessingBackend + from .externals import loky + BACKENDS['loky'] = LokyBackend + DEFAULT_BACKEND = 'loky' + + +DEFAULT_THREAD_BACKEND = 'threading' + + +# Thread local value that can be overridden by the ``parallel_config`` context +# manager +_backend = threading.local() + + +def _register_dask(): + """Register Dask Backend if called with parallel_config(backend="dask")""" + try: + from ._dask import DaskDistributedBackend + register_parallel_backend('dask', DaskDistributedBackend) + except ImportError as e: + msg = ("To use the dask.distributed backend you must install both " + "the `dask` and distributed modules.\n\n" + "See https://dask.pydata.org/en/latest/install.html for more " + "information.") + raise ImportError(msg) from e + + +EXTERNAL_BACKENDS = { + 'dask': _register_dask, +} + + +# Sentinels for the default values of the Parallel constructor and +# the parallel_config and parallel_backend context managers +default_parallel_config = { + "backend": _Sentinel(default_value=None), + "n_jobs": _Sentinel(default_value=None), + "verbose": _Sentinel(default_value=0), + "temp_folder": _Sentinel(default_value=None), + "max_nbytes": _Sentinel(default_value="1M"), + "mmap_mode": _Sentinel(default_value="r"), + "prefer": _Sentinel(default_value=None), + "require": _Sentinel(default_value=None), +} + + +VALID_BACKEND_HINTS = ('processes', 'threads', None) +VALID_BACKEND_CONSTRAINTS = ('sharedmem', None) + + +def _get_config_param(param, context_config, key): + """Return the value of a parallel config parameter + + Explicitly setting it in Parallel has priority over setting in a + parallel_(config/backend) context manager. + """ + if param is not default_parallel_config[key]: + # param is explicitely set, return it + return param + + if context_config[key] is not default_parallel_config[key]: + # there's a context manager and the key is set, return it + return context_config[key] + + # Otherwise, we are in the default_parallel_config, + # return the default value + return param.default_value + + +def get_active_backend( + prefer=default_parallel_config["prefer"], + require=default_parallel_config["require"], + verbose=default_parallel_config["verbose"], +): + """Return the active default backend""" + backend, config = _get_active_backend(prefer, require, verbose) + n_jobs = _get_config_param( + default_parallel_config['n_jobs'], config, "n_jobs" + ) + return backend, n_jobs + + +def _get_active_backend( + prefer=default_parallel_config["prefer"], + require=default_parallel_config["require"], + verbose=default_parallel_config["verbose"], +): + """Return the active default backend""" + + backend_config = getattr(_backend, "config", default_parallel_config) + + backend = _get_config_param( + default_parallel_config['backend'], backend_config, "backend" + ) + prefer = _get_config_param(prefer, backend_config, "prefer") + require = _get_config_param(require, backend_config, "require") + verbose = _get_config_param(verbose, backend_config, "verbose") + + if prefer not in VALID_BACKEND_HINTS: + raise ValueError( + f"prefer={prefer} is not a valid backend hint, " + f"expected one of {VALID_BACKEND_HINTS}" + ) + if require not in VALID_BACKEND_CONSTRAINTS: + raise ValueError( + f"require={require} is not a valid backend constraint, " + f"expected one of {VALID_BACKEND_CONSTRAINTS}" + ) + if prefer == 'processes' and require == 'sharedmem': + raise ValueError( + "prefer == 'processes' and require == 'sharedmem'" + " are inconsistent settings" + ) + + explicit_backend = True + if backend is None: + + # We are either outside of the scope of any parallel_(config/backend) + # context manager or the context manager did not set a backend. + # create the default backend instance now. + backend = BACKENDS[DEFAULT_BACKEND](nesting_level=0) + explicit_backend = False + + # Try to use the backend set by the user with the context manager. + + nesting_level = backend.nesting_level + uses_threads = getattr(backend, 'uses_threads', False) + supports_sharedmem = getattr(backend, 'supports_sharedmem', False) + # Force to use thread-based backend if the provided backend does not + # match the shared memory constraint or if the backend is not explicitely + # given and threads are prefered. + force_threads = (require == 'sharedmem' and not supports_sharedmem) + force_threads |= ( + not explicit_backend and prefer == 'threads' and not uses_threads + ) + if force_threads: + # This backend does not match the shared memory constraint: + # fallback to the default thead-based backend. + sharedmem_backend = BACKENDS[DEFAULT_THREAD_BACKEND]( + nesting_level=nesting_level + ) + # Warn the user if we forced the backend to thread-based, while the + # user explicitely specified a non-thread-based backend. + if verbose >= 10 and explicit_backend: + print( + f"Using {sharedmem_backend.__class__.__name__} as " + f"joblib backend instead of {backend.__class__.__name__} " + "as the latter does not provide shared memory semantics." + ) + # Force to n_jobs=1 by default + thread_config = backend_config.copy() + thread_config['n_jobs'] = 1 + return sharedmem_backend, thread_config + + return backend, backend_config + + +class parallel_config: + """Set the default backend or configuration for :class:`~joblib.Parallel`. + + This is an alternative to directly passing keyword arguments to the + :class:`~joblib.Parallel` class constructor. It is particularly useful when + calling into library code that uses joblib internally but does not expose + the various parallel configuration arguments in its own API. + + Parameters + ---------- + backend: str or ParallelBackendBase instance, default=None + If ``backend`` is a string it must match a previously registered + implementation using the :func:`~register_parallel_backend` function. + + By default the following backends are available: + + - 'loky': single-host, process-based parallelism (used by default), + - 'threading': single-host, thread-based parallelism, + - 'multiprocessing': legacy single-host, process-based parallelism. + + 'loky' is recommended to run functions that manipulate Python objects. + 'threading' is a low-overhead alternative that is most efficient for + functions that release the Global Interpreter Lock: e.g. I/O-bound + code or CPU-bound code in a few calls to native code that explicitly + releases the GIL. Note that on some rare systems (such as pyodide), + multiprocessing and loky may not be available, in which case joblib + defaults to threading. + + In addition, if the ``dask`` and ``distributed`` Python packages are + installed, it is possible to use the 'dask' backend for better + scheduling of nested parallel calls without over-subscription and + potentially distribute parallel calls over a networked cluster of + several hosts. + + It is also possible to use the distributed 'ray' backend for + distributing the workload to a cluster of nodes. See more details + in the Examples section below. + + Alternatively the backend can be passed directly as an instance. + + n_jobs: int, default: None + The maximum number of concurrently running jobs, such as the number + of Python worker processes when ``backend="loky"`` or the size of the + thread-pool when ``backend="threading"``. + This argument is converted to an integer, rounded below for float. + If -1 is given, `joblib` tries to use all CPUs. The number of CPUs + ``n_cpus`` is obtained with :func:`~cpu_count`. + For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For instance, + using ``n_jobs=-2`` will result in all CPUs but one being used. + This argument can also go above ``n_cpus``, which will cause + oversubscription. In some cases, slight oversubscription can be + beneficial, e.g., for tasks with large I/O operations. + If 1 is given, no parallel computing code is used at all, and the + behavior amounts to a simple python `for` loop. This mode is not + compatible with `timeout`. + None is a marker for 'unset' that will be interpreted as n_jobs=1 + unless the call is performed under a :func:`~parallel_config` + context manager that sets another value for ``n_jobs``. + If n_jobs = 0 then a ValueError is raised. + + verbose: int, default=0 + The verbosity level: if non zero, progress messages are + printed. Above 50, the output is sent to stdout. + The frequency of the messages increases with the verbosity level. + If it more than 10, all iterations are reported. + + temp_folder: str, default=None + Folder to be used by the pool for memmapping large arrays + for sharing memory with worker processes. If None, this will try in + order: + + - a folder pointed by the ``JOBLIB_TEMP_FOLDER`` environment + variable, + - ``/dev/shm`` if the folder exists and is writable: this is a + RAM disk filesystem available by default on modern Linux + distributions, + - the default system temporary folder that can be + overridden with ``TMP``, ``TMPDIR`` or ``TEMP`` environment + variables, typically ``/tmp`` under Unix operating systems. + + max_nbytes int, str, or None, optional, default='1M' + Threshold on the size of arrays passed to the workers that + triggers automated memory mapping in temp_folder. Can be an int + in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte. + Use None to disable memmapping of large arrays. + + mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default='r' + Memmapping mode for numpy arrays passed to workers. None will + disable memmapping, other modes defined in the numpy.memmap doc: + https://numpy.org/doc/stable/reference/generated/numpy.memmap.html + Also, see 'max_nbytes' parameter documentation for more details. + + prefer: str in {'processes', 'threads'} or None, default=None + Soft hint to choose the default backend. + The default process-based backend is 'loky' and the default + thread-based backend is 'threading'. Ignored if the ``backend`` + parameter is specified. + + require: 'sharedmem' or None, default=None + Hard constraint to select the backend. If set to 'sharedmem', + the selected backend will be single-host and thread-based. + + inner_max_num_threads: int, default=None + If not None, overwrites the limit set on the number of threads + usable in some third-party library threadpools like OpenBLAS, + MKL or OpenMP. This is only used with the ``loky`` backend. + + backend_params: dict + Additional parameters to pass to the backend constructor when + backend is a string. + + Notes + ----- + Joblib tries to limit the oversubscription by limiting the number of + threads usable in some third-party library threadpools like OpenBLAS, MKL + or OpenMP. The default limit in each worker is set to + ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be + overwritten with the ``inner_max_num_threads`` argument which will be used + to set this limit in the child processes. + + .. versionadded:: 1.3 + + Examples + -------- + >>> from operator import neg + >>> with parallel_config(backend='threading'): + ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) + ... + [-1, -2, -3, -4, -5] + + To use the 'ray' joblib backend add the following lines: + + >>> from ray.util.joblib import register_ray # doctest: +SKIP + >>> register_ray() # doctest: +SKIP + >>> with parallel_config(backend="ray"): # doctest: +SKIP + ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) + [-1, -2, -3, -4, -5] + + """ + def __init__( + self, + backend=default_parallel_config["backend"], + *, + n_jobs=default_parallel_config["n_jobs"], + verbose=default_parallel_config["verbose"], + temp_folder=default_parallel_config["temp_folder"], + max_nbytes=default_parallel_config["max_nbytes"], + mmap_mode=default_parallel_config["mmap_mode"], + prefer=default_parallel_config["prefer"], + require=default_parallel_config["require"], + inner_max_num_threads=None, + **backend_params + ): + # Save the parallel info and set the active parallel config + self.old_parallel_config = getattr( + _backend, "config", default_parallel_config + ) + + backend = self._check_backend( + backend, inner_max_num_threads, **backend_params + ) + + new_config = { + "n_jobs": n_jobs, + "verbose": verbose, + "temp_folder": temp_folder, + "max_nbytes": max_nbytes, + "mmap_mode": mmap_mode, + "prefer": prefer, + "require": require, + "backend": backend + } + self.parallel_config = self.old_parallel_config.copy() + self.parallel_config.update({ + k: v for k, v in new_config.items() + if not isinstance(v, _Sentinel) + }) + + setattr(_backend, "config", self.parallel_config) + + def _check_backend(self, backend, inner_max_num_threads, **backend_params): + if backend is default_parallel_config['backend']: + if inner_max_num_threads is not None or len(backend_params) > 0: + raise ValueError( + "inner_max_num_threads and other constructor " + "parameters backend_params are only supported " + "when backend is not None." + ) + return backend + + if isinstance(backend, str): + # Handle non-registered or missing backends + if backend not in BACKENDS: + if backend in EXTERNAL_BACKENDS: + register = EXTERNAL_BACKENDS[backend] + register() + elif backend in MAYBE_AVAILABLE_BACKENDS: + warnings.warn( + f"joblib backend '{backend}' is not available on " + f"your system, falling back to {DEFAULT_BACKEND}.", + UserWarning, + stacklevel=2 + ) + BACKENDS[backend] = BACKENDS[DEFAULT_BACKEND] + else: + raise ValueError( + f"Invalid backend: {backend}, expected one of " + f"{sorted(BACKENDS.keys())}" + ) + + backend = BACKENDS[backend](**backend_params) + + if inner_max_num_threads is not None: + msg = ( + f"{backend.__class__.__name__} does not accept setting the " + "inner_max_num_threads argument." + ) + assert backend.supports_inner_max_num_threads, msg + backend.inner_max_num_threads = inner_max_num_threads + + # If the nesting_level of the backend is not set previously, use the + # nesting level from the previous active_backend to set it + if backend.nesting_level is None: + parent_backend = self.old_parallel_config['backend'] + if parent_backend is default_parallel_config['backend']: + nesting_level = 0 + else: + nesting_level = parent_backend.nesting_level + backend.nesting_level = nesting_level + + return backend + + def __enter__(self): + return self.parallel_config + + def __exit__(self, type, value, traceback): + self.unregister() + + def unregister(self): + setattr(_backend, "config", self.old_parallel_config) + + +class parallel_backend(parallel_config): + """Change the default backend used by Parallel inside a with block. + + .. warning:: + It is advised to use the :class:`~joblib.parallel_config` context + manager instead, which allows more fine-grained control over the + backend configuration. + + If ``backend`` is a string it must match a previously registered + implementation using the :func:`~register_parallel_backend` function. + + By default the following backends are available: + + - 'loky': single-host, process-based parallelism (used by default), + - 'threading': single-host, thread-based parallelism, + - 'multiprocessing': legacy single-host, process-based parallelism. + + 'loky' is recommended to run functions that manipulate Python objects. + 'threading' is a low-overhead alternative that is most efficient for + functions that release the Global Interpreter Lock: e.g. I/O-bound code or + CPU-bound code in a few calls to native code that explicitly releases the + GIL. Note that on some rare systems (such as Pyodide), + multiprocessing and loky may not be available, in which case joblib + defaults to threading. + + You can also use the `Dask `_ joblib + backend to distribute work across machines. This works well with + scikit-learn estimators with the ``n_jobs`` parameter, for example:: + + >>> import joblib # doctest: +SKIP + >>> from sklearn.model_selection import GridSearchCV # doctest: +SKIP + >>> from dask.distributed import Client, LocalCluster # doctest: +SKIP + + >>> # create a local Dask cluster + >>> cluster = LocalCluster() # doctest: +SKIP + >>> client = Client(cluster) # doctest: +SKIP + >>> grid_search = GridSearchCV(estimator, param_grid, n_jobs=-1) + ... # doctest: +SKIP + >>> with joblib.parallel_backend("dask", scatter=[X, y]): # doctest: +SKIP + ... grid_search.fit(X, y) + + It is also possible to use the distributed 'ray' backend for distributing + the workload to a cluster of nodes. To use the 'ray' joblib backend add + the following lines:: + + >>> from ray.util.joblib import register_ray # doctest: +SKIP + >>> register_ray() # doctest: +SKIP + >>> with parallel_backend("ray"): # doctest: +SKIP + ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) + [-1, -2, -3, -4, -5] + + Alternatively the backend can be passed directly as an instance. + + By default all available workers will be used (``n_jobs=-1``) unless the + caller passes an explicit value for the ``n_jobs`` parameter. + + This is an alternative to passing a ``backend='backend_name'`` argument to + the :class:`~Parallel` class constructor. It is particularly useful when + calling into library code that uses joblib internally but does not expose + the backend argument in its own API. + + >>> from operator import neg + >>> with parallel_backend('threading'): + ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) + ... + [-1, -2, -3, -4, -5] + + Joblib also tries to limit the oversubscription by limiting the number of + threads usable in some third-party library threadpools like OpenBLAS, MKL + or OpenMP. The default limit in each worker is set to + ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be + overwritten with the ``inner_max_num_threads`` argument which will be used + to set this limit in the child processes. + + .. versionadded:: 0.10 + + See Also + -------- + joblib.parallel_config: context manager to change the backend + configuration. + """ + def __init__(self, backend, n_jobs=-1, inner_max_num_threads=None, + **backend_params): + + super().__init__( + backend=backend, + n_jobs=n_jobs, + inner_max_num_threads=inner_max_num_threads, + **backend_params + ) + + if self.old_parallel_config is None: + self.old_backend_and_jobs = None + else: + self.old_backend_and_jobs = ( + self.old_parallel_config["backend"], + self.old_parallel_config["n_jobs"], + ) + self.new_backend_and_jobs = ( + self.parallel_config["backend"], + self.parallel_config["n_jobs"], + ) + + def __enter__(self): + return self.new_backend_and_jobs + + +# Under Linux or OS X the default start method of multiprocessing +# can cause third party libraries to crash. Under Python 3.4+ it is possible +# to set an environment variable to switch the default start method from +# 'fork' to 'forkserver' or 'spawn' to avoid this issue albeit at the cost +# of causing semantic changes and some additional pool instantiation overhead. +DEFAULT_MP_CONTEXT = None +if hasattr(mp, 'get_context'): + method = os.environ.get('JOBLIB_START_METHOD', '').strip() or None + if method is not None: + DEFAULT_MP_CONTEXT = mp.get_context(method=method) + + +class BatchedCalls(object): + """Wrap a sequence of (func, args, kwargs) tuples as a single callable""" + + def __init__(self, iterator_slice, backend_and_jobs, reducer_callback=None, + pickle_cache=None): + self.items = list(iterator_slice) + self._size = len(self.items) + self._reducer_callback = reducer_callback + if isinstance(backend_and_jobs, tuple): + self._backend, self._n_jobs = backend_and_jobs + else: + # this is for backward compatibility purposes. Before 0.12.6, + # nested backends were returned without n_jobs indications. + self._backend, self._n_jobs = backend_and_jobs, None + self._pickle_cache = pickle_cache if pickle_cache is not None else {} + + def __call__(self): + # Set the default nested backend to self._backend but do not set the + # change the default number of processes to -1 + with parallel_config(backend=self._backend, n_jobs=self._n_jobs): + return [func(*args, **kwargs) + for func, args, kwargs in self.items] + + def __reduce__(self): + if self._reducer_callback is not None: + self._reducer_callback() + # no need to pickle the callback. + return ( + BatchedCalls, + (self.items, (self._backend, self._n_jobs), None, + self._pickle_cache) + ) + + def __len__(self): + return self._size + + +# Possible exit status for a task +TASK_DONE = "Done" +TASK_ERROR = "Error" +TASK_PENDING = "Pending" + + +############################################################################### +# CPU count that works also when multiprocessing has been disabled via +# the JOBLIB_MULTIPROCESSING environment variable +def cpu_count(only_physical_cores=False): + """Return the number of CPUs. + + This delegates to loky.cpu_count that takes into account additional + constraints such as Linux CFS scheduler quotas (typically set by container + runtimes such as docker) and CPU affinity (for instance using the taskset + command on Linux). + + If only_physical_cores is True, do not take hyperthreading / SMT logical + cores into account. + """ + if mp is None: + return 1 + + return loky.cpu_count(only_physical_cores=only_physical_cores) + + +############################################################################### +# For verbosity + +def _verbosity_filter(index, verbose): + """ Returns False for indices increasingly apart, the distance + depending on the value of verbose. + + We use a lag increasing as the square of index + """ + if not verbose: + return True + elif verbose > 10: + return False + if index == 0: + return False + verbose = .5 * (11 - verbose) ** 2 + scale = sqrt(index / verbose) + next_scale = sqrt((index + 1) / verbose) + return (int(next_scale) == int(scale)) + + +############################################################################### +def delayed(function): + """Decorator used to capture the arguments of a function.""" + + def delayed_function(*args, **kwargs): + return function, args, kwargs + try: + delayed_function = functools.wraps(function)(delayed_function) + except AttributeError: + " functools.wraps fails on some callable objects " + return delayed_function + + +############################################################################### +class BatchCompletionCallBack(object): + """Callback to keep track of completed results and schedule the next tasks. + + This callable is executed by the parent process whenever a worker process + has completed a batch of tasks. + + It is used for progress reporting, to update estimate of the batch + processing duration and to schedule the next batch of tasks to be + processed. + + It is assumed that this callback will always be triggered by the backend + right after the end of a task, in case of success as well as in case of + failure. + """ + + ########################################################################## + # METHODS CALLED BY THE MAIN THREAD # + ########################################################################## + def __init__(self, dispatch_timestamp, batch_size, parallel): + self.dispatch_timestamp = dispatch_timestamp + self.batch_size = batch_size + self.parallel = parallel + self.parallel_call_id = parallel._call_id + + # Internals to keep track of the status and outcome of the task. + + # Used to hold a reference to the future-like object returned by the + # backend after launching this task + # This will be set later when calling `register_job`, as it is only + # created once the task has been submitted. + self.job = None + + if not parallel._backend.supports_retrieve_callback: + # The status is only used for asynchronous result retrieval in the + # callback. + self.status = None + else: + # The initial status for the job is TASK_PENDING. + # Once it is done, it will be either TASK_DONE, or TASK_ERROR. + self.status = TASK_PENDING + + def register_job(self, job): + """Register the object returned by `apply_async`.""" + self.job = job + + def get_result(self, timeout): + """Returns the raw result of the task that was submitted. + + If the task raised an exception rather than returning, this same + exception will be raised instead. + + If the backend supports the retrieval callback, it is assumed that this + method is only called after the result has been registered. It is + ensured by checking that `self.status(timeout)` does not return + TASK_PENDING. In this case, `get_result` directly returns the + registered result (or raise the registered exception). + + For other backends, there are no such assumptions, but `get_result` + still needs to synchronously retrieve the result before it can + return it or raise. It will block at most `self.timeout` seconds + waiting for retrieval to complete, after that it raises a TimeoutError. + """ + + backend = self.parallel._backend + + if backend.supports_retrieve_callback: + # We assume that the result has already been retrieved by the + # callback thread, and is stored internally. It's just waiting to + # be returned. + return self._return_or_raise() + + # For other backends, the main thread needs to run the retrieval step. + try: + if backend.supports_timeout: + result = self.job.get(timeout=timeout) + else: + result = self.job.get() + outcome = dict(result=result, status=TASK_DONE) + except BaseException as e: + outcome = dict(result=e, status=TASK_ERROR) + self._register_outcome(outcome) + + return self._return_or_raise() + + def _return_or_raise(self): + try: + if self.status == TASK_ERROR: + raise self._result + return self._result + finally: + del self._result + + def get_status(self, timeout): + """Get the status of the task. + + This function also checks if the timeout has been reached and register + the TimeoutError outcome when it is the case. + """ + if timeout is None or self.status != TASK_PENDING: + return self.status + + # The computation are running and the status is pending. + # Check that we did not wait for this jobs more than `timeout`. + now = time.time() + if not hasattr(self, "_completion_timeout_counter"): + self._completion_timeout_counter = now + + if (now - self._completion_timeout_counter) > timeout: + outcome = dict(result=TimeoutError(), status=TASK_ERROR) + self._register_outcome(outcome) + + return self.status + + ########################################################################## + # METHODS CALLED BY CALLBACK THREADS # + ########################################################################## + def __call__(self, out): + """Function called by the callback thread after a job is completed.""" + + # If the backend doesn't support callback retrievals, the next batch of + # tasks is dispatched regardless. The result will be retrieved by the + # main thread when calling `get_result`. + if not self.parallel._backend.supports_retrieve_callback: + self._dispatch_new() + return + + # If the backend supports retrieving the result in the callback, it + # registers the task outcome (TASK_ERROR or TASK_DONE), and schedules + # the next batch if needed. + with self.parallel._lock: + # Edge case where while the task was processing, the `parallel` + # instance has been reset and a new call has been issued, but the + # worker managed to complete the task and trigger this callback + # call just before being aborted by the reset. + if self.parallel._call_id != self.parallel_call_id: + return + + # When aborting, stop as fast as possible and do not retrieve the + # result as it won't be returned by the Parallel call. + if self.parallel._aborting: + return + + # Retrieves the result of the task in the main process and dispatch + # a new batch if needed. + job_succeeded = self._retrieve_result(out) + + if not self.parallel.return_ordered: + # Append the job to the queue in the order of completion + # instead of submission. + self.parallel._jobs.append(self) + + if job_succeeded: + self._dispatch_new() + + def _dispatch_new(self): + """Schedule the next batch of tasks to be processed.""" + + # This steps ensure that auto-batching works as expected. + this_batch_duration = time.time() - self.dispatch_timestamp + self.parallel._backend.batch_completed(self.batch_size, + this_batch_duration) + + # Schedule the next batch of tasks. + with self.parallel._lock: + self.parallel.n_completed_tasks += self.batch_size + self.parallel.print_progress() + if self.parallel._original_iterator is not None: + self.parallel.dispatch_next() + + def _retrieve_result(self, out): + """Fetch and register the outcome of a task. + + Return True if the task succeeded, False otherwise. + This function is only called by backends that support retrieving + the task result in the callback thread. + """ + try: + result = self.parallel._backend.retrieve_result_callback(out) + outcome = dict(status=TASK_DONE, result=result) + except BaseException as e: + # Avoid keeping references to parallel in the error. + e.__traceback__ = None + outcome = dict(result=e, status=TASK_ERROR) + + self._register_outcome(outcome) + return outcome['status'] != TASK_ERROR + + ########################################################################## + # This method can be called either in the main thread # + # or in the callback thread. # + ########################################################################## + def _register_outcome(self, outcome): + """Register the outcome of a task. + + This method can be called only once, future calls will be ignored. + """ + # Covers the edge case where the main thread tries to register a + # `TimeoutError` while the callback thread tries to register a result + # at the same time. + with self.parallel._lock: + if self.status not in (TASK_PENDING, None): + return + self.status = outcome["status"] + + self._result = outcome["result"] + + # Once the result and the status are extracted, the last reference to + # the job can be deleted. + self.job = None + + # As soon as an error as been spotted, early stopping flags are sent to + # the `parallel` instance. + if self.status == TASK_ERROR: + self.parallel._exception = True + self.parallel._aborting = True + + +############################################################################### +def register_parallel_backend(name, factory, make_default=False): + """Register a new Parallel backend factory. + + The new backend can then be selected by passing its name as the backend + argument to the :class:`~Parallel` class. Moreover, the default backend can + be overwritten globally by setting make_default=True. + + The factory can be any callable that takes no argument and return an + instance of ``ParallelBackendBase``. + + Warning: this function is experimental and subject to change in a future + version of joblib. + + .. versionadded:: 0.10 + """ + BACKENDS[name] = factory + if make_default: + global DEFAULT_BACKEND + DEFAULT_BACKEND = name + + +def effective_n_jobs(n_jobs=-1): + """Determine the number of jobs that can actually run in parallel + + n_jobs is the number of workers requested by the callers. Passing n_jobs=-1 + means requesting all available workers for instance matching the number of + CPU cores on the worker host(s). + + This method should return a guesstimate of the number of workers that can + actually perform work concurrently with the currently enabled default + backend. The primary use case is to make it possible for the caller to know + in how many chunks to slice the work. + + In general working on larger data chunks is more efficient (less scheduling + overhead and better use of CPU cache prefetching heuristics) as long as all + the workers have enough work to do. + + Warning: this function is experimental and subject to change in a future + version of joblib. + + .. versionadded:: 0.10 + """ + if n_jobs == 1: + return 1 + + backend, backend_n_jobs = get_active_backend() + if n_jobs is None: + n_jobs = backend_n_jobs + return backend.effective_n_jobs(n_jobs=n_jobs) + + +############################################################################### +class Parallel(Logger): + ''' Helper class for readable parallel mapping. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_jobs: int, default: None + The maximum number of concurrently running jobs, such as the number + of Python worker processes when ``backend="loky"`` or the size of + the thread-pool when ``backend="threading"``. + This argument is converted to an integer, rounded below for float. + If -1 is given, `joblib` tries to use all CPUs. The number of CPUs + ``n_cpus`` is obtained with :func:`~cpu_count`. + For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For instance, + using ``n_jobs=-2`` will result in all CPUs but one being used. + This argument can also go above ``n_cpus``, which will cause + oversubscription. In some cases, slight oversubscription can be + beneficial, e.g., for tasks with large I/O operations. + If 1 is given, no parallel computing code is used at all, and the + behavior amounts to a simple python `for` loop. This mode is not + compatible with ``timeout``. + None is a marker for 'unset' that will be interpreted as n_jobs=1 + unless the call is performed under a :func:`~parallel_config` + context manager that sets another value for ``n_jobs``. + If n_jobs = 0 then a ValueError is raised. + backend: str, ParallelBackendBase instance or None, default: 'loky' + Specify the parallelization backend implementation. + Supported backends are: + + - "loky" used by default, can induce some + communication and memory overhead when exchanging input and + output data with the worker Python processes. On some rare + systems (such as Pyiodide), the loky backend may not be + available. + - "multiprocessing" previous process-based backend based on + `multiprocessing.Pool`. Less robust than `loky`. + - "threading" is a very low-overhead backend but it suffers + from the Python Global Interpreter Lock if the called function + relies a lot on Python objects. "threading" is mostly useful + when the execution bottleneck is a compiled extension that + explicitly releases the GIL (for instance a Cython loop wrapped + in a "with nogil" block or an expensive call to a library such + as NumPy). + - finally, you can register backends by calling + :func:`~register_parallel_backend`. This will allow you to + implement a backend of your liking. + + It is not recommended to hard-code the backend name in a call to + :class:`~Parallel` in a library. Instead it is recommended to set + soft hints (prefer) or hard constraints (require) so as to make it + possible for library users to change the backend from the outside + using the :func:`~parallel_config` context manager. + return_as: str in {'list', 'generator', 'generator_unordered'}, + default: 'list' + If 'list', calls to this instance will return a list, only when + all results have been processed and retrieved. + If 'generator', it will return a generator that yields the results + as soon as they are available, in the order the tasks have been + submitted with. + If 'generator_unordered', the generator will immediately yield + available results independently of the submission order. The output + order is not deterministic in this case because it depends on the + concurrency of the workers. + prefer: str in {'processes', 'threads'} or None, default: None + Soft hint to choose the default backend if no specific backend + was selected with the :func:`~parallel_config` context manager. + The default process-based backend is 'loky' and the default + thread-based backend is 'threading'. Ignored if the ``backend`` + parameter is specified. + require: 'sharedmem' or None, default None + Hard constraint to select the backend. If set to 'sharedmem', + the selected backend will be single-host and thread-based even + if the user asked for a non-thread based backend with + :func:`~joblib.parallel_config`. + verbose: int, optional + The verbosity level: if non zero, progress messages are + printed. Above 50, the output is sent to stdout. + The frequency of the messages increases with the verbosity level. + If it more than 10, all iterations are reported. + timeout: float, optional + Timeout limit for each task to complete. If any task takes longer + a TimeOutError will be raised. Only applied when n_jobs != 1 + pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'} + The number of batches (of tasks) to be pre-dispatched. + Default is '2*n_jobs'. When batch_size="auto" this is reasonable + default and the workers should never starve. Note that only basic + arithmetics are allowed here and no modules can be used in this + expression. + batch_size: int or 'auto', default: 'auto' + The number of atomic tasks to dispatch at once to each + worker. When individual evaluations are very fast, dispatching + calls to workers can be slower than sequential computation because + of the overhead. Batching fast computations together can mitigate + this. + The ``'auto'`` strategy keeps track of the time it takes for a + batch to complete, and dynamically adjusts the batch size to keep + the time on the order of half a second, using a heuristic. The + initial batch size is 1. + ``batch_size="auto"`` with ``backend="threading"`` will dispatch + batches of a single task at a time as the threading backend has + very little overhead and using larger batch size has not proved to + bring any gain in that case. + temp_folder: str, optional + Folder to be used by the pool for memmapping large arrays + for sharing memory with worker processes. If None, this will try in + order: + + - a folder pointed by the JOBLIB_TEMP_FOLDER environment + variable, + - /dev/shm if the folder exists and is writable: this is a + RAM disk filesystem available by default on modern Linux + distributions, + - the default system temporary folder that can be + overridden with TMP, TMPDIR or TEMP environment + variables, typically /tmp under Unix operating systems. + + Only active when ``backend="loky"`` or ``"multiprocessing"``. + max_nbytes int, str, or None, optional, 1M by default + Threshold on the size of arrays passed to the workers that + triggers automated memory mapping in temp_folder. Can be an int + in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte. + Use None to disable memmapping of large arrays. + Only active when ``backend="loky"`` or ``"multiprocessing"``. + mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default: 'r' + Memmapping mode for numpy arrays passed to workers. None will + disable memmapping, other modes defined in the numpy.memmap doc: + https://numpy.org/doc/stable/reference/generated/numpy.memmap.html + Also, see 'max_nbytes' parameter documentation for more details. + + Notes + ----- + + This object uses workers to compute in parallel the application of a + function to many different arguments. The main functionality it brings + in addition to using the raw multiprocessing or concurrent.futures API + are (see examples for details): + + * More readable code, in particular since it avoids + constructing list of arguments. + + * Easier debugging: + - informative tracebacks even when the error happens on + the client side + - using 'n_jobs=1' enables to turn off parallel computing + for debugging without changing the codepath + - early capture of pickling errors + + * An optional progress meter. + + * Interruption of multiprocesses jobs with 'Ctrl-C' + + * Flexible pickling control for the communication to and from + the worker processes. + + * Ability to use shared memory efficiently with worker + processes for large numpy-based datastructures. + + Note that the intended usage is to run one call at a time. Multiple + calls to the same Parallel object will result in a ``RuntimeError`` + + Examples + -------- + + A simple example: + + >>> from math import sqrt + >>> from joblib import Parallel, delayed + >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + + Reshaping the output when the function has several return + values: + + >>> from math import modf + >>> from joblib import Parallel, delayed + >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10)) + >>> res, i = zip(*r) + >>> res + (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5) + >>> i + (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0) + + The progress meter: the higher the value of `verbose`, the more + messages: + + >>> from time import sleep + >>> from joblib import Parallel, delayed + >>> r = Parallel(n_jobs=2, verbose=10)( + ... delayed(sleep)(.2) for _ in range(10)) #doctest: +SKIP + [Parallel(n_jobs=2)]: Done 1 tasks | elapsed: 0.6s + [Parallel(n_jobs=2)]: Done 4 tasks | elapsed: 0.8s + [Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 1.4s finished + + Traceback example, note how the line of the error is indicated + as well as the values of the parameter passed to the function that + triggered the exception, even though the traceback happens in the + child process: + + >>> from heapq import nlargest + >>> from joblib import Parallel, delayed + >>> Parallel(n_jobs=2)( + ... delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) + ... # doctest: +SKIP + ----------------------------------------------------------------------- + Sub-process traceback: + ----------------------------------------------------------------------- + TypeError Mon Nov 12 11:37:46 2012 + PID: 12934 Python 2.7.3: /usr/bin/python + ........................................................................ + /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None) + 419 if n >= size: + 420 return sorted(iterable, key=key, reverse=True)[:n] + 421 + 422 # When key is none, use simpler decoration + 423 if key is None: + --> 424 it = izip(iterable, count(0,-1)) # decorate + 425 result = _nlargest(n, it) + 426 return map(itemgetter(0), result) # undecorate + 427 + 428 # General case, slowest method + TypeError: izip argument #1 must support iteration + _______________________________________________________________________ + + + Using pre_dispatch in a producer/consumer situation, where the + data is generated on the fly. Note how the producer is first + called 3 times before the parallel loop is initiated, and then + called to generate new data on the fly: + + >>> from math import sqrt + >>> from joblib import Parallel, delayed + >>> def producer(): + ... for i in range(6): + ... print('Produced %s' % i) + ... yield i + >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')( + ... delayed(sqrt)(i) for i in producer()) #doctest: +SKIP + Produced 0 + Produced 1 + Produced 2 + [Parallel(n_jobs=2)]: Done 1 jobs | elapsed: 0.0s + Produced 3 + [Parallel(n_jobs=2)]: Done 2 jobs | elapsed: 0.0s + Produced 4 + [Parallel(n_jobs=2)]: Done 3 jobs | elapsed: 0.0s + Produced 5 + [Parallel(n_jobs=2)]: Done 4 jobs | elapsed: 0.0s + [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s finished + + ''' + def __init__( + self, + n_jobs=default_parallel_config["n_jobs"], + backend=default_parallel_config['backend'], + return_as="list", + verbose=default_parallel_config["verbose"], + timeout=None, + pre_dispatch='2 * n_jobs', + batch_size='auto', + temp_folder=default_parallel_config["temp_folder"], + max_nbytes=default_parallel_config["max_nbytes"], + mmap_mode=default_parallel_config["mmap_mode"], + prefer=default_parallel_config["prefer"], + require=default_parallel_config["require"], + ): + # Initiate parent Logger class state + super().__init__() + + # Interpret n_jobs=None as 'unset' + if n_jobs is None: + n_jobs = default_parallel_config["n_jobs"] + + active_backend, context_config = _get_active_backend( + prefer=prefer, require=require, verbose=verbose + ) + + nesting_level = active_backend.nesting_level + + self.verbose = _get_config_param(verbose, context_config, "verbose") + self.timeout = timeout + self.pre_dispatch = pre_dispatch + + if return_as not in {"list", "generator", "generator_unordered"}: + raise ValueError( + 'Expected `return_as` parameter to be a string equal to "list"' + f',"generator" or "generator_unordered", but got {return_as} ' + "instead." + ) + self.return_as = return_as + self.return_generator = return_as != "list" + self.return_ordered = return_as != "generator_unordered" + + # Check if we are under a parallel_config or parallel_backend + # context manager and use the config from the context manager + # for arguments that are not explicitly set. + self._backend_args = { + k: _get_config_param(param, context_config, k) for param, k in [ + (max_nbytes, "max_nbytes"), + (temp_folder, "temp_folder"), + (mmap_mode, "mmap_mode"), + (prefer, "prefer"), + (require, "require"), + (verbose, "verbose"), + ] + } + + if isinstance(self._backend_args["max_nbytes"], str): + self._backend_args["max_nbytes"] = memstr_to_bytes( + self._backend_args["max_nbytes"] + ) + self._backend_args["verbose"] = max( + 0, self._backend_args["verbose"] - 50 + ) + + if DEFAULT_MP_CONTEXT is not None: + self._backend_args['context'] = DEFAULT_MP_CONTEXT + elif hasattr(mp, "get_context"): + self._backend_args['context'] = mp.get_context() + + if backend is default_parallel_config['backend'] or backend is None: + backend = active_backend + + elif isinstance(backend, ParallelBackendBase): + # Use provided backend as is, with the current nesting_level if it + # is not set yet. + if backend.nesting_level is None: + backend.nesting_level = nesting_level + + elif hasattr(backend, 'Pool') and hasattr(backend, 'Lock'): + # Make it possible to pass a custom multiprocessing context as + # backend to change the start method to forkserver or spawn or + # preload modules on the forkserver helper process. + self._backend_args['context'] = backend + backend = MultiprocessingBackend(nesting_level=nesting_level) + + elif backend not in BACKENDS and backend in MAYBE_AVAILABLE_BACKENDS: + warnings.warn( + f"joblib backend '{backend}' is not available on " + f"your system, falling back to {DEFAULT_BACKEND}.", + UserWarning, + stacklevel=2) + BACKENDS[backend] = BACKENDS[DEFAULT_BACKEND] + backend = BACKENDS[DEFAULT_BACKEND](nesting_level=nesting_level) + + else: + try: + backend_factory = BACKENDS[backend] + except KeyError as e: + raise ValueError("Invalid backend: %s, expected one of %r" + % (backend, sorted(BACKENDS.keys()))) from e + backend = backend_factory(nesting_level=nesting_level) + + n_jobs = _get_config_param(n_jobs, context_config, "n_jobs") + if n_jobs is None: + # No specific context override and no specific value request: + # default to the default of the backend. + n_jobs = backend.default_n_jobs + try: + n_jobs = int(n_jobs) + except ValueError: + raise ValueError("n_jobs could not be converted to int") + self.n_jobs = n_jobs + + if (require == 'sharedmem' and + not getattr(backend, 'supports_sharedmem', False)): + raise ValueError("Backend %s does not support shared memory" + % backend) + + if (batch_size == 'auto' or isinstance(batch_size, Integral) and + batch_size > 0): + self.batch_size = batch_size + else: + raise ValueError( + "batch_size must be 'auto' or a positive integer, got: %r" + % batch_size) + + if not isinstance(backend, SequentialBackend): + if self.return_generator and not backend.supports_return_generator: + raise ValueError( + "Backend {} does not support " + "return_as={}".format(backend, return_as) + ) + # This lock is used to coordinate the main thread of this process + # with the async callback thread of our the pool. + self._lock = threading.RLock() + self._jobs = collections.deque() + self._pending_outputs = list() + self._ready_batches = queue.Queue() + self._reducer_callback = None + + # Internal variables + self._backend = backend + self._running = False + self._managed_backend = False + self._id = uuid4().hex + self._call_ref = None + + def __enter__(self): + self._managed_backend = True + self._calling = False + self._initialize_backend() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._managed_backend = False + if self.return_generator and self._calling: + self._abort() + self._terminate_and_reset() + + def _initialize_backend(self): + """Build a process or thread pool and return the number of workers""" + try: + n_jobs = self._backend.configure(n_jobs=self.n_jobs, parallel=self, + **self._backend_args) + if self.timeout is not None and not self._backend.supports_timeout: + warnings.warn( + 'The backend class {!r} does not support timeout. ' + "You have set 'timeout={}' in Parallel but " + "the 'timeout' parameter will not be used.".format( + self._backend.__class__.__name__, + self.timeout)) + + except FallbackToBackend as e: + # Recursively initialize the backend in case of requested fallback. + self._backend = e.backend + n_jobs = self._initialize_backend() + + return n_jobs + + def _effective_n_jobs(self): + if self._backend: + return self._backend.effective_n_jobs(self.n_jobs) + return 1 + + def _terminate_and_reset(self): + if hasattr(self._backend, 'stop_call') and self._calling: + self._backend.stop_call() + self._calling = False + if not self._managed_backend: + self._backend.terminate() + + def _dispatch(self, batch): + """Queue the batch for computing, with or without multiprocessing + + WARNING: this method is not thread-safe: it should be only called + indirectly via dispatch_one_batch. + + """ + # If job.get() catches an exception, it closes the queue: + if self._aborting: + return + + batch_size = len(batch) + + self.n_dispatched_tasks += batch_size + self.n_dispatched_batches += 1 + + dispatch_timestamp = time.time() + + batch_tracker = BatchCompletionCallBack( + dispatch_timestamp, batch_size, self + ) + + if self.return_ordered: + self._jobs.append(batch_tracker) + + # If return_ordered is False, the batch_tracker is not stored in the + # jobs queue at the time of submission. Instead, it will be appended to + # the queue by itself as soon as the callback is triggered to be able + # to return the results in the order of completion. + + job = self._backend.apply_async(batch, callback=batch_tracker) + batch_tracker.register_job(job) + + def dispatch_next(self): + """Dispatch more data for parallel processing + + This method is meant to be called concurrently by the multiprocessing + callback. We rely on the thread-safety of dispatch_one_batch to protect + against concurrent consumption of the unprotected iterator. + + """ + if not self.dispatch_one_batch(self._original_iterator): + self._iterating = False + self._original_iterator = None + + def dispatch_one_batch(self, iterator): + """Prefetch the tasks for the next batch and dispatch them. + + The effective size of the batch is computed here. + If there are no more jobs to dispatch, return False, else return True. + + The iterator consumption and dispatching is protected by the same + lock so calling this function should be thread safe. + + """ + + if self._aborting: + return False + + batch_size = self._get_batch_size() + + with self._lock: + # to ensure an even distribution of the workload between workers, + # we look ahead in the original iterators more than batch_size + # tasks - However, we keep consuming only one batch at each + # dispatch_one_batch call. The extra tasks are stored in a local + # queue, _ready_batches, that is looked-up prior to re-consuming + # tasks from the origal iterator. + try: + tasks = self._ready_batches.get(block=False) + except queue.Empty: + # slice the iterator n_jobs * batchsize items at a time. If the + # slice returns less than that, then the current batchsize puts + # too much weight on a subset of workers, while other may end + # up starving. So in this case, re-scale the batch size + # accordingly to distribute evenly the last items between all + # workers. + n_jobs = self._cached_effective_n_jobs + big_batch_size = batch_size * n_jobs + + try: + islice = list(itertools.islice(iterator, big_batch_size)) + except Exception as e: + # Handle the fact that the generator of task raised an + # exception. As this part of the code can be executed in + # a thread internal to the backend, register a task with + # an error that will be raised in the user's thread. + if isinstance(e.__context__, queue.Empty): + # Supress the cause of the exception if it is + # queue.Empty to avoid cluttered traceback. Only do it + # if the __context__ is really empty to avoid messing + # with causes of the original error. + e.__cause__ = None + batch_tracker = BatchCompletionCallBack( + 0, batch_size, self + ) + self._jobs.append(batch_tracker) + batch_tracker._register_outcome(dict( + result=e, status=TASK_ERROR + )) + return True + + if len(islice) == 0: + return False + elif (iterator is self._original_iterator and + len(islice) < big_batch_size): + # We reached the end of the original iterator (unless + # iterator is the ``pre_dispatch``-long initial slice of + # the original iterator) -- decrease the batch size to + # account for potential variance in the batches running + # time. + final_batch_size = max(1, len(islice) // (10 * n_jobs)) + else: + final_batch_size = max(1, len(islice) // n_jobs) + + # enqueue n_jobs batches in a local queue + for i in range(0, len(islice), final_batch_size): + tasks = BatchedCalls(islice[i:i + final_batch_size], + self._backend.get_nested_backend(), + self._reducer_callback, + self._pickle_cache) + self._ready_batches.put(tasks) + + # finally, get one task. + tasks = self._ready_batches.get(block=False) + if len(tasks) == 0: + # No more tasks available in the iterator: tell caller to stop. + return False + else: + self._dispatch(tasks) + return True + + def _get_batch_size(self): + """Returns the effective batch size for dispatch""" + if self.batch_size == 'auto': + return self._backend.compute_batch_size() + else: + # Fixed batch size strategy + return self.batch_size + + def _print(self, msg): + """Display the message on stout or stderr depending on verbosity""" + # XXX: Not using the logger framework: need to + # learn to use logger better. + if not self.verbose: + return + if self.verbose < 50: + writer = sys.stderr.write + else: + writer = sys.stdout.write + writer(f"[{self}]: {msg}\n") + + def _is_completed(self): + """Check if all tasks have been completed""" + return self.n_completed_tasks == self.n_dispatched_tasks and not ( + self._iterating or self._aborting + ) + + def print_progress(self): + """Display the process of the parallel execution only a fraction + of time, controlled by self.verbose. + """ + + if not self.verbose: + return + + elapsed_time = time.time() - self._start_time + + if self._is_completed(): + # Make sure that we get a last message telling us we are done + self._print( + f"Done {self.n_completed_tasks:3d} out of " + f"{self.n_completed_tasks:3d} | elapsed: " + f"{short_format_time(elapsed_time)} finished" + ) + return + + # Original job iterator becomes None once it has been fully + # consumed: at this point we know the total number of jobs and we are + # able to display an estimation of the remaining time based on already + # completed jobs. Otherwise, we simply display the number of completed + # tasks. + elif self._original_iterator is not None: + if _verbosity_filter(self.n_dispatched_batches, self.verbose): + return + self._print( + f"Done {self.n_completed_tasks:3d} tasks | elapsed: " + f"{short_format_time(elapsed_time)}" + ) + else: + index = self.n_completed_tasks + # We are finished dispatching + total_tasks = self.n_dispatched_tasks + # We always display the first loop + if not index == 0: + # Display depending on the number of remaining items + # A message as soon as we finish dispatching, cursor is 0 + cursor = (total_tasks - index + 1 - + self._pre_dispatch_amount) + frequency = (total_tasks // self.verbose) + 1 + is_last_item = (index + 1 == total_tasks) + if (is_last_item or cursor % frequency): + return + remaining_time = (elapsed_time / index) * \ + (self.n_dispatched_tasks - index * 1.0) + # only display status if remaining time is greater or equal to 0 + self._print( + f"Done {index:3d} out of {total_tasks:3d} | elapsed: " + f"{short_format_time(elapsed_time)} remaining: " + f"{short_format_time(remaining_time)}" + ) + + def _abort(self): + # Stop dispatching new jobs in the async callback thread + self._aborting = True + + # If the backend allows it, cancel or kill remaining running + # tasks without waiting for the results as we will raise + # the exception we got back to the caller instead of returning + # any result. + backend = self._backend + if (not self._aborted and hasattr(backend, 'abort_everything')): + # If the backend is managed externally we need to make sure + # to leave it in a working state to allow for future jobs + # scheduling. + ensure_ready = self._managed_backend + backend.abort_everything(ensure_ready=ensure_ready) + self._aborted = True + + def _start(self, iterator, pre_dispatch): + # Only set self._iterating to True if at least a batch + # was dispatched. In particular this covers the edge + # case of Parallel used with an exhausted iterator. If + # self._original_iterator is None, then this means either + # that pre_dispatch == "all", n_jobs == 1 or that the first batch + # was very quick and its callback already dispatched all the + # remaining jobs. + self._iterating = False + if self.dispatch_one_batch(iterator): + self._iterating = self._original_iterator is not None + + while self.dispatch_one_batch(iterator): + pass + + if pre_dispatch == "all": + # The iterable was consumed all at once by the above for loop. + # No need to wait for async callbacks to trigger to + # consumption. + self._iterating = False + + def _get_outputs(self, iterator, pre_dispatch): + """Iterator returning the tasks' output as soon as they are ready.""" + dispatch_thread_id = threading.get_ident() + detach_generator_exit = False + try: + self._start(iterator, pre_dispatch) + # first yield returns None, for internal use only. This ensures + # that we enter the try/except block and start dispatching the + # tasks. + yield + + with self._backend.retrieval_context(): + yield from self._retrieve() + + except GeneratorExit: + # The generator has been garbage collected before being fully + # consumed. This aborts the remaining tasks if possible and warn + # the user if necessary. + self._exception = True + + # In some interpreters such as PyPy, GeneratorExit can be raised in + # a different thread than the one used to start the dispatch of the + # parallel tasks. This can lead to hang when a thread attempts to + # join itself. As workaround, we detach the execution of the + # aborting code to a dedicated thread. We then need to make sure + # the rest of the function does not call `_terminate_and_reset` + # in finally. + if dispatch_thread_id != threading.get_ident(): + if not IS_PYPY: + warnings.warn( + "A generator produced by joblib.Parallel has been " + "gc'ed in an unexpected thread. This behavior should " + "not cause major -issues but to make sure, please " + "report this warning and your use case at " + "https://github.com/joblib/joblib/issues so it can " + "be investigated." + ) + + detach_generator_exit = True + _parallel = self + + class _GeneratorExitThread(threading.Thread): + def run(self): + _parallel._abort() + if _parallel.return_generator: + _parallel._warn_exit_early() + _parallel._terminate_and_reset() + + _GeneratorExitThread( + name="GeneratorExitThread" + ).start() + return + + # Otherwise, we are in the thread that started the dispatch: we can + # safely abort the execution and warn the user. + self._abort() + if self.return_generator: + self._warn_exit_early() + + raise + + # Note: we catch any BaseException instead of just Exception instances + # to also include KeyboardInterrupt + except BaseException: + self._exception = True + self._abort() + raise + finally: + # Store the unconsumed tasks and terminate the workers if necessary + _remaining_outputs = ([] if self._exception else self._jobs) + self._jobs = collections.deque() + self._running = False + if not detach_generator_exit: + self._terminate_and_reset() + + while len(_remaining_outputs) > 0: + batched_results = _remaining_outputs.popleft() + batched_results = batched_results.get_result(self.timeout) + for result in batched_results: + yield result + + def _wait_retrieval(self): + """Return True if we need to continue retriving some tasks.""" + + # If the input load is still being iterated over, it means that tasks + # are still on the dispatch wait list and their results will need to + # be retrieved later on. + if self._iterating: + return True + + # If some of the dispatched tasks are still being processed by the + # workers, wait for the compute to finish before starting retrieval + if self.n_completed_tasks < self.n_dispatched_tasks: + return True + + # For backends that does not support retrieving asynchronously the + # result to the main process, all results must be carefully retrieved + # in the _retrieve loop in the main thread while the backend is alive. + # For other backends, the actual retrieval is done asynchronously in + # the callback thread, and we can terminate the backend before the + # `self._jobs` result list has been emptied. The remaining results + # will be collected in the `finally` step of the generator. + if not self._backend.supports_retrieve_callback: + if len(self._jobs) > 0: + return True + + return False + + def _retrieve(self): + while self._wait_retrieval(): + + # If the callback thread of a worker has signaled that its task + # triggered an exception, or if the retrieval loop has raised an + # exception (e.g. `GeneratorExit`), exit the loop and surface the + # worker traceback. + if self._aborting: + self._raise_error_fast() + break + + # If the next job is not ready for retrieval yet, we just wait for + # async callbacks to progress. + if ((len(self._jobs) == 0) or + (self._jobs[0].get_status( + timeout=self.timeout) == TASK_PENDING)): + time.sleep(0.01) + continue + + # We need to be careful: the job list can be filling up as + # we empty it and Python list are not thread-safe by + # default hence the use of the lock + with self._lock: + batched_results = self._jobs.popleft() + + # Flatten the batched results to output one output at a time + batched_results = batched_results.get_result(self.timeout) + for result in batched_results: + self._nb_consumed += 1 + yield result + + def _raise_error_fast(self): + """If we are aborting, raise if a job caused an error.""" + + # Find the first job whose status is TASK_ERROR if it exists. + with self._lock: + error_job = next((job for job in self._jobs + if job.status == TASK_ERROR), None) + + # If this error job exists, immediatly raise the error by + # calling get_result. This job might not exists if abort has been + # called directly or if the generator is gc'ed. + if error_job is not None: + error_job.get_result(self.timeout) + + def _warn_exit_early(self): + """Warn the user if the generator is gc'ed before being consumned.""" + ready_outputs = self.n_completed_tasks - self._nb_consumed + is_completed = self._is_completed() + msg = "" + if ready_outputs: + msg += ( + f"{ready_outputs} tasks have been successfully executed " + " but not used." + ) + if not is_completed: + msg += " Additionally, " + + if not is_completed: + msg += ( + f"{self.n_dispatched_tasks - self.n_completed_tasks} tasks " + "which were still being processed by the workers have been " + "cancelled." + ) + + if msg: + msg += ( + " You could benefit from adjusting the input task " + "iterator to limit unnecessary computation time." + ) + + warnings.warn(msg) + + def _get_sequential_output(self, iterable): + """Separate loop for sequential output. + + This simplifies the traceback in case of errors and reduces the + overhead of calling sequential tasks with `joblib`. + """ + try: + self._iterating = True + self._original_iterator = iterable + batch_size = self._get_batch_size() + + if batch_size != 1: + it = iter(iterable) + iterable_batched = iter( + lambda: tuple(itertools.islice(it, batch_size)), () + ) + iterable = ( + task for batch in iterable_batched for task in batch + ) + + # first yield returns None, for internal use only. This ensures + # that we enter the try/except block and setup the generator. + yield None + + # Sequentially call the tasks and yield the results. + for func, args, kwargs in iterable: + self.n_dispatched_batches += 1 + self.n_dispatched_tasks += 1 + res = func(*args, **kwargs) + self.n_completed_tasks += 1 + self.print_progress() + yield res + self._nb_consumed += 1 + except BaseException: + self._exception = True + self._aborting = True + self._aborted = True + raise + finally: + self.print_progress() + self._running = False + self._iterating = False + self._original_iterator = None + + def _reset_run_tracking(self): + """Reset the counters and flags used to track the execution.""" + + # Makes sur the parallel instance was not previously running in a + # thread-safe way. + with getattr(self, '_lock', nullcontext()): + if self._running: + msg = 'This Parallel instance is already running !' + if self.return_generator is True: + msg += ( + " Before submitting new tasks, you must wait for the " + "completion of all the previous tasks, or clean all " + "references to the output generator." + ) + raise RuntimeError(msg) + self._running = True + + # Counter to keep track of the task dispatched and completed. + self.n_dispatched_batches = 0 + self.n_dispatched_tasks = 0 + self.n_completed_tasks = 0 + + # Following count is incremented by one each time the user iterates + # on the output generator, it is used to prepare an informative + # warning message in case the generator is deleted before all the + # dispatched tasks have been consumed. + self._nb_consumed = 0 + + # Following flags are used to synchronize the threads in case one of + # the tasks error-out to ensure that all workers abort fast and that + # the backend terminates properly. + + # Set to True as soon as a worker signals that a task errors-out + self._exception = False + # Set to True in case of early termination following an incident + self._aborting = False + # Set to True after abortion is complete + self._aborted = False + + def __call__(self, iterable): + """Main function to dispatch parallel tasks.""" + + self._reset_run_tracking() + self._start_time = time.time() + + if not self._managed_backend: + n_jobs = self._initialize_backend() + else: + n_jobs = self._effective_n_jobs() + + if n_jobs == 1: + # If n_jobs==1, run the computation sequentially and return + # immediatly to avoid overheads. + output = self._get_sequential_output(iterable) + next(output) + return output if self.return_generator else list(output) + + # Let's create an ID that uniquely identifies the current call. If the + # call is interrupted early and that the same instance is immediately + # re-used, this id will be used to prevent workers that were + # concurrently finalizing a task from the previous call to run the + # callback. + with self._lock: + self._call_id = uuid4().hex + + # self._effective_n_jobs should be called in the Parallel.__call__ + # thread only -- store its value in an attribute for further queries. + self._cached_effective_n_jobs = n_jobs + + if isinstance(self._backend, LokyBackend): + # For the loky backend, we add a callback executed when reducing + # BatchCalls, that makes the loky executor use a temporary folder + # specific to this Parallel object when pickling temporary memmaps. + # This callback is necessary to ensure that several Parallel + # objects using the same resuable executor don't use the same + # temporary resources. + + def _batched_calls_reducer_callback(): + # Relevant implementation detail: the following lines, called + # when reducing BatchedCalls, are called in a thread-safe + # situation, meaning that the context of the temporary folder + # manager will not be changed in between the callback execution + # and the end of the BatchedCalls pickling. The reason is that + # pickling (the only place where set_current_context is used) + # is done from a single thread (the queue_feeder_thread). + self._backend._workers._temp_folder_manager.set_current_context( # noqa + self._id + ) + self._reducer_callback = _batched_calls_reducer_callback + + # self._effective_n_jobs should be called in the Parallel.__call__ + # thread only -- store its value in an attribute for further queries. + self._cached_effective_n_jobs = n_jobs + + backend_name = self._backend.__class__.__name__ + if n_jobs == 0: + raise RuntimeError("%s has no active worker." % backend_name) + + self._print( + f"Using backend {backend_name} with {n_jobs} concurrent workers." + ) + if hasattr(self._backend, 'start_call'): + self._backend.start_call() + + # Following flag prevents double calls to `backend.stop_call`. + self._calling = True + + iterator = iter(iterable) + pre_dispatch = self.pre_dispatch + + if pre_dispatch == 'all': + # prevent further dispatch via multiprocessing callback thread + self._original_iterator = None + self._pre_dispatch_amount = 0 + else: + self._original_iterator = iterator + if hasattr(pre_dispatch, 'endswith'): + pre_dispatch = eval_expr( + pre_dispatch.replace("n_jobs", str(n_jobs)) + ) + self._pre_dispatch_amount = pre_dispatch = int(pre_dispatch) + + # The main thread will consume the first pre_dispatch items and + # the remaining items will later be lazily dispatched by async + # callbacks upon task completions. + + # TODO: this iterator should be batch_size * n_jobs + iterator = itertools.islice(iterator, self._pre_dispatch_amount) + + # Use a caching dict for callables that are pickled with cloudpickle to + # improve performances. This cache is used only in the case of + # functions that are defined in the __main__ module, functions that + # are defined locally (inside another function) and lambda expressions. + self._pickle_cache = dict() + + output = self._get_outputs(iterator, pre_dispatch) + self._call_ref = weakref.ref(output) + + # The first item from the output is blank, but it makes the interpreter + # progress until it enters the Try/Except block of the generator and + # reach the first `yield` statement. This starts the aynchronous + # dispatch of the tasks to the workers. + next(output) + + return output if self.return_generator else list(output) + + def __repr__(self): + return '%s(n_jobs=%s)' % (self.__class__.__name__, self.n_jobs) diff --git a/testbed/joblib__joblib/joblib/pool.py b/testbed/joblib__joblib/joblib/pool.py new file mode 100644 index 0000000000000000000000000000000000000000..72a6baa3ac5854ebac9f96a4c6df77b52bff300e --- /dev/null +++ b/testbed/joblib__joblib/joblib/pool.py @@ -0,0 +1,354 @@ +"""Custom implementation of multiprocessing.Pool with custom pickler. + +This module provides efficient ways of working with data stored in +shared memory with numpy.memmap arrays without inducing any memory +copy between the parent and child processes. + +This module should not be imported if multiprocessing is not +available as it implements subclasses of multiprocessing Pool +that uses a custom alternative to SimpleQueue. + +""" +# Author: Olivier Grisel +# Copyright: 2012, Olivier Grisel +# License: BSD 3 clause + +import copyreg +import sys +import warnings +from time import sleep + +try: + WindowsError +except NameError: + WindowsError = type(None) + +from pickle import Pickler + +from pickle import HIGHEST_PROTOCOL +from io import BytesIO + +from ._memmapping_reducer import get_memmapping_reducers +from ._memmapping_reducer import TemporaryResourcesManager +from ._multiprocessing_helpers import mp, assert_spawning + +# We need the class definition to derive from it, not the multiprocessing.Pool +# factory function +from multiprocessing.pool import Pool + +try: + import numpy as np +except ImportError: + np = None + + +############################################################################### +# Enable custom pickling in Pool queues + +class CustomizablePickler(Pickler): + """Pickler that accepts custom reducers. + + TODO python2_drop : can this be simplified ? + + HIGHEST_PROTOCOL is selected by default as this pickler is used + to pickle ephemeral datastructures for interprocess communication + hence no backward compatibility is required. + + `reducers` is expected to be a dictionary with key/values + being `(type, callable)` pairs where `callable` is a function that + give an instance of `type` will return a tuple `(constructor, + tuple_of_objects)` to rebuild an instance out of the pickled + `tuple_of_objects` as would return a `__reduce__` method. See the + standard library documentation on pickling for more details. + + """ + + # We override the pure Python pickler as its the only way to be able to + # customize the dispatch table without side effects in Python 2.7 + # to 3.2. For Python 3.3+ leverage the new dispatch_table + # feature from https://bugs.python.org/issue14166 that makes it possible + # to use the C implementation of the Pickler which is faster. + + def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL): + Pickler.__init__(self, writer, protocol=protocol) + if reducers is None: + reducers = {} + if hasattr(Pickler, 'dispatch'): + # Make the dispatch registry an instance level attribute instead of + # a reference to the class dictionary under Python 2 + self.dispatch = Pickler.dispatch.copy() + else: + # Under Python 3 initialize the dispatch table with a copy of the + # default registry + self.dispatch_table = copyreg.dispatch_table.copy() + for type, reduce_func in reducers.items(): + self.register(type, reduce_func) + + def register(self, type, reduce_func): + """Attach a reducer function to a given type in the dispatch table.""" + if hasattr(Pickler, 'dispatch'): + # Python 2 pickler dispatching is not explicitly customizable. + # Let us use a closure to workaround this limitation. + def dispatcher(self, obj): + reduced = reduce_func(obj) + self.save_reduce(obj=obj, *reduced) + self.dispatch[type] = dispatcher + else: + self.dispatch_table[type] = reduce_func + + +class CustomizablePicklingQueue(object): + """Locked Pipe implementation that uses a customizable pickler. + + This class is an alternative to the multiprocessing implementation + of SimpleQueue in order to make it possible to pass custom + pickling reducers, for instance to avoid memory copy when passing + memory mapped datastructures. + + `reducers` is expected to be a dict with key / values being + `(type, callable)` pairs where `callable` is a function that, given an + instance of `type`, will return a tuple `(constructor, tuple_of_objects)` + to rebuild an instance out of the pickled `tuple_of_objects` as would + return a `__reduce__` method. + + See the standard library documentation on pickling for more details. + """ + + def __init__(self, context, reducers=None): + self._reducers = reducers + self._reader, self._writer = context.Pipe(duplex=False) + self._rlock = context.Lock() + if sys.platform == 'win32': + self._wlock = None + else: + self._wlock = context.Lock() + self._make_methods() + + def __getstate__(self): + assert_spawning(self) + return (self._reader, self._writer, self._rlock, self._wlock, + self._reducers) + + def __setstate__(self, state): + (self._reader, self._writer, self._rlock, self._wlock, + self._reducers) = state + self._make_methods() + + def empty(self): + return not self._reader.poll() + + def _make_methods(self): + self._recv = recv = self._reader.recv + racquire, rrelease = self._rlock.acquire, self._rlock.release + + def get(): + racquire() + try: + return recv() + finally: + rrelease() + + self.get = get + + if self._reducers: + def send(obj): + buffer = BytesIO() + CustomizablePickler(buffer, self._reducers).dump(obj) + self._writer.send_bytes(buffer.getvalue()) + self._send = send + else: + self._send = send = self._writer.send + if self._wlock is None: + # writes to a message oriented win32 pipe are atomic + self.put = send + else: + wlock_acquire, wlock_release = ( + self._wlock.acquire, self._wlock.release) + + def put(obj): + wlock_acquire() + try: + return send(obj) + finally: + wlock_release() + + self.put = put + + +class PicklingPool(Pool): + """Pool implementation with customizable pickling reducers. + + This is useful to control how data is shipped between processes + and makes it possible to use shared memory without useless + copies induces by the default pickling methods of the original + objects passed as arguments to dispatch. + + `forward_reducers` and `backward_reducers` are expected to be + dictionaries with key/values being `(type, callable)` pairs where + `callable` is a function that, given an instance of `type`, will return a + tuple `(constructor, tuple_of_objects)` to rebuild an instance out of the + pickled `tuple_of_objects` as would return a `__reduce__` method. + See the standard library documentation about pickling for more details. + + """ + + def __init__(self, processes=None, forward_reducers=None, + backward_reducers=None, **kwargs): + if forward_reducers is None: + forward_reducers = dict() + if backward_reducers is None: + backward_reducers = dict() + self._forward_reducers = forward_reducers + self._backward_reducers = backward_reducers + poolargs = dict(processes=processes) + poolargs.update(kwargs) + super(PicklingPool, self).__init__(**poolargs) + + def _setup_queues(self): + context = getattr(self, '_ctx', mp) + self._inqueue = CustomizablePicklingQueue(context, + self._forward_reducers) + self._outqueue = CustomizablePicklingQueue(context, + self._backward_reducers) + self._quick_put = self._inqueue._send + self._quick_get = self._outqueue._recv + + +class MemmappingPool(PicklingPool): + """Process pool that shares large arrays to avoid memory copy. + + This drop-in replacement for `multiprocessing.pool.Pool` makes + it possible to work efficiently with shared memory in a numpy + context. + + Existing instances of numpy.memmap are preserved: the child + suprocesses will have access to the same shared memory in the + original mode except for the 'w+' mode that is automatically + transformed as 'r+' to avoid zeroing the original data upon + instantiation. + + Furthermore large arrays from the parent process are automatically + dumped to a temporary folder on the filesystem such as child + processes to access their content via memmapping (file system + backed shared memory). + + Note: it is important to call the terminate method to collect + the temporary folder used by the pool. + + Parameters + ---------- + processes: int, optional + Number of worker processes running concurrently in the pool. + initializer: callable, optional + Callable executed on worker process creation. + initargs: tuple, optional + Arguments passed to the initializer callable. + temp_folder: (str, callable) optional + If str: + Folder to be used by the pool for memmapping large arrays + for sharing memory with worker processes. If None, this will try in + order: + - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable, + - /dev/shm if the folder exists and is writable: this is a RAMdisk + filesystem available by default on modern Linux distributions, + - the default system temporary folder that can be overridden + with TMP, TMPDIR or TEMP environment variables, typically /tmp + under Unix operating systems. + if callable: + An callable in charge of dynamically resolving a temporary folder + for memmapping large arrays. + max_nbytes int or None, optional, 1e6 by default + Threshold on the size of arrays passed to the workers that + triggers automated memory mapping in temp_folder. + Use None to disable memmapping of large arrays. + mmap_mode: {'r+', 'r', 'w+', 'c'} + Memmapping mode for numpy arrays passed to workers. + See 'max_nbytes' parameter documentation for more details. + forward_reducers: dictionary, optional + Reducers used to pickle objects passed from master to worker + processes: see below. + backward_reducers: dictionary, optional + Reducers used to pickle return values from workers back to the + master process. + verbose: int, optional + Make it possible to monitor how the communication of numpy arrays + with the subprocess is handled (pickling or memmapping) + prewarm: bool or str, optional, "auto" by default. + If True, force a read on newly memmapped array to make sure that OS + pre-cache it in memory. This can be useful to avoid concurrent disk + access when the same data array is passed to different worker + processes. If "auto" (by default), prewarm is set to True, unless the + Linux shared memory partition /dev/shm is available and used as temp + folder. + + `forward_reducers` and `backward_reducers` are expected to be + dictionaries with key/values being `(type, callable)` pairs where + `callable` is a function that give an instance of `type` will return + a tuple `(constructor, tuple_of_objects)` to rebuild an instance out + of the pickled `tuple_of_objects` as would return a `__reduce__` + method. See the standard library documentation on pickling for more + details. + + """ + + def __init__(self, processes=None, temp_folder=None, max_nbytes=1e6, + mmap_mode='r', forward_reducers=None, backward_reducers=None, + verbose=0, context_id=None, prewarm=False, **kwargs): + + if context_id is not None: + warnings.warn('context_id is deprecated and ignored in joblib' + ' 0.9.4 and will be removed in 0.11', + DeprecationWarning) + + manager = TemporaryResourcesManager(temp_folder) + self._temp_folder_manager = manager + + # The usage of a temp_folder_resolver over a simple temp_folder is + # superfluous for multiprocessing pools, as they don't get reused, see + # get_memmapping_executor for more details. We still use it for code + # simplicity. + forward_reducers, backward_reducers = \ + get_memmapping_reducers( + temp_folder_resolver=manager.resolve_temp_folder_name, + max_nbytes=max_nbytes, mmap_mode=mmap_mode, + forward_reducers=forward_reducers, + backward_reducers=backward_reducers, verbose=verbose, + unlink_on_gc_collect=False, prewarm=prewarm) + + poolargs = dict( + processes=processes, + forward_reducers=forward_reducers, + backward_reducers=backward_reducers) + poolargs.update(kwargs) + super(MemmappingPool, self).__init__(**poolargs) + + def terminate(self): + n_retries = 10 + for i in range(n_retries): + try: + super(MemmappingPool, self).terminate() + break + except OSError as e: + if isinstance(e, WindowsError): + # Workaround occasional "[Error 5] Access is denied" issue + # when trying to terminate a process under windows. + sleep(0.1) + if i + 1 == n_retries: + warnings.warn("Failed to terminate worker processes in" + " multiprocessing pool: %r" % e) + + # Clean up the temporary resources as the workers should now be off. + self._temp_folder_manager._clean_temporary_resources() + + @property + def _temp_folder(self): + # Legacy property in tests. could be removed if we refactored the + # memmapping tests. SHOULD ONLY BE USED IN TESTS! + # We cache this property because it is called late in the tests - at + # this point, all context have been unregistered, and + # resolve_temp_folder_name raises an error. + if getattr(self, '_cached_temp_folder', None) is not None: + return self._cached_temp_folder + else: + self._cached_temp_folder = self._temp_folder_manager.resolve_temp_folder_name() # noqa + return self._cached_temp_folder diff --git a/testbed/joblib__joblib/joblib/test/__init__.py b/testbed/joblib__joblib/joblib/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/joblib__joblib/joblib/test/_openmp_test_helper/.gitignore b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2e5170f44c0a277fbb4f671d91a174b536009eb3 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/.gitignore @@ -0,0 +1,3 @@ +*.c +*.so +/build diff --git a/testbed/joblib__joblib/joblib/test/_openmp_test_helper/__init__.py b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/joblib__joblib/joblib/test/_openmp_test_helper/parallel_sum.pyx b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/parallel_sum.pyx new file mode 100644 index 0000000000000000000000000000000000000000..548f5bac8e70416834e110b23bf4bd0f93c81460 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/parallel_sum.pyx @@ -0,0 +1,17 @@ +import cython +cimport openmp +from cython.parallel import prange +from libc.stdlib cimport malloc, free + + +def parallel_sum(int N): + cdef double Ysum = 0 + cdef int i, num_threads + cdef double* X = malloc(N*cython.sizeof(double)) + + for i in prange(N, nogil=True): + num_threads = openmp.omp_get_num_threads() + Ysum += X[i] + + free(X) + return num_threads diff --git a/testbed/joblib__joblib/joblib/test/_openmp_test_helper/setup.py b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd9e59e8f4450c4eba75c14ddc768f53978cad7 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/_openmp_test_helper/setup.py @@ -0,0 +1,33 @@ +"""Helper module to test OpenMP support on Continuous Integration +""" +import os +import sys +from distutils.core import setup +from Cython.Build import cythonize +from distutils.extension import Extension + + +if sys.platform == "darwin": + os.environ["CC"] = "gcc-4.9" + os.environ["CXX"] = "g++-4.9" + +if sys.platform != "win32": + extra_compile_args = ["-ffast-math", "-fopenmp"] + extra_link_args = ['-fopenmp'] +else: + extra_compile_args = ["/openmp"] + extra_link_args = None + +ext_modules = [ + Extension( + "parallel_sum", + ["parallel_sum.pyx"], + extra_compile_args=extra_compile_args, + extra_link_args=extra_link_args + ) +] + +setup( + name='_openmp_test_helper', + ext_modules=cythonize(ext_modules), +) diff --git a/testbed/joblib__joblib/joblib/test/common.py b/testbed/joblib__joblib/joblib/test/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b0ca0c6abd913bc37091ebae4bd6a0b64084d20f --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/common.py @@ -0,0 +1,84 @@ +""" +Small utilities for testing. +""" +import os +import gc +import sys + +from joblib._multiprocessing_helpers import mp +from joblib.testing import SkipTest, skipif + +try: + import lz4 +except ImportError: + lz4 = None + +IS_PYPY = hasattr(sys, "pypy_version_info") + +# A decorator to run tests only when numpy is available +try: + import numpy as np + + def with_numpy(func): + """A decorator to skip tests requiring numpy.""" + return func + +except ImportError: + def with_numpy(func): + """A decorator to skip tests requiring numpy.""" + def my_func(): + raise SkipTest('Test requires numpy') + return my_func + np = None + +# TODO: Turn this back on after refactoring yield based tests in test_hashing +# with_numpy = skipif(not np, reason='Test requires numpy.') + +# we use memory_profiler library for memory consumption checks +try: + from memory_profiler import memory_usage + + def with_memory_profiler(func): + """A decorator to skip tests requiring memory_profiler.""" + return func + + def memory_used(func, *args, **kwargs): + """Compute memory usage when executing func.""" + gc.collect() + mem_use = memory_usage((func, args, kwargs), interval=.001) + return max(mem_use) - min(mem_use) + +except ImportError: + def with_memory_profiler(func): + """A decorator to skip tests requiring memory_profiler.""" + def dummy_func(): + raise SkipTest('Test requires memory_profiler.') + return dummy_func + + memory_usage = memory_used = None + + +def force_gc_pypy(): + # The gc in pypy can be delayed. Force it to test the behavior when it + # will eventually be collected. + if IS_PYPY: + # Run gc.collect() twice to make sure the weakref is collected, as + # mentionned in the pypy doc: + # https://doc.pypy.org/en/latest/config/objspace.usemodules._weakref.html + import gc + gc.collect() + gc.collect() + + +with_multiprocessing = skipif( + mp is None, reason='Needs multiprocessing to run.') + + +with_dev_shm = skipif( + not os.path.exists('/dev/shm'), + reason='This test requires a large /dev/shm shared memory fs.') + +with_lz4 = skipif(lz4 is None, reason='Needs lz4 compression to run') + +without_lz4 = skipif( + lz4 is not None, reason='Needs lz4 not being installed to run') diff --git a/testbed/joblib__joblib/joblib/test/data/__init__.py b/testbed/joblib__joblib/joblib/test/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/joblib__joblib/joblib/test/data/create_numpy_pickle.py b/testbed/joblib__joblib/joblib/test/data/create_numpy_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..ba903d6cc2cd75879eed60ff31ecdf7ffe230d45 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/data/create_numpy_pickle.py @@ -0,0 +1,95 @@ +""" +This script is used to generate test data for joblib/test/test_numpy_pickle.py +""" + +import sys +import re + +# pytest needs to be able to import this module even when numpy is +# not installed +try: + import numpy as np +except ImportError: + np = None + +import joblib + + +def get_joblib_version(joblib_version=joblib.__version__): + """Normalize joblib version by removing suffix. + + >>> get_joblib_version('0.8.4') + '0.8.4' + >>> get_joblib_version('0.8.4b1') + '0.8.4' + >>> get_joblib_version('0.9.dev0') + '0.9' + """ + matches = [re.match(r'(\d+).*', each) + for each in joblib_version.split('.')] + return '.'.join([m.group(1) for m in matches if m is not None]) + + +def write_test_pickle(to_pickle, args): + kwargs = {} + compress = args.compress + method = args.method + joblib_version = get_joblib_version() + py_version = '{0[0]}{0[1]}'.format(sys.version_info) + numpy_version = ''.join(np.__version__.split('.')[:2]) + + # The game here is to generate the right filename according to the options. + body = '_compressed' if (compress and method == 'zlib') else '' + if compress: + if method == 'zlib': + kwargs['compress'] = True + extension = '.gz' + else: + kwargs['compress'] = (method, 3) + extension = '.pkl.{}'.format(method) + if args.cache_size: + kwargs['cache_size'] = 0 + body += '_cache_size' + else: + extension = '.pkl' + + pickle_filename = 'joblib_{}{}_pickle_py{}_np{}{}'.format( + joblib_version, body, py_version, numpy_version, extension) + + try: + joblib.dump(to_pickle, pickle_filename, **kwargs) + except Exception as e: + # With old python version (=< 3.3.), we can arrive there when + # dumping compressed pickle with LzmaFile. + print("Error: cannot generate file '{}' with arguments '{}'. " + "Error was: {}".format(pickle_filename, kwargs, e)) + else: + print("File '{}' generated successfully.".format(pickle_filename)) + + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser(description="Joblib pickle data " + "generator.") + parser.add_argument('--cache_size', action="store_true", + help="Force creation of companion numpy " + "files for pickled arrays.") + parser.add_argument('--compress', action="store_true", + help="Generate compress pickles.") + parser.add_argument('--method', type=str, default='zlib', + choices=['zlib', 'gzip', 'bz2', 'xz', 'lzma', 'lz4'], + help="Set compression method.") + # We need to be specific about dtypes in particular endianness + # because the pickles can be generated on one architecture and + # the tests run on another one. See + # https://github.com/joblib/joblib/issues/279. + to_pickle = [np.arange(5, dtype=np.dtype(' 0 + + +@with_numpy +@with_multiprocessing +def test_parallel_config_params_explicit_set(tmpdir): + with parallel_config(n_jobs=3, max_nbytes=1, temp_folder=tmpdir): + with Parallel(n_jobs=2, prefer="processes", max_nbytes='1M') as p: + assert isinstance(p._backend, LokyBackend) + assert p.n_jobs == 2 + + # Checks that memmapping is disabled + with raises(TypeError, match="Expected np.memmap instance"): + p(delayed(check_memmap)(a) for a in [np.random.random(10)] * 2) + + +@parametrize("param", ["prefer", "require"]) +def test_parallel_config_bad_params(param): + # Check that an error is raised when setting a wrong backend + # hint or constraint + with raises(ValueError, match=f"{param}=wrong is not a valid"): + with parallel_config(**{param: "wrong"}): + Parallel() + + +def test_parallel_config_constructor_params(): + # Check that an error is raised when backend is None + # but backend constructor params are given + with raises(ValueError, match="only supported when backend is not None"): + with parallel_config(inner_max_num_threads=1): + pass + + with raises(ValueError, match="only supported when backend is not None"): + with parallel_config(backend_param=1): + pass + + +def test_parallel_config_nested(): + # Check that nested configuration retrieves the info from the + # parent config and do not reset them. + + with parallel_config(n_jobs=2): + p = Parallel() + assert isinstance(p._backend, BACKENDS[DEFAULT_BACKEND]) + assert p.n_jobs == 2 + + with parallel_config(backend='threading'): + with parallel_config(n_jobs=2): + p = Parallel() + assert isinstance(p._backend, ThreadingBackend) + assert p.n_jobs == 2 + + with parallel_config(verbose=100): + with parallel_config(n_jobs=2): + p = Parallel() + assert p.verbose == 100 + assert p.n_jobs == 2 + + +@with_numpy +@with_multiprocessing +@parametrize('backend', ['multiprocessing', 'threading', + MultiprocessingBackend(), ThreadingBackend()]) +@parametrize("context", [parallel_config, parallel_backend]) +def test_threadpool_limitation_in_child_context_error(context, backend): + + with raises(AssertionError, match=r"does not acc.*inner_max_num_threads"): + context(backend, inner_max_num_threads=1) + + +@parametrize("context", [parallel_config, parallel_backend]) +def test_parallel_n_jobs_none(context): + # Check that n_jobs=None is interpreted as "unset" in Parallel + # non regression test for #1473 + with context(backend="threading", n_jobs=2): + with Parallel(n_jobs=None) as p: + assert p.n_jobs == 2 + + with context(backend="threading"): + default_n_jobs = Parallel().n_jobs + with Parallel(n_jobs=None) as p: + assert p.n_jobs == default_n_jobs + + +@parametrize("context", [parallel_config, parallel_backend]) +def test_parallel_config_n_jobs_none(context): + # Check that n_jobs=None is interpreted as "explicitly set" in + # parallel_(config/backend) + # non regression test for #1473 + with context(backend="threading", n_jobs=2): + with context(backend="threading", n_jobs=None): + # n_jobs=None resets n_jobs to backend's default + with Parallel() as p: + assert p.n_jobs == 1 diff --git a/testbed/joblib__joblib/joblib/test/test_dask.py b/testbed/joblib__joblib/joblib/test/test_dask.py new file mode 100644 index 0000000000000000000000000000000000000000..aebe65525fc55f4593e6c83b5bfd4ffc76d945a7 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_dask.py @@ -0,0 +1,499 @@ +from __future__ import print_function, division, absolute_import +import os +import warnings + +import pytest +from random import random +from uuid import uuid4 +from time import sleep + +from .. import Parallel, delayed, parallel_config +from ..parallel import ThreadingBackend, AutoBatchingMixin +from .._dask import DaskDistributedBackend + +distributed = pytest.importorskip('distributed') +dask = pytest.importorskip('dask') + +# These imports need to be after the pytest.importorskip hence the noqa: E402 +from distributed import Client, LocalCluster, get_client # noqa: E402 +from distributed.metrics import time # noqa: E402 +# Note: pytest requires to manually import all fixtures used in the test +# and their dependencies. +from distributed.utils_test import cluster, inc, cleanup # noqa: E402, F401 + + +def noop(*args, **kwargs): + pass + + +def slow_raise_value_error(condition, duration=0.05): + sleep(duration) + if condition: + raise ValueError("condition evaluated to True") + + +def count_events(event_name, client): + worker_events = client.run(lambda dask_worker: dask_worker.log) + event_counts = {} + for w, events in worker_events.items(): + event_counts[w] = len([event for event in list(events) + if event[1] == event_name]) + return event_counts + + +def test_simple(loop): + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + with parallel_config(backend='dask'): + seq = Parallel()(delayed(inc)(i) for i in range(10)) + assert seq == [inc(i) for i in range(10)] + + with pytest.raises(ValueError): + Parallel()(delayed(slow_raise_value_error)(i == 3) + for i in range(10)) + + seq = Parallel()(delayed(inc)(i) for i in range(10)) + assert seq == [inc(i) for i in range(10)] + + +def test_dask_backend_uses_autobatching(loop): + assert (DaskDistributedBackend.compute_batch_size + is AutoBatchingMixin.compute_batch_size) + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + with parallel_config(backend='dask'): + with Parallel() as parallel: + # The backend should be initialized with a default + # batch size of 1: + backend = parallel._backend + assert isinstance(backend, DaskDistributedBackend) + assert backend.parallel is parallel + assert backend._effective_batch_size == 1 + + # Launch many short tasks that should trigger + # auto-batching: + parallel( + delayed(lambda: None)() + for _ in range(int(1e4)) + ) + assert backend._effective_batch_size > 10 + + +def random2(): + return random() + + +def test_dont_assume_function_purity(loop): + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + with parallel_config(backend='dask'): + x, y = Parallel()(delayed(random2)() for i in range(2)) + assert x != y + + +@pytest.mark.parametrize("mixed", [True, False]) +def test_dask_funcname(loop, mixed): + from joblib._dask import Batch + if not mixed: + tasks = [delayed(inc)(i) for i in range(4)] + batch_repr = 'batch_of_inc_4_calls' + else: + tasks = [ + delayed(abs)(i) if i % 2 else delayed(inc)(i) for i in range(4) + ] + batch_repr = 'mixed_batch_of_inc_4_calls' + + assert repr(Batch(tasks)) == batch_repr + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: + with parallel_config(backend='dask'): + _ = Parallel(batch_size=2, pre_dispatch='all')(tasks) + + def f(dask_scheduler): + return list(dask_scheduler.transition_log) + batch_repr = batch_repr.replace('4', '2') + log = client.run_on_scheduler(f) + assert all('batch_of_inc' in tup[0] for tup in log) + + +def test_no_undesired_distributed_cache_hit(): + # Dask has a pickle cache for callables that are called many times. Because + # the dask backends used to wrap both the functions and the arguments + # under instances of the Batch callable class this caching mechanism could + # lead to bugs as described in: https://github.com/joblib/joblib/pull/1055 + # The joblib-dask backend has been refactored to avoid bundling the + # arguments as an attribute of the Batch instance to avoid this problem. + # This test serves as non-regression problem. + + # Use a large number of input arguments to give the AutoBatchingMixin + # enough tasks to kick-in. + lists = [[] for _ in range(100)] + np = pytest.importorskip('numpy') + X = np.arange(int(1e6)) + + def isolated_operation(list_, data=None): + if data is not None: + np.testing.assert_array_equal(data, X) + list_.append(uuid4().hex) + return list_ + + cluster = LocalCluster(n_workers=1, threads_per_worker=2) + client = Client(cluster) + try: + with parallel_config(backend='dask'): + # dispatches joblib.parallel.BatchedCalls + res = Parallel()( + delayed(isolated_operation)(list_) for list_ in lists + ) + + # The original arguments should not have been mutated as the mutation + # happens in the dask worker process. + assert lists == [[] for _ in range(100)] + + # Here we did not pass any large numpy array as argument to + # isolated_operation so no scattering event should happen under the + # hood. + counts = count_events('receive-from-scatter', client) + assert sum(counts.values()) == 0 + assert all([len(r) == 1 for r in res]) + + with parallel_config(backend='dask'): + # Append a large array which will be scattered by dask, and + # dispatch joblib._dask.Batch + res = Parallel()( + delayed(isolated_operation)(list_, data=X) for list_ in lists + ) + + # This time, auto-scattering should have kicked it. + counts = count_events('receive-from-scatter', client) + assert sum(counts.values()) > 0 + assert all([len(r) == 1 for r in res]) + finally: + client.close(timeout=30) + cluster.close(timeout=30) + + +class CountSerialized(object): + def __init__(self, x): + self.x = x + self.count = 0 + + def __add__(self, other): + return self.x + getattr(other, 'x', other) + + __radd__ = __add__ + + def __reduce__(self): + self.count += 1 + return (CountSerialized, (self.x,)) + + +def add5(a, b, c, d=0, e=0): + return a + b + c + d + e + + +def test_manual_scatter(loop): + x = CountSerialized(1) + y = CountSerialized(2) + z = CountSerialized(3) + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + with parallel_config(backend='dask', scatter=[x, y]): + f = delayed(add5) + tasks = [f(x, y, z, d=4, e=5), + f(x, z, y, d=5, e=4), + f(y, x, z, d=x, e=5), + f(z, z, x, d=z, e=y)] + expected = [func(*args, **kwargs) + for func, args, kwargs in tasks] + results = Parallel()(tasks) + + # Scatter must take a list/tuple + with pytest.raises(TypeError): + with parallel_config(backend='dask', loop=loop, scatter=1): + pass + + assert results == expected + + # Scattered variables only serialized once + assert x.count == 1 + assert y.count == 1 + # Depending on the version of distributed, the unscattered z variable + # is either pickled 4 or 6 times, possibly because of the memoization + # of objects that appear several times in the arguments of a delayed + # task. + assert z.count in (4, 6) + + +# When the same IOLoop is used for multiple clients in a row, use +# loop_in_thread instead of loop to prevent the Client from closing it. See +# dask/distributed #4112 +def test_auto_scatter(loop_in_thread): + np = pytest.importorskip('numpy') + data1 = np.ones(int(1e4), dtype=np.uint8) + data2 = np.ones(int(1e4), dtype=np.uint8) + data_to_process = ([data1] * 3) + ([data2] * 3) + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop_in_thread) as client: + with parallel_config(backend='dask'): + # Passing the same data as arg and kwarg triggers a single + # scatter operation whose result is reused. + Parallel()(delayed(noop)(data, data, i, opt=data) + for i, data in enumerate(data_to_process)) + # By default large array are automatically scattered with + # broadcast=1 which means that one worker must directly receive + # the data from the scatter operation once. + counts = count_events('receive-from-scatter', client) + assert counts[a['address']] + counts[b['address']] == 2 + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop_in_thread) as client: + with parallel_config(backend='dask'): + Parallel()(delayed(noop)(data1[:3], i) for i in range(5)) + # Small arrays are passed within the task definition without going + # through a scatter operation. + counts = count_events('receive-from-scatter', client) + assert counts[a['address']] == 0 + assert counts[b['address']] == 0 + + +@pytest.mark.parametrize("retry_no", list(range(2))) +def test_nested_scatter(loop, retry_no): + + np = pytest.importorskip('numpy') + + NUM_INNER_TASKS = 10 + NUM_OUTER_TASKS = 10 + + def my_sum(x, i, j): + return np.sum(x) + + def outer_function_joblib(array, i): + client = get_client() # noqa + with parallel_config(backend="dask"): + results = Parallel()( + delayed(my_sum)(array[j:], i, j) for j in range( + NUM_INNER_TASKS) + ) + return sum(results) + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as _: + with parallel_config(backend="dask"): + my_array = np.ones(10000) + _ = Parallel()( + delayed(outer_function_joblib)( + my_array[i:], i) for i in range(NUM_OUTER_TASKS) + ) + + +def test_nested_backend_context_manager(loop_in_thread): + def get_nested_pids(): + pids = set(Parallel(n_jobs=2)(delayed(os.getpid)() for _ in range(2))) + pids |= set(Parallel(n_jobs=2)(delayed(os.getpid)() for _ in range(2))) + return pids + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop_in_thread) as client: + with parallel_config(backend='dask'): + pid_groups = Parallel(n_jobs=2)( + delayed(get_nested_pids)() + for _ in range(10) + ) + for pid_group in pid_groups: + assert len(set(pid_group)) <= 2 + + # No deadlocks + with Client(s['address'], loop=loop_in_thread) as client: # noqa: F841 + with parallel_config(backend='dask'): + pid_groups = Parallel(n_jobs=2)( + delayed(get_nested_pids)() + for _ in range(10) + ) + for pid_group in pid_groups: + assert len(set(pid_group)) <= 2 + + +def test_nested_backend_context_manager_implicit_n_jobs(loop): + # Check that Parallel with no explicit n_jobs value automatically selects + # all the dask workers, including in nested calls. + + def _backend_type(p): + return p._backend.__class__.__name__ + + def get_nested_implicit_n_jobs(): + with Parallel() as p: + return _backend_type(p), p.n_jobs + + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + with parallel_config(backend='dask'): + with Parallel() as p: + assert _backend_type(p) == "DaskDistributedBackend" + assert p.n_jobs == -1 + all_nested_n_jobs = p( + delayed(get_nested_implicit_n_jobs)() + for _ in range(2) + ) + for backend_type, nested_n_jobs in all_nested_n_jobs: + assert backend_type == "DaskDistributedBackend" + assert nested_n_jobs == -1 + + +def test_errors(loop): + with pytest.raises(ValueError) as info: + with parallel_config(backend='dask'): + pass + + assert "create a dask client" in str(info.value).lower() + + +def test_correct_nested_backend(loop): + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + # No requirement, should be us + with parallel_config(backend='dask'): + result = Parallel(n_jobs=2)( + delayed(outer)(nested_require=None) for _ in range(1)) + assert isinstance(result[0][0][0], DaskDistributedBackend) + + # Require threads, should be threading + with parallel_config(backend='dask'): + result = Parallel(n_jobs=2)( + delayed(outer)(nested_require='sharedmem') + for _ in range(1)) + assert isinstance(result[0][0][0], ThreadingBackend) + + +def outer(nested_require): + return Parallel(n_jobs=2, prefer='threads')( + delayed(middle)(nested_require) for _ in range(1) + ) + + +def middle(require): + return Parallel(n_jobs=2, require=require)( + delayed(inner)() for _ in range(1) + ) + + +def inner(): + return Parallel()._backend + + +def test_secede_with_no_processes(loop): + # https://github.com/dask/distributed/issues/1775 + with Client(loop=loop, processes=False, set_as_default=True): + with parallel_config(backend='dask'): + Parallel(n_jobs=4)(delayed(id)(i) for i in range(2)) + + +def _worker_address(_): + from distributed import get_worker + return get_worker().address + + +def test_dask_backend_keywords(loop): + with cluster() as (s, [a, b]): + with Client(s['address'], loop=loop) as client: # noqa: F841 + with parallel_config(backend='dask', workers=a['address']): + seq = Parallel()( + delayed(_worker_address)(i) for i in range(10)) + assert seq == [a['address']] * 10 + + with parallel_config(backend='dask', workers=b['address']): + seq = Parallel()( + delayed(_worker_address)(i) for i in range(10)) + assert seq == [b['address']] * 10 + + +def test_scheduler_tasks_cleanup(loop): + with Client(processes=False, loop=loop) as client: + with parallel_config(backend='dask'): + Parallel()(delayed(inc)(i) for i in range(10)) + + start = time() + while client.cluster.scheduler.tasks: + sleep(0.01) + assert time() < start + 5 + + assert not client.futures + + +@pytest.mark.parametrize("cluster_strategy", ["adaptive", "late_scaling"]) +@pytest.mark.skipif( + distributed.__version__ <= '2.1.1' and distributed.__version__ >= '1.28.0', + reason="distributed bug - https://github.com/dask/distributed/pull/2841") +def test_wait_for_workers(cluster_strategy): + cluster = LocalCluster(n_workers=0, processes=False, threads_per_worker=2) + client = Client(cluster) + if cluster_strategy == "adaptive": + cluster.adapt(minimum=0, maximum=2) + elif cluster_strategy == "late_scaling": + # Tell the cluster to start workers but this is a non-blocking call + # and new workers might take time to connect. In this case the Parallel + # call should wait for at least one worker to come up before starting + # to schedule work. + cluster.scale(2) + try: + with parallel_config(backend='dask'): + # The following should wait a bit for at least one worker to + # become available. + Parallel()(delayed(inc)(i) for i in range(10)) + finally: + client.close() + cluster.close() + + +def test_wait_for_workers_timeout(): + # Start a cluster with 0 worker: + cluster = LocalCluster(n_workers=0, processes=False, threads_per_worker=2) + client = Client(cluster) + try: + with parallel_config(backend='dask', wait_for_workers_timeout=0.1): + # Short timeout: DaskDistributedBackend + msg = "DaskDistributedBackend has no worker after 0.1 seconds." + with pytest.raises(TimeoutError, match=msg): + Parallel()(delayed(inc)(i) for i in range(10)) + + with parallel_config(backend='dask', wait_for_workers_timeout=0): + # No timeout: fallback to generic joblib failure: + msg = "DaskDistributedBackend has no active worker" + with pytest.raises(RuntimeError, match=msg): + Parallel()(delayed(inc)(i) for i in range(10)) + finally: + client.close() + cluster.close() + + +@pytest.mark.parametrize("backend", ["loky", "multiprocessing"]) +def test_joblib_warning_inside_dask_daemonic_worker(backend): + cluster = LocalCluster(n_workers=2) + client = Client(cluster) + try: + + def func_using_joblib_parallel(): + # Somehow trying to check the warning type here (e.g. with + # pytest.warns(UserWarning)) make the test hang. Work-around: + # return the warning record to the client and the warning check is + # done client-side. + with warnings.catch_warnings(record=True) as record: + Parallel(n_jobs=2, backend=backend)( + delayed(inc)(i) for i in range(10)) + + return record + + fut = client.submit(func_using_joblib_parallel) + record = fut.result() + + assert len(record) == 1 + warning = record[0].message + assert isinstance(warning, UserWarning) + assert "distributed.worker.daemon" in str(warning) + finally: + client.close(timeout=30) + cluster.close(timeout=30) diff --git a/testbed/joblib__joblib/joblib/test/test_disk.py b/testbed/joblib__joblib/joblib/test/test_disk.py new file mode 100644 index 0000000000000000000000000000000000000000..b825a8b3a5c18a3114f34ed9d7c90cce62799085 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_disk.py @@ -0,0 +1,71 @@ +""" +Unit tests for the disk utilities. +""" + +# Authors: Gael Varoquaux +# Lars Buitinck +# Copyright (c) 2010 Gael Varoquaux +# License: BSD Style, 3 clauses. + +from __future__ import with_statement +import array +import os + +from joblib.disk import disk_used, memstr_to_bytes, mkdirp, rm_subdirs +from joblib.testing import parametrize, raises + +############################################################################### + + +def test_disk_used(tmpdir): + cachedir = tmpdir.strpath + # Not write a file that is 1M big in this directory, and check the + # size. The reason we use such a big file is that it makes us robust + # to errors due to block allocation. + a = array.array('i') + sizeof_i = a.itemsize + target_size = 1024 + n = int(target_size * 1024 / sizeof_i) + a = array.array('i', n * (1,)) + with open(os.path.join(cachedir, 'test'), 'wb') as output: + a.tofile(output) + assert disk_used(cachedir) >= target_size + assert disk_used(cachedir) < target_size + 12 + + +@parametrize('text,value', + [('80G', 80 * 1024 ** 3), + ('1.4M', int(1.4 * 1024 ** 2)), + ('120M', 120 * 1024 ** 2), + ('53K', 53 * 1024)]) +def test_memstr_to_bytes(text, value): + assert memstr_to_bytes(text) == value + + +@parametrize('text,exception,regex', + [('fooG', ValueError, r'Invalid literal for size.*fooG.*'), + ('1.4N', ValueError, r'Invalid literal for size.*1.4N.*')]) +def test_memstr_to_bytes_exception(text, exception, regex): + with raises(exception) as excinfo: + memstr_to_bytes(text) + assert excinfo.match(regex) + + +def test_mkdirp(tmpdir): + mkdirp(os.path.join(tmpdir.strpath, 'ham')) + mkdirp(os.path.join(tmpdir.strpath, 'ham')) + mkdirp(os.path.join(tmpdir.strpath, 'spam', 'spam')) + + # Not all OSErrors are ignored + with raises(OSError): + mkdirp('') + + +def test_rm_subdirs(tmpdir): + sub_path = os.path.join(tmpdir.strpath, "am", "stram") + full_path = os.path.join(sub_path, "gram") + mkdirp(os.path.join(full_path)) + + rm_subdirs(sub_path) + assert os.path.exists(sub_path) + assert not os.path.exists(full_path) diff --git a/testbed/joblib__joblib/joblib/test/test_func_inspect.py b/testbed/joblib__joblib/joblib/test/test_func_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..dba237d48578e5d6386e67e80f3e6d31761108d6 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_func_inspect.py @@ -0,0 +1,310 @@ +""" +Test the func_inspect module. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import functools + +from joblib.func_inspect import filter_args, get_func_name, get_func_code +from joblib.func_inspect import _clean_win_chars, format_signature +from joblib.memory import Memory +from joblib.test.common import with_numpy +from joblib.testing import fixture, parametrize, raises + + +############################################################################### +# Module-level functions and fixture, for tests +def f(x, y=0): + pass + + +def g(x): + pass + + +def h(x, y=0, *args, **kwargs): + pass + + +def i(x=1): + pass + + +def j(x, y, **kwargs): + pass + + +def k(*args, **kwargs): + pass + + +def m1(x, *, y): + pass + + +def m2(x, *, y, z=3): + pass + + +@fixture(scope='module') +def cached_func(tmpdir_factory): + # Create a Memory object to test decorated functions. + # We should be careful not to call the decorated functions, so that + # cache directories are not created in the temp dir. + cachedir = tmpdir_factory.mktemp("joblib_test_func_inspect") + mem = Memory(cachedir.strpath) + + @mem.cache + def cached_func_inner(x): + return x + + return cached_func_inner + + +class Klass(object): + + def f(self, x): + return x + + +############################################################################### +# Tests + +@parametrize('func,args,filtered_args', + [(f, [[], (1, )], {'x': 1, 'y': 0}), + (f, [['x'], (1, )], {'y': 0}), + (f, [['y'], (0, )], {'x': 0}), + (f, [['y'], (0, ), {'y': 1}], {'x': 0}), + (f, [['x', 'y'], (0, )], {}), + (f, [[], (0,), {'y': 1}], {'x': 0, 'y': 1}), + (f, [['y'], (), {'x': 2, 'y': 1}], {'x': 2}), + (g, [[], (), {'x': 1}], {'x': 1}), + (i, [[], (2, )], {'x': 2})]) +def test_filter_args(func, args, filtered_args): + assert filter_args(func, *args) == filtered_args + + +def test_filter_args_method(): + obj = Klass() + assert filter_args(obj.f, [], (1, )) == {'x': 1, 'self': obj} + + +@parametrize('func,args,filtered_args', + [(h, [[], (1, )], + {'x': 1, 'y': 0, '*': [], '**': {}}), + (h, [[], (1, 2, 3, 4)], + {'x': 1, 'y': 2, '*': [3, 4], '**': {}}), + (h, [[], (1, 25), {'ee': 2}], + {'x': 1, 'y': 25, '*': [], '**': {'ee': 2}}), + (h, [['*'], (1, 2, 25), {'ee': 2}], + {'x': 1, 'y': 2, '**': {'ee': 2}})]) +def test_filter_varargs(func, args, filtered_args): + assert filter_args(func, *args) == filtered_args + + +test_filter_kwargs_extra_params = [ + (m1, [[], (1,), {'y': 2}], {'x': 1, 'y': 2}), + (m2, [[], (1,), {'y': 2}], {'x': 1, 'y': 2, 'z': 3}) +] + + +@parametrize('func,args,filtered_args', + [(k, [[], (1, 2), {'ee': 2}], + {'*': [1, 2], '**': {'ee': 2}}), + (k, [[], (3, 4)], + {'*': [3, 4], '**': {}})] + + test_filter_kwargs_extra_params) +def test_filter_kwargs(func, args, filtered_args): + assert filter_args(func, *args) == filtered_args + + +def test_filter_args_2(): + assert (filter_args(j, [], (1, 2), {'ee': 2}) == + {'x': 1, 'y': 2, '**': {'ee': 2}}) + + ff = functools.partial(f, 1) + # filter_args has to special-case partial + assert filter_args(ff, [], (1, )) == {'*': [1], '**': {}} + assert filter_args(ff, ['y'], (1, )) == {'*': [1], '**': {}} + + +@parametrize('func,funcname', [(f, 'f'), (g, 'g'), + (cached_func, 'cached_func')]) +def test_func_name(func, funcname): + # Check that we are not confused by decoration + # here testcase 'cached_func' is the function itself + assert get_func_name(func)[1] == funcname + + +def test_func_name_on_inner_func(cached_func): + # Check that we are not confused by decoration + # here testcase 'cached_func' is the 'cached_func_inner' function + # returned by 'cached_func' fixture + assert get_func_name(cached_func)[1] == 'cached_func_inner' + + +def test_func_name_collision_on_inner_func(): + # Check that two functions defining and caching an inner function + # with the same do not cause (module, name) collision + def f(): + def inner_func(): + return # pragma: no cover + return get_func_name(inner_func) + + def g(): + def inner_func(): + return # pragma: no cover + return get_func_name(inner_func) + + module, name = f() + other_module, other_name = g() + + assert name == other_name + assert module != other_module + + +def test_func_inspect_errors(): + # Check that func_inspect is robust and will work on weird objects + assert get_func_name('a'.lower)[-1] == 'lower' + assert get_func_code('a'.lower)[1:] == (None, -1) + ff = lambda x: x # noqa: E731 + assert get_func_name(ff, win_characters=False)[-1] == '' + assert get_func_code(ff)[1] == __file__.replace('.pyc', '.py') + # Simulate a function defined in __main__ + ff.__module__ = '__main__' + assert get_func_name(ff, win_characters=False)[-1] == '' + assert get_func_code(ff)[1] == __file__.replace('.pyc', '.py') + + +def func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'): + pass + + +def func_with_signature(a: int, b: int) -> None: + pass + + +def test_filter_args_edge_cases(): + assert ( + filter_args(func_with_kwonly_args, [], (1, 2), + {'kw1': 3, 'kw2': 4}) == + {'a': 1, 'b': 2, 'kw1': 3, 'kw2': 4}) + + # filter_args doesn't care about keyword-only arguments so you + # can pass 'kw1' into *args without any problem + with raises(ValueError) as excinfo: + filter_args(func_with_kwonly_args, [], (1, 2, 3), {'kw2': 2}) + excinfo.match("Keyword-only parameter 'kw1' was passed as positional " + "parameter") + + assert ( + filter_args(func_with_kwonly_args, ['b', 'kw2'], (1, 2), + {'kw1': 3, 'kw2': 4}) == + {'a': 1, 'kw1': 3}) + + assert (filter_args(func_with_signature, ['b'], (1, 2)) == {'a': 1}) + + +def test_bound_methods(): + """ Make sure that calling the same method on two different instances + of the same class does resolv to different signatures. + """ + a = Klass() + b = Klass() + assert filter_args(a.f, [], (1, )) != filter_args(b.f, [], (1, )) + + +@parametrize('exception,regex,func,args', + [(ValueError, 'ignore_lst must be a list of parameters to ignore', + f, ['bar', (None, )]), + (ValueError, r'Ignore list: argument \'(.*)\' is not defined', + g, [['bar'], (None, )]), + (ValueError, 'Wrong number of arguments', + h, [[]])]) +def test_filter_args_error_msg(exception, regex, func, args): + """ Make sure that filter_args returns decent error messages, for the + sake of the user. + """ + with raises(exception) as excinfo: + filter_args(func, *args) + excinfo.match(regex) + + +def test_filter_args_no_kwargs_mutation(): + """None-regression test against 0.12.0 changes. + + https://github.com/joblib/joblib/pull/75 + + Make sure filter args doesn't mutate the kwargs dict that gets passed in. + """ + kwargs = {'x': 0} + filter_args(g, [], [], kwargs) + assert kwargs == {'x': 0} + + +def test_clean_win_chars(): + string = r'C:\foo\bar\main.py' + mangled_string = _clean_win_chars(string) + for char in ('\\', ':', '<', '>', '!'): + assert char not in mangled_string + + +@parametrize('func,args,kwargs,sgn_expected', + [(g, [list(range(5))], {}, 'g([0, 1, 2, 3, 4])'), + (k, [1, 2, (3, 4)], {'y': True}, 'k(1, 2, (3, 4), y=True)')]) +def test_format_signature(func, args, kwargs, sgn_expected): + # Test signature formatting. + path, sgn_result = format_signature(func, *args, **kwargs) + assert sgn_result == sgn_expected + + +def test_format_signature_long_arguments(): + shortening_threshold = 1500 + # shortening gets it down to 700 characters but there is the name + # of the function in the signature and a few additional things + # like dots for the ellipsis + shortening_target = 700 + 10 + + arg = 'a' * shortening_threshold + _, signature = format_signature(h, arg) + assert len(signature) < shortening_target + + nb_args = 5 + args = [arg for _ in range(nb_args)] + _, signature = format_signature(h, *args) + assert len(signature) < shortening_target * nb_args + + kwargs = {str(i): arg for i, arg in enumerate(args)} + _, signature = format_signature(h, **kwargs) + assert len(signature) < shortening_target * nb_args + + _, signature = format_signature(h, *args, **kwargs) + assert len(signature) < shortening_target * 2 * nb_args + + +@with_numpy +def test_format_signature_numpy(): + """ Test the format signature formatting with numpy. + """ + + +def test_special_source_encoding(): + from joblib.test.test_func_inspect_special_encoding import big5_f + func_code, source_file, first_line = get_func_code(big5_f) + assert first_line == 5 + assert "def big5_f():" in func_code + assert "test_func_inspect_special_encoding" in source_file + + +def _get_code(): + from joblib.test.test_func_inspect_special_encoding import big5_f + return get_func_code(big5_f)[0] + + +def test_func_code_consistency(): + from joblib.parallel import Parallel, delayed + codes = Parallel(n_jobs=2)(delayed(_get_code)() for _ in range(5)) + assert len(set(codes)) == 1 diff --git a/testbed/joblib__joblib/joblib/test/test_func_inspect_special_encoding.py b/testbed/joblib__joblib/joblib/test/test_func_inspect_special_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..6c41a59a6900ced36050bf357359c1164a11fdbe --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_func_inspect_special_encoding.py @@ -0,0 +1,9 @@ +# -*- coding: big5 -*- + + +# Some Traditional Chinese characters: @Ǥr +def big5_f(): + """Ωժ + """ + # + return 0 diff --git a/testbed/joblib__joblib/joblib/test/test_hashing.py b/testbed/joblib__joblib/joblib/test/test_hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..85593d297f6e2387c58cad8d5bceba4d21b1c0aa --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_hashing.py @@ -0,0 +1,495 @@ +""" +Test the hashing module. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import time +import hashlib +import sys +import gc +import io +import collections +import itertools +import pickle +import random +from concurrent.futures import ProcessPoolExecutor +from decimal import Decimal + +from joblib.hashing import hash +from joblib.func_inspect import filter_args +from joblib.memory import Memory +from joblib.testing import raises, skipif, fixture, parametrize +from joblib.test.common import np, with_numpy + + +def unicode(s): + return s + + +############################################################################### +# Helper functions for the tests +def time_func(func, *args): + """ Time function func on *args. + """ + times = list() + for _ in range(3): + t1 = time.time() + func(*args) + times.append(time.time() - t1) + return min(times) + + +def relative_time(func1, func2, *args): + """ Return the relative time between func1 and func2 applied on + *args. + """ + time_func1 = time_func(func1, *args) + time_func2 = time_func(func2, *args) + relative_diff = 0.5 * (abs(time_func1 - time_func2) + / (time_func1 + time_func2)) + return relative_diff + + +class Klass(object): + + def f(self, x): + return x + + +class KlassWithCachedMethod(object): + + def __init__(self, cachedir): + mem = Memory(location=cachedir) + self.f = mem.cache(self.f) + + def f(self, x): + return x + + +############################################################################### +# Tests + +input_list = [1, 2, 1., 2., 1 + 1j, 2. + 1j, + 'a', 'b', + (1,), (1, 1,), [1, ], [1, 1, ], + {1: 1}, {1: 2}, {2: 1}, + None, + gc.collect, + [1, ].append, + # Next 2 sets have unorderable elements in python 3. + set(('a', 1)), + set(('a', 1, ('a', 1))), + # Next 2 dicts have unorderable type of keys in python 3. + {'a': 1, 1: 2}, + {'a': 1, 1: 2, 'd': {'a': 1}}] + + +@parametrize('obj1', input_list) +@parametrize('obj2', input_list) +def test_trivial_hash(obj1, obj2): + """Smoke test hash on various types.""" + # Check that 2 objects have the same hash only if they are the same. + are_hashes_equal = hash(obj1) == hash(obj2) + are_objs_identical = obj1 is obj2 + assert are_hashes_equal == are_objs_identical + + +def test_hash_methods(): + # Check that hashing instance methods works + a = io.StringIO(unicode('a')) + assert hash(a.flush) == hash(a.flush) + a1 = collections.deque(range(10)) + a2 = collections.deque(range(9)) + assert hash(a1.extend) != hash(a2.extend) + + +@fixture(scope='function') +@with_numpy +def three_np_arrays(): + rnd = np.random.RandomState(0) + arr1 = rnd.random_sample((10, 10)) + arr2 = arr1.copy() + arr3 = arr2.copy() + arr3[0] += 1 + return arr1, arr2, arr3 + + +def test_hash_numpy_arrays(three_np_arrays): + arr1, arr2, arr3 = three_np_arrays + + for obj1, obj2 in itertools.product(three_np_arrays, repeat=2): + are_hashes_equal = hash(obj1) == hash(obj2) + are_arrays_equal = np.all(obj1 == obj2) + assert are_hashes_equal == are_arrays_equal + + assert hash(arr1) != hash(arr1.T) + + +def test_hash_numpy_dict_of_arrays(three_np_arrays): + arr1, arr2, arr3 = three_np_arrays + + d1 = {1: arr1, 2: arr2} + d2 = {1: arr2, 2: arr1} + d3 = {1: arr2, 2: arr3} + + assert hash(d1) == hash(d2) + assert hash(d1) != hash(d3) + + +@with_numpy +@parametrize('dtype', ['datetime64[s]', 'timedelta64[D]']) +def test_numpy_datetime_array(dtype): + # memoryview is not supported for some dtypes e.g. datetime64 + # see https://github.com/joblib/joblib/issues/188 for more details + a_hash = hash(np.arange(10)) + array = np.arange(0, 10, dtype=dtype) + assert hash(array) != a_hash + + +@with_numpy +def test_hash_numpy_noncontiguous(): + a = np.asarray(np.arange(6000).reshape((1000, 2, 3)), + order='F')[:, :1, :] + b = np.ascontiguousarray(a) + assert hash(a) != hash(b) + + c = np.asfortranarray(a) + assert hash(a) != hash(c) + + +@with_numpy +@parametrize('coerce_mmap', [True, False]) +def test_hash_memmap(tmpdir, coerce_mmap): + """Check that memmap and arrays hash identically if coerce_mmap is True.""" + filename = tmpdir.join('memmap_temp').strpath + try: + m = np.memmap(filename, shape=(10, 10), mode='w+') + a = np.asarray(m) + are_hashes_equal = (hash(a, coerce_mmap=coerce_mmap) == + hash(m, coerce_mmap=coerce_mmap)) + assert are_hashes_equal == coerce_mmap + finally: + if 'm' in locals(): + del m + # Force a garbage-collection cycle, to be certain that the + # object is delete, and we don't run in a problem under + # Windows with a file handle still open. + gc.collect() + + +@with_numpy +@skipif(sys.platform == 'win32', reason='This test is not stable under windows' + ' for some reason') +def test_hash_numpy_performance(): + """ Check the performance of hashing numpy arrays: + + In [22]: a = np.random.random(1000000) + + In [23]: %timeit hashlib.md5(a).hexdigest() + 100 loops, best of 3: 20.7 ms per loop + + In [24]: %timeit hashlib.md5(pickle.dumps(a, protocol=2)).hexdigest() + 1 loops, best of 3: 73.1 ms per loop + + In [25]: %timeit hashlib.md5(cPickle.dumps(a, protocol=2)).hexdigest() + 10 loops, best of 3: 53.9 ms per loop + + In [26]: %timeit hash(a) + 100 loops, best of 3: 20.8 ms per loop + """ + rnd = np.random.RandomState(0) + a = rnd.random_sample(1000000) + + def md5_hash(x): + return hashlib.md5(memoryview(x)).hexdigest() + + relative_diff = relative_time(md5_hash, hash, a) + assert relative_diff < 0.3 + + # Check that hashing an tuple of 3 arrays takes approximately + # 3 times as much as hashing one array + time_hashlib = 3 * time_func(md5_hash, a) + time_hash = time_func(hash, (a, a, a)) + relative_diff = 0.5 * (abs(time_hash - time_hashlib) + / (time_hash + time_hashlib)) + assert relative_diff < 0.3 + + +def test_bound_methods_hash(): + """ Make sure that calling the same method on two different instances + of the same class does resolve to the same hashes. + """ + a = Klass() + b = Klass() + assert (hash(filter_args(a.f, [], (1, ))) == + hash(filter_args(b.f, [], (1, )))) + + +def test_bound_cached_methods_hash(tmpdir): + """ Make sure that calling the same _cached_ method on two different + instances of the same class does resolve to the same hashes. + """ + a = KlassWithCachedMethod(tmpdir.strpath) + b = KlassWithCachedMethod(tmpdir.strpath) + assert (hash(filter_args(a.f.func, [], (1, ))) == + hash(filter_args(b.f.func, [], (1, )))) + + +@with_numpy +def test_hash_object_dtype(): + """ Make sure that ndarrays with dtype `object' hash correctly.""" + + a = np.array([np.arange(i) for i in range(6)], dtype=object) + b = np.array([np.arange(i) for i in range(6)], dtype=object) + + assert hash(a) == hash(b) + + +@with_numpy +def test_numpy_scalar(): + # Numpy scalars are built from compiled functions, and lead to + # strange pickling paths explored, that can give hash collisions + a = np.float64(2.0) + b = np.float64(3.0) + assert hash(a) != hash(b) + + +def test_dict_hash(tmpdir): + # Check that dictionaries hash consistently, even though the ordering + # of the keys is not guaranteed + k = KlassWithCachedMethod(tmpdir.strpath) + + d = {'#s12069__c_maps.nii.gz': [33], + '#s12158__c_maps.nii.gz': [33], + '#s12258__c_maps.nii.gz': [33], + '#s12277__c_maps.nii.gz': [33], + '#s12300__c_maps.nii.gz': [33], + '#s12401__c_maps.nii.gz': [33], + '#s12430__c_maps.nii.gz': [33], + '#s13817__c_maps.nii.gz': [33], + '#s13903__c_maps.nii.gz': [33], + '#s13916__c_maps.nii.gz': [33], + '#s13981__c_maps.nii.gz': [33], + '#s13982__c_maps.nii.gz': [33], + '#s13983__c_maps.nii.gz': [33]} + + a = k.f(d) + b = k.f(a) + + assert hash(a) == hash(b) + + +def test_set_hash(tmpdir): + # Check that sets hash consistently, even though their ordering + # is not guaranteed + k = KlassWithCachedMethod(tmpdir.strpath) + + s = set(['#s12069__c_maps.nii.gz', + '#s12158__c_maps.nii.gz', + '#s12258__c_maps.nii.gz', + '#s12277__c_maps.nii.gz', + '#s12300__c_maps.nii.gz', + '#s12401__c_maps.nii.gz', + '#s12430__c_maps.nii.gz', + '#s13817__c_maps.nii.gz', + '#s13903__c_maps.nii.gz', + '#s13916__c_maps.nii.gz', + '#s13981__c_maps.nii.gz', + '#s13982__c_maps.nii.gz', + '#s13983__c_maps.nii.gz']) + + a = k.f(s) + b = k.f(a) + + assert hash(a) == hash(b) + + +def test_set_decimal_hash(): + # Check that sets containing decimals hash consistently, even though + # ordering is not guaranteed + assert (hash(set([Decimal(0), Decimal('NaN')])) == + hash(set([Decimal('NaN'), Decimal(0)]))) + + +def test_string(): + # Test that we obtain the same hash for object owning several strings, + # whatever the past of these strings (which are immutable in Python) + string = 'foo' + a = {string: 'bar'} + b = {string: 'bar'} + c = pickle.loads(pickle.dumps(b)) + assert hash([a, b]) == hash([a, c]) + + +@with_numpy +def test_numpy_dtype_pickling(): + # numpy dtype hashing is tricky to get right: see #231, #239, #251 #1080, + # #1082, and explanatory comments inside + # ``joblib.hashing.NumpyHasher.save``. + + # In this test, we make sure that the pickling of numpy dtypes is robust to + # object identity and object copy. + + dt1 = np.dtype('f4') + dt2 = np.dtype('f4') + + # simple dtypes objects are interned + assert dt1 is dt2 + assert hash(dt1) == hash(dt2) + + dt1_roundtripped = pickle.loads(pickle.dumps(dt1)) + assert dt1 is not dt1_roundtripped + assert hash(dt1) == hash(dt1_roundtripped) + + assert hash([dt1, dt1]) == hash([dt1_roundtripped, dt1_roundtripped]) + assert hash([dt1, dt1]) == hash([dt1, dt1_roundtripped]) + + complex_dt1 = np.dtype( + [('name', np.str_, 16), ('grades', np.float64, (2,))] + ) + complex_dt2 = np.dtype( + [('name', np.str_, 16), ('grades', np.float64, (2,))] + ) + + # complex dtypes objects are not interned + assert hash(complex_dt1) == hash(complex_dt2) + + complex_dt1_roundtripped = pickle.loads(pickle.dumps(complex_dt1)) + assert complex_dt1_roundtripped is not complex_dt1 + assert hash(complex_dt1) == hash(complex_dt1_roundtripped) + + assert hash([complex_dt1, complex_dt1]) == hash( + [complex_dt1_roundtripped, complex_dt1_roundtripped] + ) + assert hash([complex_dt1, complex_dt1]) == hash( + [complex_dt1_roundtripped, complex_dt1] + ) + + +@parametrize('to_hash,expected', + [('This is a string to hash', + '71b3f47df22cb19431d85d92d0b230b2'), + (u"C'est l\xe9t\xe9", + '2d8d189e9b2b0b2e384d93c868c0e576'), + ((123456, 54321, -98765), + 'e205227dd82250871fa25aa0ec690aa3'), + ([random.Random(42).random() for _ in range(5)], + 'a11ffad81f9682a7d901e6edc3d16c84'), + ({'abcde': 123, 'sadfas': [-9999, 2, 3]}, + 'aeda150553d4bb5c69f0e69d51b0e2ef')]) +def test_hashes_stay_the_same(to_hash, expected): + # We want to make sure that hashes don't change with joblib + # version. For end users, that would mean that they have to + # regenerate their cache from scratch, which potentially means + # lengthy recomputations. + # Expected results have been generated with joblib 0.9.2 + assert hash(to_hash) == expected + + +@with_numpy +def test_hashes_are_different_between_c_and_fortran_contiguous_arrays(): + # We want to be sure that the c-contiguous and f-contiguous versions of the + # same array produce 2 different hashes. + rng = np.random.RandomState(0) + arr_c = rng.random_sample((10, 10)) + arr_f = np.asfortranarray(arr_c) + assert hash(arr_c) != hash(arr_f) + + +@with_numpy +def test_0d_array(): + hash(np.array(0)) + + +@with_numpy +def test_0d_and_1d_array_hashing_is_different(): + assert hash(np.array(0)) != hash(np.array([0])) + + +@with_numpy +def test_hashes_stay_the_same_with_numpy_objects(): + # Note: joblib used to test numpy objects hashing by comparing the produced + # hash of an object with some hard-coded target value to guarantee that + # hashing remains the same across joblib versions. However, since numpy + # 1.20 and joblib 1.0, joblib relies on potentially unstable implementation + # details of numpy to hash np.dtype objects, which makes the stability of + # hash values across different environments hard to guarantee and to test. + # As a result, hashing stability across joblib versions becomes best-effort + # only, and we only test the consistency within a single environment by + # making sure: + # - the hash of two copies of the same objects is the same + # - hashing some object in two different python processes produces the same + # value. This should be viewed as a proxy for testing hash consistency + # through time between Python sessions (provided no change in the + # environment was done between sessions). + + def create_objects_to_hash(): + rng = np.random.RandomState(42) + # Being explicit about dtypes in order to avoid + # architecture-related differences. Also using 'f4' rather than + # 'f8' for float arrays because 'f8' arrays generated by + # rng.random.randn don't seem to be bit-identical on 32bit and + # 64bit machines. + to_hash_list = [ + rng.randint(-1000, high=1000, size=50).astype(' +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. +import re + +from joblib.logger import PrintTime + + +def test_print_time(tmpdir, capsys): + # A simple smoke test for PrintTime. + logfile = tmpdir.join('test.log').strpath + print_time = PrintTime(logfile=logfile) + print_time('Foo') + # Create a second time, to smoke test log rotation. + print_time = PrintTime(logfile=logfile) + print_time('Foo') + # And a third time + print_time = PrintTime(logfile=logfile) + print_time('Foo') + + out_printed_text, err_printed_text = capsys.readouterr() + # Use regexps to be robust to time variations + match = r"Foo: 0\..s, 0\..min\nFoo: 0\..s, 0..min\nFoo: " + \ + r".\..s, 0..min\n" + if not re.match(match, err_printed_text): + raise AssertionError('Excepted %s, got %s' % + (match, err_printed_text)) diff --git a/testbed/joblib__joblib/joblib/test/test_memmapping.py b/testbed/joblib__joblib/joblib/test/test_memmapping.py new file mode 100644 index 0000000000000000000000000000000000000000..42a297a9e445d38c0daa03bc7d78e4c4f1fd4571 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_memmapping.py @@ -0,0 +1,1191 @@ +import os +import mmap +import sys +import platform +import gc +import pickle +import itertools +from time import sleep +import subprocess +import threading +import faulthandler + +import pytest + +from joblib.test.common import with_numpy, np +from joblib.test.common import with_multiprocessing +from joblib.test.common import with_dev_shm +from joblib.testing import raises, parametrize, skipif +from joblib.backports import make_memmap +from joblib.parallel import Parallel, delayed + +from joblib.pool import MemmappingPool +from joblib.executor import _TestingMemmappingExecutor as TestExecutor +from joblib._memmapping_reducer import has_shareable_memory +from joblib._memmapping_reducer import ArrayMemmapForwardReducer +from joblib._memmapping_reducer import _strided_from_memmap +from joblib._memmapping_reducer import _get_temp_dir +from joblib._memmapping_reducer import _WeakArrayKeyMap +from joblib._memmapping_reducer import _get_backing_memmap +import joblib._memmapping_reducer as jmr + + +def setup_module(): + faulthandler.dump_traceback_later(timeout=300, exit=True) + + +def teardown_module(): + faulthandler.cancel_dump_traceback_later() + + +def check_memmap_and_send_back(array): + assert _get_backing_memmap(array) is not None + return array + + +def check_array(args): + """Dummy helper function to be executed in subprocesses + + Check that the provided array has the expected values in the provided + range. + + """ + data, position, expected = args + np.testing.assert_array_equal(data[position], expected) + + +def inplace_double(args): + """Dummy helper function to be executed in subprocesses + + + Check that the input array has the right values in the provided range + and perform an inplace modification to double the values in the range by + two. + + """ + data, position, expected = args + assert data[position] == expected + data[position] *= 2 + np.testing.assert_array_equal(data[position], 2 * expected) + + +@with_numpy +@with_multiprocessing +def test_memmap_based_array_reducing(tmpdir): + """Check that it is possible to reduce a memmap backed array""" + assert_array_equal = np.testing.assert_array_equal + filename = tmpdir.join('test.mmap').strpath + + # Create a file larger than what will be used by a + buffer = np.memmap(filename, dtype=np.float64, shape=500, mode='w+') + + # Fill the original buffer with negative markers to detect over of + # underflow in case of test failures + buffer[:] = - 1.0 * np.arange(buffer.shape[0], dtype=buffer.dtype) + buffer.flush() + + # Memmap a 2D fortran array on a offsetted subsection of the previous + # buffer + a = np.memmap(filename, dtype=np.float64, shape=(3, 5, 4), + mode='r+', order='F', offset=4) + a[:] = np.arange(60).reshape(a.shape) + + # Build various views that share the buffer with the original memmap + + # b is an memmap sliced view on an memmap instance + b = a[1:-1, 2:-1, 2:4] + + # c and d are array views + c = np.asarray(b) + d = c.T + + # Array reducer with auto dumping disabled + reducer = ArrayMemmapForwardReducer(None, tmpdir.strpath, 'c', True) + + def reconstruct_array_or_memmap(x): + cons, args = reducer(x) + return cons(*args) + + # Reconstruct original memmap + a_reconstructed = reconstruct_array_or_memmap(a) + assert has_shareable_memory(a_reconstructed) + assert isinstance(a_reconstructed, np.memmap) + assert_array_equal(a_reconstructed, a) + + # Reconstruct strided memmap view + b_reconstructed = reconstruct_array_or_memmap(b) + assert has_shareable_memory(b_reconstructed) + assert_array_equal(b_reconstructed, b) + + # Reconstruct arrays views on memmap base + c_reconstructed = reconstruct_array_or_memmap(c) + assert not isinstance(c_reconstructed, np.memmap) + assert has_shareable_memory(c_reconstructed) + assert_array_equal(c_reconstructed, c) + + d_reconstructed = reconstruct_array_or_memmap(d) + assert not isinstance(d_reconstructed, np.memmap) + assert has_shareable_memory(d_reconstructed) + assert_array_equal(d_reconstructed, d) + + # Test graceful degradation on fake memmap instances with in-memory + # buffers + a3 = a * 3 + assert not has_shareable_memory(a3) + a3_reconstructed = reconstruct_array_or_memmap(a3) + assert not has_shareable_memory(a3_reconstructed) + assert not isinstance(a3_reconstructed, np.memmap) + assert_array_equal(a3_reconstructed, a * 3) + + # Test graceful degradation on arrays derived from fake memmap instances + b3 = np.asarray(a3) + assert not has_shareable_memory(b3) + + b3_reconstructed = reconstruct_array_or_memmap(b3) + assert isinstance(b3_reconstructed, np.ndarray) + assert not has_shareable_memory(b3_reconstructed) + assert_array_equal(b3_reconstructed, b3) + + +@with_multiprocessing +@skipif((sys.platform != "win32") or (), + reason="PermissionError only easily triggerable on Windows") +def test_resource_tracker_retries_when_permissionerror(tmpdir): + # Test resource_tracker retry mechanism when unlinking memmaps. See more + # thorough information in the ``unlink_file`` documentation of joblib. + filename = tmpdir.join('test.mmap').strpath + cmd = """if 1: + import os + import numpy as np + import time + from joblib.externals.loky.backend import resource_tracker + resource_tracker.VERBOSE = 1 + + # Start the resource tracker + resource_tracker.ensure_running() + time.sleep(1) + + # Create a file containing numpy data + memmap = np.memmap(r"{filename}", dtype=np.float64, shape=10, mode='w+') + memmap[:] = np.arange(10).astype(np.int8).data + memmap.flush() + assert os.path.exists(r"{filename}") + del memmap + + # Create a np.memmap backed by this file + memmap = np.memmap(r"{filename}", dtype=np.float64, shape=10, mode='w+') + resource_tracker.register(r"{filename}", "file") + + # Ask the resource_tracker to delete the file backing the np.memmap , this + # should raise PermissionError that the resource_tracker will log. + resource_tracker.maybe_unlink(r"{filename}", "file") + + # Wait for the resource_tracker to process the maybe_unlink before cleaning + # up the memmap + time.sleep(2) + """.format(filename=filename) + p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE, + stdout=subprocess.PIPE) + p.wait() + out, err = p.communicate() + assert p.returncode == 0 + assert out == b'' + msg = 'tried to unlink {}, got PermissionError'.format(filename) + assert msg in err.decode() + + +@with_numpy +@with_multiprocessing +def test_high_dimension_memmap_array_reducing(tmpdir): + assert_array_equal = np.testing.assert_array_equal + + filename = tmpdir.join('test.mmap').strpath + + # Create a high dimensional memmap + a = np.memmap(filename, dtype=np.float64, shape=(100, 15, 15, 3), + mode='w+') + a[:] = np.arange(100 * 15 * 15 * 3).reshape(a.shape) + + # Create some slices/indices at various dimensions + b = a[0:10] + c = a[:, 5:10] + d = a[:, :, :, 0] + e = a[1:3:4] + + # Array reducer with auto dumping disabled + reducer = ArrayMemmapForwardReducer(None, tmpdir.strpath, 'c', True) + + def reconstruct_array_or_memmap(x): + cons, args = reducer(x) + return cons(*args) + + a_reconstructed = reconstruct_array_or_memmap(a) + assert has_shareable_memory(a_reconstructed) + assert isinstance(a_reconstructed, np.memmap) + assert_array_equal(a_reconstructed, a) + + b_reconstructed = reconstruct_array_or_memmap(b) + assert has_shareable_memory(b_reconstructed) + assert_array_equal(b_reconstructed, b) + + c_reconstructed = reconstruct_array_or_memmap(c) + assert has_shareable_memory(c_reconstructed) + assert_array_equal(c_reconstructed, c) + + d_reconstructed = reconstruct_array_or_memmap(d) + assert has_shareable_memory(d_reconstructed) + assert_array_equal(d_reconstructed, d) + + e_reconstructed = reconstruct_array_or_memmap(e) + assert has_shareable_memory(e_reconstructed) + assert_array_equal(e_reconstructed, e) + + +@with_numpy +def test__strided_from_memmap(tmpdir): + fname = tmpdir.join('test.mmap').strpath + size = 5 * mmap.ALLOCATIONGRANULARITY + offset = mmap.ALLOCATIONGRANULARITY + 1 + # This line creates the mmap file that is reused later + memmap_obj = np.memmap(fname, mode='w+', shape=size + offset) + # filename, dtype, mode, offset, order, shape, strides, total_buffer_len + memmap_obj = _strided_from_memmap(fname, dtype='uint8', mode='r', + offset=offset, order='C', shape=size, + strides=None, total_buffer_len=None, + unlink_on_gc_collect=False) + assert isinstance(memmap_obj, np.memmap) + assert memmap_obj.offset == offset + memmap_backed_obj = _strided_from_memmap( + fname, dtype='uint8', mode='r', offset=offset, order='C', + shape=(size // 2,), strides=(2,), total_buffer_len=size, + unlink_on_gc_collect=False + ) + assert _get_backing_memmap(memmap_backed_obj).offset == offset + + +@with_numpy +@with_multiprocessing +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_pool_with_memmap(factory, tmpdir): + """Check that subprocess can access and update shared memory memmap""" + assert_array_equal = np.testing.assert_array_equal + + # Fork the subprocess before allocating the objects to be passed + pool_temp_folder = tmpdir.mkdir('pool').strpath + p = factory(10, max_nbytes=2, temp_folder=pool_temp_folder) + try: + filename = tmpdir.join('test.mmap').strpath + a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+') + a.fill(1.0) + + p.map(inplace_double, [(a, (i, j), 1.0) + for i in range(a.shape[0]) + for j in range(a.shape[1])]) + + assert_array_equal(a, 2 * np.ones(a.shape)) + + # Open a copy-on-write view on the previous data + b = np.memmap(filename, dtype=np.float32, shape=(5, 3), mode='c') + + p.map(inplace_double, [(b, (i, j), 2.0) + for i in range(b.shape[0]) + for j in range(b.shape[1])]) + + # Passing memmap instances to the pool should not trigger the creation + # of new files on the FS + assert os.listdir(pool_temp_folder) == [] + + # the original data is untouched + assert_array_equal(a, 2 * np.ones(a.shape)) + assert_array_equal(b, 2 * np.ones(b.shape)) + + # readonly maps can be read but not updated + c = np.memmap(filename, dtype=np.float32, shape=(10,), mode='r', + offset=5 * 4) + + with raises(AssertionError): + p.map(check_array, [(c, i, 3.0) for i in range(c.shape[0])]) + + # depending on the version of numpy one can either get a RuntimeError + # or a ValueError + with raises((RuntimeError, ValueError)): + p.map(inplace_double, [(c, i, 2.0) for i in range(c.shape[0])]) + finally: + # Clean all filehandlers held by the pool + p.terminate() + del p + + +@with_numpy +@with_multiprocessing +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_pool_with_memmap_array_view(factory, tmpdir): + """Check that subprocess can access and update shared memory array""" + assert_array_equal = np.testing.assert_array_equal + + # Fork the subprocess before allocating the objects to be passed + pool_temp_folder = tmpdir.mkdir('pool').strpath + p = factory(10, max_nbytes=2, temp_folder=pool_temp_folder) + try: + + filename = tmpdir.join('test.mmap').strpath + a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+') + a.fill(1.0) + + # Create an ndarray view on the memmap instance + a_view = np.asarray(a) + assert not isinstance(a_view, np.memmap) + assert has_shareable_memory(a_view) + + p.map(inplace_double, [(a_view, (i, j), 1.0) + for i in range(a.shape[0]) + for j in range(a.shape[1])]) + + # Both a and the a_view have been updated + assert_array_equal(a, 2 * np.ones(a.shape)) + assert_array_equal(a_view, 2 * np.ones(a.shape)) + + # Passing memmap array view to the pool should not trigger the + # creation of new files on the FS + assert os.listdir(pool_temp_folder) == [] + + finally: + p.terminate() + del p + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_permission_error_windows_reference_cycle(backend): + # Non regression test for: + # https://github.com/joblib/joblib/issues/806 + # + # The issue happens when trying to delete a memory mapped file that has + # not yet been closed by one of the worker processes. + cmd = """if 1: + import numpy as np + from joblib import Parallel, delayed + + + data = np.random.rand(int(2e6)).reshape((int(1e6), 2)) + + # Build a complex cyclic reference that is likely to delay garbage + # collection of the memmapped array in the worker processes. + first_list = current_list = [data] + for i in range(10): + current_list = [current_list] + first_list.append(current_list) + + if __name__ == "__main__": + results = Parallel(n_jobs=2, backend="{b}")( + delayed(len)(current_list) for i in range(10)) + assert results == [1] * 10 + """.format(b=backend) + p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE, + stdout=subprocess.PIPE) + p.wait() + out, err = p.communicate() + assert p.returncode == 0, out.decode() + "\n\n" + err.decode() + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_permission_error_windows_memmap_sent_to_parent(backend): + # Second non-regression test for: + # https://github.com/joblib/joblib/issues/806 + # previously, child process would not convert temporary memmaps to numpy + # arrays when sending the data back to the parent process. This would lead + # to permission errors on windows when deleting joblib's temporary folder, + # as the memmaped files handles would still opened in the parent process. + cmd = '''if 1: + import os + import time + + import numpy as np + + from joblib import Parallel, delayed + from testutils import return_slice_of_data + + data = np.ones(int(2e6)) + + if __name__ == '__main__': + # warm-up call to launch the workers and start the resource_tracker + _ = Parallel(n_jobs=2, verbose=5, backend='{b}')( + delayed(id)(i) for i in range(20)) + + time.sleep(0.5) + + slice_of_data = Parallel(n_jobs=2, verbose=5, backend='{b}')( + delayed(return_slice_of_data)(data, 0, 20) for _ in range(10)) + '''.format(b=backend) + + for _ in range(3): + env = os.environ.copy() + env['PYTHONPATH'] = os.path.dirname(__file__) + p = subprocess.Popen([sys.executable, '-c', cmd], + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, env=env) + p.wait() + out, err = p.communicate() + assert p.returncode == 0, err + assert out == b'' + if sys.version_info[:3] not in [(3, 8, 0), (3, 8, 1)]: + # In early versions of Python 3.8, a reference leak + # https://github.com/cloudpipe/cloudpickle/issues/327, holds + # references to pickled objects, generating race condition during + # cleanup finalizers of joblib and noisy resource_tracker outputs. + assert b'resource_tracker' not in err + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_parallel_isolated_temp_folders(backend): + # Test that consecutive Parallel call use isolated subfolders, even + # for the loky backend that reuses its executor instance across calls. + array = np.arange(int(1e2)) + [filename_1] = Parallel(n_jobs=2, backend=backend, max_nbytes=10)( + delayed(getattr)(array, 'filename') for _ in range(1) + ) + [filename_2] = Parallel(n_jobs=2, backend=backend, max_nbytes=10)( + delayed(getattr)(array, 'filename') for _ in range(1) + ) + assert os.path.dirname(filename_2) != os.path.dirname(filename_1) + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_managed_backend_reuse_temp_folder(backend): + # Test that calls to a managed parallel object reuse the same memmaps. + array = np.arange(int(1e2)) + with Parallel(n_jobs=2, backend=backend, max_nbytes=10) as p: + [filename_1] = p( + delayed(getattr)(array, 'filename') for _ in range(1) + ) + [filename_2] = p( + delayed(getattr)(array, 'filename') for _ in range(1) + ) + assert os.path.dirname(filename_2) == os.path.dirname(filename_1) + + +@with_numpy +@with_multiprocessing +def test_memmapping_temp_folder_thread_safety(): + # Concurrent calls to Parallel with the loky backend will use the same + # executor, and thus the same reducers. Make sure that those reducers use + # different temporary folders depending on which Parallel objects called + # them, which is necessary to limit potential race conditions during the + # garbage collection of temporary memmaps. + array = np.arange(int(1e2)) + + temp_dirs_thread_1 = set() + temp_dirs_thread_2 = set() + + def concurrent_get_filename(array, temp_dirs): + with Parallel(backend='loky', n_jobs=2, max_nbytes=10) as p: + for i in range(10): + [filename] = p( + delayed(getattr)(array, 'filename') for _ in range(1) + ) + temp_dirs.add(os.path.dirname(filename)) + + t1 = threading.Thread( + target=concurrent_get_filename, args=(array, temp_dirs_thread_1) + ) + t2 = threading.Thread( + target=concurrent_get_filename, args=(array, temp_dirs_thread_2) + ) + + t1.start() + t2.start() + + t1.join() + t2.join() + + assert len(temp_dirs_thread_1) == 1 + assert len(temp_dirs_thread_2) == 1 + + assert temp_dirs_thread_1 != temp_dirs_thread_2 + + +@with_numpy +@with_multiprocessing +def test_multithreaded_parallel_termination_resource_tracker_silent(): + # test that concurrent termination attempts of a same executor does not + # emit any spurious error from the resource_tracker. We test various + # situations making 0, 1 or both parallel call sending a task that will + # make the worker (and thus the whole Parallel call) error out. + cmd = '''if 1: + import os + import numpy as np + from joblib import Parallel, delayed + from joblib.externals.loky.backend import resource_tracker + from concurrent.futures import ThreadPoolExecutor, wait + + resource_tracker.VERBOSE = 0 + + array = np.arange(int(1e2)) + + temp_dirs_thread_1 = set() + temp_dirs_thread_2 = set() + + + def raise_error(array): + raise ValueError + + + def parallel_get_filename(array, temp_dirs): + with Parallel(backend="loky", n_jobs=2, max_nbytes=10) as p: + for i in range(10): + [filename] = p( + delayed(getattr)(array, "filename") for _ in range(1) + ) + temp_dirs.add(os.path.dirname(filename)) + + + def parallel_raise(array, temp_dirs): + with Parallel(backend="loky", n_jobs=2, max_nbytes=10) as p: + for i in range(10): + [filename] = p( + delayed(raise_error)(array) for _ in range(1) + ) + temp_dirs.add(os.path.dirname(filename)) + + + executor = ThreadPoolExecutor(max_workers=2) + + # both function calls will use the same loky executor, but with a + # different Parallel object. + future_1 = executor.submit({f1}, array, temp_dirs_thread_1) + future_2 = executor.submit({f2}, array, temp_dirs_thread_2) + + # Wait for both threads to terminate their backend + wait([future_1, future_2]) + + future_1.result() + future_2.result() + ''' + functions_and_returncodes = [ + ("parallel_get_filename", "parallel_get_filename", 0), + ("parallel_get_filename", "parallel_raise", 1), + ("parallel_raise", "parallel_raise", 1) + ] + + for f1, f2, returncode in functions_and_returncodes: + p = subprocess.Popen([sys.executable, '-c', cmd.format(f1=f1, f2=f2)], + stderr=subprocess.PIPE, stdout=subprocess.PIPE) + p.wait() + out, err = p.communicate() + assert p.returncode == returncode, out.decode() + assert b"resource_tracker" not in err, err.decode() + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_many_parallel_calls_on_same_object(backend): + # After #966 got merged, consecutive Parallel objects were sharing temp + # folder, which would lead to race conditions happening during the + # temporary resources management with the resource_tracker. This is a + # non-regression test that makes sure that consecutive Parallel operations + # on the same object do not error out. + cmd = '''if 1: + import os + import time + + import numpy as np + + from joblib import Parallel, delayed + from testutils import return_slice_of_data + + data = np.ones(100) + + if __name__ == '__main__': + for i in range(5): + slice_of_data = Parallel( + n_jobs=2, max_nbytes=1, backend='{b}')( + delayed(return_slice_of_data)(data, 0, 20) + for _ in range(10) + ) + '''.format(b=backend) + env = os.environ.copy() + env['PYTHONPATH'] = os.path.dirname(__file__) + p = subprocess.Popen( + [sys.executable, '-c', cmd], + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + env=env, + ) + p.wait() + out, err = p.communicate() + assert p.returncode == 0, err + assert out == b'' + if sys.version_info[:3] not in [(3, 8, 0), (3, 8, 1)]: + # In early versions of Python 3.8, a reference leak + # https://github.com/cloudpipe/cloudpickle/issues/327, holds + # references to pickled objects, generating race condition during + # cleanup finalizers of joblib and noisy resource_tracker outputs. + assert b'resource_tracker' not in err + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_memmap_returned_as_regular_array(backend): + data = np.ones(int(1e3)) + # Check that child processes send temporary memmaps back as numpy arrays. + [result] = Parallel(n_jobs=2, backend=backend, max_nbytes=100)( + delayed(check_memmap_and_send_back)(data) for _ in range(1)) + assert _get_backing_memmap(result) is None + + +@with_numpy +@with_multiprocessing +@parametrize("backend", ["multiprocessing", "loky"]) +def test_resource_tracker_silent_when_reference_cycles(backend): + # There is a variety of reasons that can make joblib with loky backend + # output noisy warnings when a reference cycle is preventing a memmap from + # being garbage collected. Especially, joblib's main process finalizer + # deletes the temporary folder if it was not done before, which can + # interact badly with the resource_tracker. We don't risk leaking any + # resources, but this will likely make joblib output a lot of low-level + # confusing messages. + # + # This test makes sure that the resource_tracker is silent when a reference + # has been collected concurrently on non-Windows platforms. + # + # Note that the script in ``cmd`` is the exact same script as in + # test_permission_error_windows_reference_cycle. + if backend == "loky" and sys.platform.startswith('win'): + # XXX: on Windows, reference cycles can delay timely garbage collection + # and make it impossible to properly delete the temporary folder in the + # main process because of permission errors. + pytest.xfail( + "The temporary folder cannot be deleted on Windows in the " + "presence of a reference cycle" + ) + + cmd = """if 1: + import numpy as np + from joblib import Parallel, delayed + + + data = np.random.rand(int(2e6)).reshape((int(1e6), 2)) + + # Build a complex cyclic reference that is likely to delay garbage + # collection of the memmapped array in the worker processes. + first_list = current_list = [data] + for i in range(10): + current_list = [current_list] + first_list.append(current_list) + + if __name__ == "__main__": + results = Parallel(n_jobs=2, backend="{b}")( + delayed(len)(current_list) for i in range(10)) + assert results == [1] * 10 + """.format(b=backend) + p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE, + stdout=subprocess.PIPE) + p.wait() + out, err = p.communicate() + out = out.decode() + err = err.decode() + assert p.returncode == 0, out + "\n\n" + err + assert "resource_tracker" not in err, err + + +@with_numpy +@with_multiprocessing +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_memmapping_pool_for_large_arrays(factory, tmpdir): + """Check that large arrays are not copied in memory""" + + # Check that the tempfolder is empty + assert os.listdir(tmpdir.strpath) == [] + + # Build an array reducers that automatically dump large array content + # to filesystem backed memmap instances to avoid memory explosion + p = factory(3, max_nbytes=40, temp_folder=tmpdir.strpath, verbose=2) + try: + # The temporary folder for the pool is not provisioned in advance + assert os.listdir(tmpdir.strpath) == [] + assert not os.path.exists(p._temp_folder) + + small = np.ones(5, dtype=np.float32) + assert small.nbytes == 20 + p.map(check_array, [(small, i, 1.0) for i in range(small.shape[0])]) + + # Memory has been copied, the pool filesystem folder is unused + assert os.listdir(tmpdir.strpath) == [] + + # Try with a file larger than the memmap threshold of 40 bytes + large = np.ones(100, dtype=np.float64) + assert large.nbytes == 800 + p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])]) + + # The data has been dumped in a temp folder for subprocess to share it + # without per-child memory copies + assert os.path.isdir(p._temp_folder) + dumped_filenames = os.listdir(p._temp_folder) + assert len(dumped_filenames) == 1 + + # Check that memory mapping is not triggered for arrays with + # dtype='object' + objects = np.array(['abc'] * 100, dtype='object') + results = p.map(has_shareable_memory, [objects]) + assert not results[0] + + finally: + # check FS garbage upon pool termination + p.terminate() + for i in range(10): + sleep(.1) + if not os.path.exists(p._temp_folder): + break + else: # pragma: no cover + raise AssertionError( + 'temporary folder {} was not deleted'.format(p._temp_folder) + ) + del p + + +@with_numpy +@with_multiprocessing +@parametrize( + "backend", + [ + pytest.param( + "multiprocessing", + marks=pytest.mark.xfail( + reason='https://github.com/joblib/joblib/issues/1086' + ), + ), + "loky", + ] +) +def test_child_raises_parent_exits_cleanly(backend): + # When a task executed by a child process raises an error, the parent + # process's backend is notified, and calls abort_everything. + # In loky, abort_everything itself calls shutdown(kill_workers=True) which + # sends SIGKILL to the worker, preventing it from running the finalizers + # supposed to signal the resource_tracker when the worker is done using + # objects relying on a shared resource (e.g np.memmaps). Because this + # behavior is prone to : + # - cause a resource leak + # - make the resource tracker emit noisy resource warnings + # we explicitly test that, when the said situation occurs: + # - no resources are actually leaked + # - the temporary resources are deleted as soon as possible (typically, at + # the end of the failing Parallel call) + # - the resource_tracker does not emit any warnings. + cmd = """if 1: + import os + from pathlib import Path + from time import sleep + + import numpy as np + from joblib import Parallel, delayed + from testutils import print_filename_and_raise + + data = np.random.rand(1000) + + def get_temp_folder(parallel_obj, backend): + if "{b}" == "loky": + return Path(parallel_obj._backend._workers._temp_folder) + else: + return Path(parallel_obj._backend._pool._temp_folder) + + + if __name__ == "__main__": + try: + with Parallel(n_jobs=2, backend="{b}", max_nbytes=100) as p: + temp_folder = get_temp_folder(p, "{b}") + p(delayed(print_filename_and_raise)(data) + for i in range(1)) + except ValueError as e: + # the temporary folder should be deleted by the end of this + # call but apparently on some file systems, this takes + # some time to be visible. + # + # We attempt to write into the temporary folder to test for + # its existence and we wait for a maximum of 10 seconds. + for i in range(100): + try: + with open(temp_folder / "some_file.txt", "w") as f: + f.write("some content") + except FileNotFoundError: + # temp_folder has been deleted, all is fine + break + + # ... else, wait a bit and try again + sleep(.1) + else: + raise AssertionError( + str(temp_folder) + " was not deleted" + ) from e + """.format(b=backend) + env = os.environ.copy() + env['PYTHONPATH'] = os.path.dirname(__file__) + p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE, + stdout=subprocess.PIPE, env=env) + p.wait() + out, err = p.communicate() + out, err = out.decode(), err.decode() + filename = out.split('\n')[0] + assert p.returncode == 0, err or out + assert err == '' # no resource_tracker warnings. + assert not os.path.exists(filename) + + +@with_numpy +@with_multiprocessing +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_memmapping_pool_for_large_arrays_disabled(factory, tmpdir): + """Check that large arrays memmapping can be disabled""" + # Set max_nbytes to None to disable the auto memmapping feature + p = factory(3, max_nbytes=None, temp_folder=tmpdir.strpath) + try: + + # Check that the tempfolder is empty + assert os.listdir(tmpdir.strpath) == [] + + # Try with a file largish than the memmap threshold of 40 bytes + large = np.ones(100, dtype=np.float64) + assert large.nbytes == 800 + p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])]) + + # Check that the tempfolder is still empty + assert os.listdir(tmpdir.strpath) == [] + + finally: + # Cleanup open file descriptors + p.terminate() + del p + + +@with_numpy +@with_multiprocessing +@with_dev_shm +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_memmapping_on_large_enough_dev_shm(factory): + """Check that memmapping uses /dev/shm when possible""" + orig_size = jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE + try: + # Make joblib believe that it can use /dev/shm even when running on a + # CI container where the size of the /dev/shm is not very large (that + # is at least 32 MB instead of 2 GB by default). + jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(32e6) + p = factory(3, max_nbytes=10) + try: + # Check that the pool has correctly detected the presence of the + # shared memory filesystem. + pool_temp_folder = p._temp_folder + folder_prefix = '/dev/shm/joblib_memmapping_folder_' + assert pool_temp_folder.startswith(folder_prefix) + assert os.path.exists(pool_temp_folder) + + # Try with a file larger than the memmap threshold of 10 bytes + a = np.ones(100, dtype=np.float64) + assert a.nbytes == 800 + p.map(id, [a] * 10) + # a should have been memmapped to the pool temp folder: the joblib + # pickling procedure generate one .pkl file: + assert len(os.listdir(pool_temp_folder)) == 1 + + # create a new array with content that is different from 'a' so + # that it is mapped to a different file in the temporary folder of + # the pool. + b = np.ones(100, dtype=np.float64) * 2 + assert b.nbytes == 800 + p.map(id, [b] * 10) + # A copy of both a and b are now stored in the shared memory folder + assert len(os.listdir(pool_temp_folder)) == 2 + finally: + # Cleanup open file descriptors + p.terminate() + del p + + for i in range(100): + # The temp folder is cleaned up upon pool termination + if not os.path.exists(pool_temp_folder): + break + sleep(.1) + else: # pragma: no cover + raise AssertionError('temporary folder of pool was not deleted') + finally: + jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = orig_size + + +@with_numpy +@with_multiprocessing +@with_dev_shm +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_memmapping_on_too_small_dev_shm(factory): + orig_size = jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE + try: + # Make joblib believe that it cannot use /dev/shm unless there is + # 42 exabytes of available shared memory in /dev/shm + jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(42e18) + + p = factory(3, max_nbytes=10) + try: + # Check that the pool has correctly detected the presence of the + # shared memory filesystem. + pool_temp_folder = p._temp_folder + assert not pool_temp_folder.startswith('/dev/shm') + finally: + # Cleanup open file descriptors + p.terminate() + del p + + # The temp folder is cleaned up upon pool termination + assert not os.path.exists(pool_temp_folder) + finally: + jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = orig_size + + +@with_numpy +@with_multiprocessing +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_memmapping_pool_for_large_arrays_in_return(factory, tmpdir): + """Check that large arrays are not copied in memory in return""" + assert_array_equal = np.testing.assert_array_equal + + # Build an array reducers that automatically dump large array content + # but check that the returned datastructure are regular arrays to avoid + # passing a memmap array pointing to a pool controlled temp folder that + # might be confusing to the user + + # The MemmappingPool user can always return numpy.memmap object explicitly + # to avoid memory copy + p = factory(3, max_nbytes=10, temp_folder=tmpdir.strpath) + try: + res = p.apply_async(np.ones, args=(1000,)) + large = res.get() + assert not has_shareable_memory(large) + assert_array_equal(large, np.ones(1000)) + finally: + p.terminate() + del p + + +def _worker_multiply(a, n_times): + """Multiplication function to be executed by subprocess""" + assert has_shareable_memory(a) + return a * n_times + + +@with_numpy +@with_multiprocessing +@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor], + ids=["multiprocessing", "loky"]) +def test_workaround_against_bad_memmap_with_copied_buffers(factory, tmpdir): + """Check that memmaps with a bad buffer are returned as regular arrays + + Unary operations and ufuncs on memmap instances return a new memmap + instance with an in-memory buffer (probably a numpy bug). + """ + assert_array_equal = np.testing.assert_array_equal + + p = factory(3, max_nbytes=10, temp_folder=tmpdir.strpath) + try: + # Send a complex, large-ish view on a array that will be converted to + # a memmap in the worker process + a = np.asarray(np.arange(6000).reshape((1000, 2, 3)), + order='F')[:, :1, :] + + # Call a non-inplace multiply operation on the worker and memmap and + # send it back to the parent. + b = p.apply_async(_worker_multiply, args=(a, 3)).get() + assert not has_shareable_memory(b) + assert_array_equal(b, 3 * a) + finally: + p.terminate() + del p + + +def identity(arg): + return arg + + +@with_numpy +@with_multiprocessing +@parametrize( + "factory,retry_no", + list(itertools.product( + [MemmappingPool, TestExecutor.get_memmapping_executor], range(3))), + ids=['{}, {}'.format(x, y) for x, y in itertools.product( + ["multiprocessing", "loky"], map(str, range(3)))]) +def test_pool_memmap_with_big_offset(factory, retry_no, tmpdir): + # Test that numpy memmap offset is set correctly if greater than + # mmap.ALLOCATIONGRANULARITY, see + # https://github.com/joblib/joblib/issues/451 and + # https://github.com/numpy/numpy/pull/8443 for more details. + fname = tmpdir.join('test.mmap').strpath + size = 5 * mmap.ALLOCATIONGRANULARITY + offset = mmap.ALLOCATIONGRANULARITY + 1 + obj = make_memmap(fname, mode='w+', shape=size, dtype='uint8', + offset=offset) + + p = factory(2, temp_folder=tmpdir.strpath) + result = p.apply_async(identity, args=(obj,)).get() + assert isinstance(result, np.memmap) + assert result.offset == offset + np.testing.assert_array_equal(obj, result) + p.terminate() + + +def test_pool_get_temp_dir(tmpdir): + pool_folder_name = 'test.tmpdir' + pool_folder, shared_mem = _get_temp_dir(pool_folder_name, tmpdir.strpath) + assert shared_mem is False + assert pool_folder == tmpdir.join('test.tmpdir').strpath + + pool_folder, shared_mem = _get_temp_dir(pool_folder_name, temp_folder=None) + if sys.platform.startswith('win'): + assert shared_mem is False + assert pool_folder.endswith(pool_folder_name) + + +def test_pool_get_temp_dir_no_statvfs(tmpdir, monkeypatch): + """Check that _get_temp_dir works when os.statvfs is not defined + + Regression test for #902 + """ + pool_folder_name = 'test.tmpdir' + import joblib._memmapping_reducer + if hasattr(joblib._memmapping_reducer.os, 'statvfs'): + # We are on Unix, since Windows doesn't have this function + monkeypatch.delattr(joblib._memmapping_reducer.os, 'statvfs') + + pool_folder, shared_mem = _get_temp_dir(pool_folder_name, temp_folder=None) + if sys.platform.startswith('win'): + assert shared_mem is False + assert pool_folder.endswith(pool_folder_name) + + +@with_numpy +@skipif(sys.platform == 'win32', reason='This test fails with a ' + 'PermissionError on Windows') +@parametrize("mmap_mode", ["r+", "w+"]) +def test_numpy_arrays_use_different_memory(mmap_mode): + def func(arr, value): + arr[:] = value + return arr + + arrays = [np.zeros((10, 10), dtype='float64') for i in range(10)] + + results = Parallel(mmap_mode=mmap_mode, max_nbytes=0, n_jobs=2)( + delayed(func)(arr, i) for i, arr in enumerate(arrays)) + + for i, arr in enumerate(results): + np.testing.assert_array_equal(arr, i) + + +@with_numpy +def test_weak_array_key_map(): + + def assert_empty_after_gc_collect(container, retries=100): + for i in range(retries): + if len(container) == 0: + return + gc.collect() + sleep(.1) + assert len(container) == 0 + + a = np.ones(42) + m = _WeakArrayKeyMap() + m.set(a, 'a') + assert m.get(a) == 'a' + + b = a + assert m.get(b) == 'a' + m.set(b, 'b') + assert m.get(a) == 'b' + + del a + gc.collect() + assert len(m._data) == 1 + assert m.get(b) == 'b' + + del b + assert_empty_after_gc_collect(m._data) + + c = np.ones(42) + m.set(c, 'c') + assert len(m._data) == 1 + assert m.get(c) == 'c' + + with raises(KeyError): + m.get(np.ones(42)) + + del c + assert_empty_after_gc_collect(m._data) + + # Check that creating and dropping numpy arrays with potentially the same + # object id will not cause the map to get confused. + def get_set_get_collect(m, i): + a = np.ones(42) + with raises(KeyError): + m.get(a) + m.set(a, i) + assert m.get(a) == i + return id(a) + + unique_ids = set([get_set_get_collect(m, i) for i in range(1000)]) + if platform.python_implementation() == 'CPython': + # On CPython (at least) the same id is often reused many times for the + # temporary arrays created under the local scope of the + # get_set_get_collect function without causing any spurious lookups / + # insertions in the map. Apparently on Python nogil, the id is not + # reused as often. + max_len_unique_ids = 400 if getattr(sys.flags, 'nogil', False) else 100 + assert len(unique_ids) < max_len_unique_ids + + +def test_weak_array_key_map_no_pickling(): + m = _WeakArrayKeyMap() + with raises(pickle.PicklingError): + pickle.dumps(m) + + +@with_numpy +@with_multiprocessing +def test_direct_mmap(tmpdir): + testfile = str(tmpdir.join('arr.dat')) + a = np.arange(10, dtype='uint8') + a.tofile(testfile) + + def _read_array(): + with open(testfile) as fd: + mm = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ, offset=0) + return np.ndarray((10,), dtype=np.uint8, buffer=mm, offset=0) + + def func(x): + return x**2 + + arr = _read_array() + + # this is expected to work and gives the reference + ref = Parallel(n_jobs=2)(delayed(func)(x) for x in [a]) + + # now test that it work with the mmap array + results = Parallel(n_jobs=2)(delayed(func)(x) for x in [arr]) + np.testing.assert_array_equal(results, ref) + + # also test with a mmap array read in the subprocess + def worker(): + return _read_array() + + results = Parallel(n_jobs=2)(delayed(worker)() for _ in range(1)) + np.testing.assert_array_equal(results[0], arr) diff --git a/testbed/joblib__joblib/joblib/test/test_memory.py b/testbed/joblib__joblib/joblib/test/test_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9761fd19b0f955467b8b532d05d48217079b85 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_memory.py @@ -0,0 +1,1493 @@ +""" +Test the memory module. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2009 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import functools +import gc +import logging +import shutil +import os +import os.path +import pathlib +import pickle +import sys +import time +import datetime +import textwrap + +import pytest + +from joblib.memory import Memory +from joblib.memory import expires_after +from joblib.memory import MemorizedFunc, NotMemorizedFunc +from joblib.memory import MemorizedResult, NotMemorizedResult +from joblib.memory import _FUNCTION_HASHES +from joblib.memory import register_store_backend, _STORE_BACKENDS +from joblib.memory import _build_func_identifier, _store_backend_factory +from joblib.memory import JobLibCollisionWarning +from joblib.parallel import Parallel, delayed +from joblib._store_backends import StoreBackendBase, FileSystemStoreBackend +from joblib.test.common import with_numpy, np +from joblib.test.common import with_multiprocessing +from joblib.testing import parametrize, raises, warns +from joblib.hashing import hash + + +############################################################################### +# Module-level variables for the tests +def f(x, y=1): + """ A module-level function for testing purposes. + """ + return x ** 2 + y + + +############################################################################### +# Helper function for the tests +def check_identity_lazy(func, accumulator, location): + """ Given a function and an accumulator (a list that grows every + time the function is called), check that the function can be + decorated by memory to be a lazy identity. + """ + # Call each function with several arguments, and check that it is + # evaluated only once per argument. + memory = Memory(location=location, verbose=0) + func = memory.cache(func) + for i in range(3): + for _ in range(2): + assert func(i) == i + assert len(accumulator) == i + 1 + + +def corrupt_single_cache_item(memory): + single_cache_item, = memory.store_backend.get_items() + output_filename = os.path.join(single_cache_item.path, 'output.pkl') + with open(output_filename, 'w') as f: + f.write('garbage') + + +def monkeypatch_cached_func_warn(func, monkeypatch_fixture): + # Need monkeypatch because pytest does not + # capture stdlib logging output (see + # https://github.com/pytest-dev/pytest/issues/2079) + + recorded = [] + + def append_to_record(item): + recorded.append(item) + monkeypatch_fixture.setattr(func, 'warn', append_to_record) + return recorded + + +############################################################################### +# Tests +def test_memory_integration(tmpdir): + """ Simple test of memory lazy evaluation. + """ + accumulator = list() + + # Rmk: this function has the same name than a module-level function, + # thus it serves as a test to see that both are identified + # as different. + def f(arg): + accumulator.append(1) + return arg + + check_identity_lazy(f, accumulator, tmpdir.strpath) + + # Now test clearing + for compress in (False, True): + for mmap_mode in ('r', None): + memory = Memory(location=tmpdir.strpath, verbose=10, + mmap_mode=mmap_mode, compress=compress) + # First clear the cache directory, to check that our code can + # handle that + # NOTE: this line would raise an exception, as the database file is + # still open; we ignore the error since we want to test what + # happens if the directory disappears + shutil.rmtree(tmpdir.strpath, ignore_errors=True) + g = memory.cache(f) + g(1) + g.clear(warn=False) + current_accumulator = len(accumulator) + out = g(1) + + assert len(accumulator) == current_accumulator + 1 + # Also, check that Memory.eval works similarly + assert memory.eval(f, 1) == out + assert len(accumulator) == current_accumulator + 1 + + # Now do a smoke test with a function defined in __main__, as the name + # mangling rules are more complex + f.__module__ = '__main__' + memory = Memory(location=tmpdir.strpath, verbose=0) + memory.cache(f)(1) + + +@parametrize("call_before_reducing", [True, False]) +def test_parallel_call_cached_function_defined_in_jupyter( + tmpdir, call_before_reducing +): + # Calling an interactively defined memory.cache()'d function inside a + # Parallel call used to clear the existing cache related to the said + # function (https://github.com/joblib/joblib/issues/1035) + + # This tests checks that this is no longer the case. + + # TODO: test that the cache related to the function cache persists across + # ipython sessions (provided that no code change were made to the + # function's source)? + + # The first part of the test makes the necessary low-level calls to emulate + # the definition of a function in an jupyter notebook cell. Joblib has + # some custom code to treat functions defined specifically in jupyter + # notebooks/ipython session -- we want to test this code, which requires + # the emulation to be rigorous. + for session_no in [0, 1]: + ipython_cell_source = ''' + def f(x): + return x + ''' + + ipython_cell_id = ''.format(session_no) + + exec( + compile( + textwrap.dedent(ipython_cell_source), + filename=ipython_cell_id, + mode='exec' + ) + ) + # f is now accessible in the locals mapping - but for some unknown + # reason, f = locals()['f'] throws a KeyError at runtime, we need to + # bind locals()['f'] to a different name in the local namespace + aliased_f = locals()['f'] + aliased_f.__module__ = "__main__" + + # Preliminary sanity checks, and tests checking that joblib properly + # identified f as an interactive function defined in a jupyter notebook + assert aliased_f(1) == 1 + assert aliased_f.__code__.co_filename == ipython_cell_id + + memory = Memory(location=tmpdir.strpath, verbose=0) + cached_f = memory.cache(aliased_f) + + assert len(os.listdir(tmpdir / 'joblib')) == 1 + f_cache_relative_directory = os.listdir(tmpdir / 'joblib')[0] + assert 'ipython-input' in f_cache_relative_directory + + f_cache_directory = tmpdir / 'joblib' / f_cache_relative_directory + + if session_no == 0: + # The cache should be empty as cached_f has not been called yet. + assert os.listdir(f_cache_directory) == ['f'] + assert os.listdir(f_cache_directory / 'f') == [] + + if call_before_reducing: + cached_f(3) + # Two files were just created, func_code.py, and a folder + # containing the information (inputs hash/ouptput) of + # cached_f(3) + assert len(os.listdir(f_cache_directory / 'f')) == 2 + + # Now, testing #1035: when calling a cached function, joblib + # used to dynamically inspect the underlying function to + # extract its source code (to verify it matches the source code + # of the function as last inspected by joblib) -- however, + # source code introspection fails for dynamic functions sent to + # child processes - which would eventually make joblib clear + # the cache associated to f + res = Parallel(n_jobs=2)(delayed(cached_f)(i) for i in [1, 2]) + else: + # Submit the function to the joblib child processes, although + # the function has never been called in the parent yet. This + # triggers a specific code branch inside + # MemorizedFunc.__reduce__. + res = Parallel(n_jobs=2)(delayed(cached_f)(i) for i in [1, 2]) + assert len(os.listdir(f_cache_directory / 'f')) == 3 + + cached_f(3) + + # Making sure f's cache does not get cleared after the parallel + # calls, and contains ALL cached functions calls (f(1), f(2), f(3)) + # and 'func_code.py' + assert len(os.listdir(f_cache_directory / 'f')) == 4 + else: + # For the second session, there should be an already existing cache + assert len(os.listdir(f_cache_directory / 'f')) == 4 + + cached_f(3) + + # The previous cache should not be invalidated after calling the + # function in a new session + assert len(os.listdir(f_cache_directory / 'f')) == 4 + + +def test_no_memory(): + """ Test memory with location=None: no memoize """ + accumulator = list() + + def ff(arg): + accumulator.append(1) + return arg + + memory = Memory(location=None, verbose=0) + gg = memory.cache(ff) + for _ in range(4): + current_accumulator = len(accumulator) + gg(1) + assert len(accumulator) == current_accumulator + 1 + + +def test_memory_kwarg(tmpdir): + " Test memory with a function with keyword arguments." + accumulator = list() + + def g(arg1=None, arg2=1): + accumulator.append(1) + return arg1 + + check_identity_lazy(g, accumulator, tmpdir.strpath) + + memory = Memory(location=tmpdir.strpath, verbose=0) + g = memory.cache(g) + # Smoke test with an explicit keyword argument: + assert g(arg1=30, arg2=2) == 30 + + +def test_memory_lambda(tmpdir): + " Test memory with a function with a lambda." + accumulator = list() + + def helper(x): + """ A helper function to define l as a lambda. + """ + accumulator.append(1) + return x + + check_identity_lazy(lambda x: helper(x), accumulator, tmpdir.strpath) + + +def test_memory_name_collision(tmpdir): + " Check that name collisions with functions will raise warnings" + memory = Memory(location=tmpdir.strpath, verbose=0) + + @memory.cache + def name_collision(x): + """ A first function called name_collision + """ + return x + + a = name_collision + + @memory.cache + def name_collision(x): + """ A second function called name_collision + """ + return x + + b = name_collision + + with warns(JobLibCollisionWarning) as warninfo: + a(1) + b(1) + + assert len(warninfo) == 1 + assert "collision" in str(warninfo[0].message) + + +def test_memory_warning_lambda_collisions(tmpdir): + # Check that multiple use of lambda will raise collisions + memory = Memory(location=tmpdir.strpath, verbose=0) + a = memory.cache(lambda x: x) + b = memory.cache(lambda x: x + 1) + + with warns(JobLibCollisionWarning) as warninfo: + assert a(0) == 0 + assert b(1) == 2 + assert a(1) == 1 + + # In recent Python versions, we can retrieve the code of lambdas, + # thus nothing is raised + assert len(warninfo) == 4 + + +def test_memory_warning_collision_detection(tmpdir): + # Check that collisions impossible to detect will raise appropriate + # warnings. + memory = Memory(location=tmpdir.strpath, verbose=0) + a1 = eval('lambda x: x') + a1 = memory.cache(a1) + b1 = eval('lambda x: x+1') + b1 = memory.cache(b1) + + with warns(JobLibCollisionWarning) as warninfo: + a1(1) + b1(1) + a1(0) + + assert len(warninfo) == 2 + assert "cannot detect" in str(warninfo[0].message).lower() + + +def test_memory_partial(tmpdir): + " Test memory with functools.partial." + accumulator = list() + + def func(x, y): + """ A helper function to define l as a lambda. + """ + accumulator.append(1) + return y + + import functools + function = functools.partial(func, 1) + + check_identity_lazy(function, accumulator, tmpdir.strpath) + + +def test_memory_eval(tmpdir): + " Smoke test memory with a function with a function defined in an eval." + memory = Memory(location=tmpdir.strpath, verbose=0) + + m = eval('lambda x: x') + mm = memory.cache(m) + + assert mm(1) == 1 + + +def count_and_append(x=[]): + """ A function with a side effect in its arguments. + + Return the length of its argument and append one element. + """ + len_x = len(x) + x.append(None) + return len_x + + +def test_argument_change(tmpdir): + """ Check that if a function has a side effect in its arguments, it + should use the hash of changing arguments. + """ + memory = Memory(location=tmpdir.strpath, verbose=0) + func = memory.cache(count_and_append) + # call the function for the first time, is should cache it with + # argument x=[] + assert func() == 0 + # the second time the argument is x=[None], which is not cached + # yet, so the functions should be called a second time + assert func() == 1 + + +@with_numpy +@parametrize('mmap_mode', [None, 'r']) +def test_memory_numpy(tmpdir, mmap_mode): + " Test memory with a function with numpy arrays." + accumulator = list() + + def n(arg=None): + accumulator.append(1) + return arg + + memory = Memory(location=tmpdir.strpath, mmap_mode=mmap_mode, + verbose=0) + cached_n = memory.cache(n) + + rnd = np.random.RandomState(0) + for i in range(3): + a = rnd.random_sample((10, 10)) + for _ in range(3): + assert np.all(cached_n(a) == a) + assert len(accumulator) == i + 1 + + +@with_numpy +def test_memory_numpy_check_mmap_mode(tmpdir, monkeypatch): + """Check that mmap_mode is respected even at the first call""" + + memory = Memory(location=tmpdir.strpath, mmap_mode='r', verbose=0) + + @memory.cache() + def twice(a): + return a * 2 + + a = np.ones(3) + + b = twice(a) + c = twice(a) + + assert isinstance(c, np.memmap) + assert c.mode == 'r' + + assert isinstance(b, np.memmap) + assert b.mode == 'r' + + # Corrupts the file, Deleting b and c mmaps + # is necessary to be able edit the file + del b + del c + gc.collect() + corrupt_single_cache_item(memory) + + # Make sure that corrupting the file causes recomputation and that + # a warning is issued. + recorded_warnings = monkeypatch_cached_func_warn(twice, monkeypatch) + d = twice(a) + assert len(recorded_warnings) == 1 + exception_msg = 'Exception while loading results' + assert exception_msg in recorded_warnings[0] + # Asserts that the recomputation returns a mmap + assert isinstance(d, np.memmap) + assert d.mode == 'r' + + +def test_memory_exception(tmpdir): + """ Smoketest the exception handling of Memory. + """ + memory = Memory(location=tmpdir.strpath, verbose=0) + + class MyException(Exception): + pass + + @memory.cache + def h(exc=0): + if exc: + raise MyException + + # Call once, to initialise the cache + h() + + for _ in range(3): + # Call 3 times, to be sure that the Exception is always raised + with raises(MyException): + h(1) + + +def test_memory_ignore(tmpdir): + " Test the ignore feature of memory " + memory = Memory(location=tmpdir.strpath, verbose=0) + accumulator = list() + + @memory.cache(ignore=['y']) + def z(x, y=1): + accumulator.append(1) + + assert z.ignore == ['y'] + + z(0, y=1) + assert len(accumulator) == 1 + z(0, y=1) + assert len(accumulator) == 1 + z(0, y=2) + assert len(accumulator) == 1 + + +def test_memory_ignore_decorated(tmpdir): + " Test the ignore feature of memory on a decorated function " + memory = Memory(location=tmpdir.strpath, verbose=0) + accumulator = list() + + def decorate(f): + @functools.wraps(f) + def wrapped(*args, **kwargs): + return f(*args, **kwargs) + return wrapped + + @memory.cache(ignore=['y']) + @decorate + def z(x, y=1): + accumulator.append(1) + + assert z.ignore == ['y'] + + z(0, y=1) + assert len(accumulator) == 1 + z(0, y=1) + assert len(accumulator) == 1 + z(0, y=2) + assert len(accumulator) == 1 + + +def test_memory_args_as_kwargs(tmpdir): + """Non-regression test against 0.12.0 changes. + + https://github.com/joblib/joblib/pull/751 + """ + memory = Memory(location=tmpdir.strpath, verbose=0) + + @memory.cache + def plus_one(a): + return a + 1 + + # It's possible to call a positional arg as a kwarg. + assert plus_one(1) == 2 + assert plus_one(a=1) == 2 + + # However, a positional argument that joblib hadn't seen + # before would cause a failure if it was passed as a kwarg. + assert plus_one(a=2) == 3 + + +@parametrize('ignore, verbose, mmap_mode', [(['x'], 100, 'r'), + ([], 10, None)]) +def test_partial_decoration(tmpdir, ignore, verbose, mmap_mode): + "Check cache may be called with kwargs before decorating" + memory = Memory(location=tmpdir.strpath, verbose=0) + + @memory.cache(ignore=ignore, verbose=verbose, mmap_mode=mmap_mode) + def z(x): + pass + + assert z.ignore == ignore + assert z._verbose == verbose + assert z.mmap_mode == mmap_mode + + +def test_func_dir(tmpdir): + # Test the creation of the memory cache directory for the function. + memory = Memory(location=tmpdir.strpath, verbose=0) + path = __name__.split('.') + path.append('f') + path = tmpdir.join('joblib', *path).strpath + + g = memory.cache(f) + # Test that the function directory is created on demand + func_id = _build_func_identifier(f) + location = os.path.join(g.store_backend.location, func_id) + assert location == path + assert os.path.exists(path) + assert memory.location == os.path.dirname(g.store_backend.location) + + # Test that the code is stored. + # For the following test to be robust to previous execution, we clear + # the in-memory store + _FUNCTION_HASHES.clear() + assert not g._check_previous_func_code() + assert os.path.exists(os.path.join(path, 'func_code.py')) + assert g._check_previous_func_code() + + # Test the robustness to failure of loading previous results. + func_id, args_id = g._get_output_identifiers(1) + output_dir = os.path.join(g.store_backend.location, func_id, args_id) + a = g(1) + assert os.path.exists(output_dir) + os.remove(os.path.join(output_dir, 'output.pkl')) + assert a == g(1) + + +def test_persistence(tmpdir): + # Test the memorized functions can be pickled and restored. + memory = Memory(location=tmpdir.strpath, verbose=0) + g = memory.cache(f) + output = g(1) + + h = pickle.loads(pickle.dumps(g)) + + func_id, args_id = h._get_output_identifiers(1) + output_dir = os.path.join(h.store_backend.location, func_id, args_id) + assert os.path.exists(output_dir) + assert output == h.store_backend.load_item([func_id, args_id]) + memory2 = pickle.loads(pickle.dumps(memory)) + assert memory.store_backend.location == memory2.store_backend.location + + # Smoke test that pickling a memory with location=None works + memory = Memory(location=None, verbose=0) + pickle.loads(pickle.dumps(memory)) + g = memory.cache(f) + gp = pickle.loads(pickle.dumps(g)) + gp(1) + + +def test_check_call_in_cache(tmpdir): + for func in (MemorizedFunc(f, tmpdir.strpath), + Memory(location=tmpdir.strpath, verbose=0).cache(f)): + result = func.check_call_in_cache(2) + assert not result + assert isinstance(result, bool) + assert func(2) == 5 + result = func.check_call_in_cache(2) + assert result + assert isinstance(result, bool) + func.clear() + + +def test_call_and_shelve(tmpdir): + # Test MemorizedFunc outputting a reference to cache. + + for func, Result in zip((MemorizedFunc(f, tmpdir.strpath), + NotMemorizedFunc(f), + Memory(location=tmpdir.strpath, + verbose=0).cache(f), + Memory(location=None).cache(f), + ), + (MemorizedResult, NotMemorizedResult, + MemorizedResult, NotMemorizedResult)): + assert func(2) == 5 + result = func.call_and_shelve(2) + assert isinstance(result, Result) + assert result.get() == 5 + + result.clear() + with raises(KeyError): + result.get() + result.clear() # Do nothing if there is no cache. + + +def test_call_and_shelve_argument_hash(tmpdir): + # Verify that a warning is raised when accessing arguments_hash + # attribute from MemorizedResult + func = Memory(location=tmpdir.strpath, verbose=0).cache(f) + result = func.call_and_shelve(2) + assert isinstance(result, MemorizedResult) + with warns(DeprecationWarning) as w: + assert result.argument_hash == result.args_id + assert len(w) == 1 + assert "The 'argument_hash' attribute has been deprecated" \ + in str(w[-1].message) + + +def test_call_and_shelve_lazily_load_stored_result(tmpdir): + """Check call_and_shelve only load stored data if needed.""" + test_access_time_file = tmpdir.join('test_access') + test_access_time_file.write('test_access') + test_access_time = os.stat(test_access_time_file.strpath).st_atime + # check file system access time stats resolution is lower than test wait + # timings. + time.sleep(0.5) + assert test_access_time_file.read() == 'test_access' + + if test_access_time == os.stat(test_access_time_file.strpath).st_atime: + # Skip this test when access time cannot be retrieved with enough + # precision from the file system (e.g. NTFS on windows). + pytest.skip("filesystem does not support fine-grained access time " + "attribute") + + memory = Memory(location=tmpdir.strpath, verbose=0) + func = memory.cache(f) + func_id, argument_hash = func._get_output_identifiers(2) + result_path = os.path.join(memory.store_backend.location, + func_id, argument_hash, 'output.pkl') + assert func(2) == 5 + first_access_time = os.stat(result_path).st_atime + time.sleep(1) + + # Should not access the stored data + result = func.call_and_shelve(2) + assert isinstance(result, MemorizedResult) + assert os.stat(result_path).st_atime == first_access_time + time.sleep(1) + + # Read the stored data => last access time is greater than first_access + assert result.get() == 5 + assert os.stat(result_path).st_atime > first_access_time + + +def test_memorized_pickling(tmpdir): + for func in (MemorizedFunc(f, tmpdir.strpath), NotMemorizedFunc(f)): + filename = tmpdir.join('pickling_test.dat').strpath + result = func.call_and_shelve(2) + with open(filename, 'wb') as fp: + pickle.dump(result, fp) + with open(filename, 'rb') as fp: + result2 = pickle.load(fp) + assert result2.get() == result.get() + os.remove(filename) + + +def test_memorized_repr(tmpdir): + func = MemorizedFunc(f, tmpdir.strpath) + result = func.call_and_shelve(2) + + func2 = MemorizedFunc(f, tmpdir.strpath) + result2 = func2.call_and_shelve(2) + assert result.get() == result2.get() + assert repr(func) == repr(func2) + + # Smoke test with NotMemorizedFunc + func = NotMemorizedFunc(f) + repr(func) + repr(func.call_and_shelve(2)) + + # Smoke test for message output (increase code coverage) + func = MemorizedFunc(f, tmpdir.strpath, verbose=11, timestamp=time.time()) + result = func.call_and_shelve(11) + result.get() + + func = MemorizedFunc(f, tmpdir.strpath, verbose=11) + result = func.call_and_shelve(11) + result.get() + + func = MemorizedFunc(f, tmpdir.strpath, verbose=5, timestamp=time.time()) + result = func.call_and_shelve(11) + result.get() + + func = MemorizedFunc(f, tmpdir.strpath, verbose=5) + result = func.call_and_shelve(11) + result.get() + + +def test_memory_file_modification(capsys, tmpdir, monkeypatch): + # Test that modifying a Python file after loading it does not lead to + # Recomputation + dir_name = tmpdir.mkdir('tmp_import').strpath + filename = os.path.join(dir_name, 'tmp_joblib_.py') + content = 'def f(x):\n print(x)\n return x\n' + with open(filename, 'w') as module_file: + module_file.write(content) + + # Load the module: + monkeypatch.syspath_prepend(dir_name) + import tmp_joblib_ as tmp + + memory = Memory(location=tmpdir.strpath, verbose=0) + f = memory.cache(tmp.f) + # First call f a few times + f(1) + f(2) + f(1) + + # Now modify the module where f is stored without modifying f + with open(filename, 'w') as module_file: + module_file.write('\n\n' + content) + + # And call f a couple more times + f(1) + f(1) + + # Flush the .pyc files + shutil.rmtree(dir_name) + os.mkdir(dir_name) + # Now modify the module where f is stored, modifying f + content = 'def f(x):\n print("x=%s" % x)\n return x\n' + with open(filename, 'w') as module_file: + module_file.write(content) + + # And call f more times prior to reloading: the cache should not be + # invalidated at this point as the active function definition has not + # changed in memory yet. + f(1) + f(1) + + # Now reload + sys.stdout.write('Reloading\n') + sys.modules.pop('tmp_joblib_') + import tmp_joblib_ as tmp + f = memory.cache(tmp.f) + + # And call f more times + f(1) + f(1) + + out, err = capsys.readouterr() + assert out == '1\n2\nReloading\nx=1\n' + + +def _function_to_cache(a, b): + # Just a place holder function to be mutated by tests + pass + + +def _sum(a, b): + return a + b + + +def _product(a, b): + return a * b + + +def test_memory_in_memory_function_code_change(tmpdir): + _function_to_cache.__code__ = _sum.__code__ + + memory = Memory(location=tmpdir.strpath, verbose=0) + f = memory.cache(_function_to_cache) + + assert f(1, 2) == 3 + assert f(1, 2) == 3 + + with warns(JobLibCollisionWarning): + # Check that inline function modification triggers a cache invalidation + _function_to_cache.__code__ = _product.__code__ + assert f(1, 2) == 2 + assert f(1, 2) == 2 + + +def test_clear_memory_with_none_location(): + memory = Memory(location=None) + memory.clear() + + +def func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'): + return a, b, kw1, kw2 + + +def func_with_signature(a: int, b: float) -> float: + return a + b + + +def test_memory_func_with_kwonly_args(tmpdir): + memory = Memory(location=tmpdir.strpath, verbose=0) + func_cached = memory.cache(func_with_kwonly_args) + + assert func_cached(1, 2, kw1=3) == (1, 2, 3, 'kw2') + + # Making sure that providing a keyword-only argument by + # position raises an exception + with raises(ValueError) as excinfo: + func_cached(1, 2, 3, kw2=4) + excinfo.match("Keyword-only parameter 'kw1' was passed as positional " + "parameter") + + # Keyword-only parameter passed by position with cached call + # should still raise ValueError + func_cached(1, 2, kw1=3, kw2=4) + + with raises(ValueError) as excinfo: + func_cached(1, 2, 3, kw2=4) + excinfo.match("Keyword-only parameter 'kw1' was passed as positional " + "parameter") + + # Test 'ignore' parameter + func_cached = memory.cache(func_with_kwonly_args, ignore=['kw2']) + assert func_cached(1, 2, kw1=3, kw2=4) == (1, 2, 3, 4) + assert func_cached(1, 2, kw1=3, kw2='ignored') == (1, 2, 3, 4) + + +def test_memory_func_with_signature(tmpdir): + memory = Memory(location=tmpdir.strpath, verbose=0) + func_cached = memory.cache(func_with_signature) + + assert func_cached(1, 2.) == 3. + + +def _setup_toy_cache(tmpdir, num_inputs=10): + memory = Memory(location=tmpdir.strpath, verbose=0) + + @memory.cache() + def get_1000_bytes(arg): + return 'a' * 1000 + + inputs = list(range(num_inputs)) + for arg in inputs: + get_1000_bytes(arg) + + func_id = _build_func_identifier(get_1000_bytes) + hash_dirnames = [get_1000_bytes._get_output_identifiers(arg)[1] + for arg in inputs] + + full_hashdirs = [os.path.join(get_1000_bytes.store_backend.location, + func_id, dirname) + for dirname in hash_dirnames] + return memory, full_hashdirs, get_1000_bytes + + +def test__get_items(tmpdir): + memory, expected_hash_dirs, _ = _setup_toy_cache(tmpdir) + items = memory.store_backend.get_items() + hash_dirs = [ci.path for ci in items] + assert set(hash_dirs) == set(expected_hash_dirs) + + def get_files_size(directory): + full_paths = [os.path.join(directory, fn) + for fn in os.listdir(directory)] + return sum(os.path.getsize(fp) for fp in full_paths) + + expected_hash_cache_sizes = [get_files_size(hash_dir) + for hash_dir in hash_dirs] + hash_cache_sizes = [ci.size for ci in items] + assert hash_cache_sizes == expected_hash_cache_sizes + + output_filenames = [os.path.join(hash_dir, 'output.pkl') + for hash_dir in hash_dirs] + + expected_last_accesses = [ + datetime.datetime.fromtimestamp(os.path.getatime(fn)) + for fn in output_filenames] + last_accesses = [ci.last_access for ci in items] + assert last_accesses == expected_last_accesses + + +def test__get_items_to_delete(tmpdir): + # test empty cache + memory, _, _ = _setup_toy_cache(tmpdir, num_inputs=0) + items_to_delete = memory.store_backend._get_items_to_delete('1K') + assert items_to_delete == [] + + memory, expected_hash_cachedirs, _ = _setup_toy_cache(tmpdir) + items = memory.store_backend.get_items() + # bytes_limit set to keep only one cache item (each hash cache + # folder is about 1000 bytes + metadata) + items_to_delete = memory.store_backend._get_items_to_delete('2K') + nb_hashes = len(expected_hash_cachedirs) + assert set.issubset(set(items_to_delete), set(items)) + assert len(items_to_delete) == nb_hashes - 1 + + # Sanity check bytes_limit=2048 is the same as bytes_limit='2K' + items_to_delete_2048b = memory.store_backend._get_items_to_delete(2048) + assert sorted(items_to_delete) == sorted(items_to_delete_2048b) + + # bytes_limit greater than the size of the cache + items_to_delete_empty = memory.store_backend._get_items_to_delete('1M') + assert items_to_delete_empty == [] + + # All the cache items need to be deleted + bytes_limit_too_small = 500 + items_to_delete_500b = memory.store_backend._get_items_to_delete( + bytes_limit_too_small + ) + assert set(items_to_delete_500b), set(items) + + # Test LRU property: surviving cache items should all have a more + # recent last_access that the ones that have been deleted + items_to_delete_6000b = memory.store_backend._get_items_to_delete(6000) + surviving_items = set(items).difference(items_to_delete_6000b) + + assert (max(ci.last_access for ci in items_to_delete_6000b) <= + min(ci.last_access for ci in surviving_items)) + + +def test_memory_reduce_size_bytes_limit(tmpdir): + memory, _, _ = _setup_toy_cache(tmpdir) + ref_cache_items = memory.store_backend.get_items() + + # By default memory.bytes_limit is None and reduce_size is a noop + memory.reduce_size() + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # No cache items deleted if bytes_limit greater than the size of + # the cache + memory.reduce_size(bytes_limit='1M') + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # bytes_limit is set so that only two cache items are kept + memory.reduce_size(bytes_limit='3K') + cache_items = memory.store_backend.get_items() + assert set.issubset(set(cache_items), set(ref_cache_items)) + assert len(cache_items) == 2 + + # bytes_limit set so that no cache item is kept + bytes_limit_too_small = 500 + memory.reduce_size(bytes_limit=bytes_limit_too_small) + cache_items = memory.store_backend.get_items() + assert cache_items == [] + + +def test_memory_reduce_size_items_limit(tmpdir): + memory, _, _ = _setup_toy_cache(tmpdir) + ref_cache_items = memory.store_backend.get_items() + + # By default reduce_size is a noop + memory.reduce_size() + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # No cache items deleted if items_limit greater than the size of + # the cache + memory.reduce_size(items_limit=10) + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # items_limit is set so that only two cache items are kept + memory.reduce_size(items_limit=2) + cache_items = memory.store_backend.get_items() + assert set.issubset(set(cache_items), set(ref_cache_items)) + assert len(cache_items) == 2 + + # item_limit set so that no cache item is kept + memory.reduce_size(items_limit=0) + cache_items = memory.store_backend.get_items() + assert cache_items == [] + + +def test_memory_reduce_size_age_limit(tmpdir): + import time + import datetime + memory, _, put_cache = _setup_toy_cache(tmpdir) + ref_cache_items = memory.store_backend.get_items() + + # By default reduce_size is a noop + memory.reduce_size() + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # No cache items deleted if age_limit big. + memory.reduce_size(age_limit=datetime.timedelta(days=1)) + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # age_limit is set so that only two cache items are kept + time.sleep(1) + put_cache(-1) + put_cache(-2) + memory.reduce_size(age_limit=datetime.timedelta(seconds=1)) + cache_items = memory.store_backend.get_items() + assert not set.issubset(set(cache_items), set(ref_cache_items)) + assert len(cache_items) == 2 + + # age_limit set so that no cache item is kept + memory.reduce_size(age_limit=datetime.timedelta(seconds=0)) + cache_items = memory.store_backend.get_items() + assert cache_items == [] + + +def test_memory_clear(tmpdir): + memory, _, g = _setup_toy_cache(tmpdir) + memory.clear() + + assert os.listdir(memory.store_backend.location) == [] + + # Check that the cache for functions hash is also reset. + assert not g._check_previous_func_code(stacklevel=4) + + +def fast_func_with_complex_output(): + complex_obj = ['a' * 1000] * 1000 + return complex_obj + + +def fast_func_with_conditional_complex_output(complex_output=True): + complex_obj = {str(i): i for i in range(int(1e5))} + return complex_obj if complex_output else 'simple output' + + +@with_multiprocessing +def test_cached_function_race_condition_when_persisting_output(tmpdir, capfd): + # Test race condition where multiple processes are writing into + # the same output.pkl. See + # https://github.com/joblib/joblib/issues/490 for more details. + memory = Memory(location=tmpdir.strpath) + func_cached = memory.cache(fast_func_with_complex_output) + + Parallel(n_jobs=2)(delayed(func_cached)() for i in range(3)) + + stdout, stderr = capfd.readouterr() + + # Checking both stdout and stderr (ongoing PR #434 may change + # logging destination) to make sure there is no exception while + # loading the results + exception_msg = 'Exception while loading results' + assert exception_msg not in stdout + assert exception_msg not in stderr + + +@with_multiprocessing +def test_cached_function_race_condition_when_persisting_output_2(tmpdir, + capfd): + # Test race condition in first attempt at solving + # https://github.com/joblib/joblib/issues/490. The race condition + # was due to the delay between seeing the cache directory created + # (interpreted as the result being cached) and the output.pkl being + # pickled. + memory = Memory(location=tmpdir.strpath) + func_cached = memory.cache(fast_func_with_conditional_complex_output) + + Parallel(n_jobs=2)(delayed(func_cached)(True if i % 2 == 0 else False) + for i in range(3)) + + stdout, stderr = capfd.readouterr() + + # Checking both stdout and stderr (ongoing PR #434 may change + # logging destination) to make sure there is no exception while + # loading the results + exception_msg = 'Exception while loading results' + assert exception_msg not in stdout + assert exception_msg not in stderr + + +def test_memory_recomputes_after_an_error_while_loading_results( + tmpdir, monkeypatch): + memory = Memory(location=tmpdir.strpath) + + def func(arg): + # This makes sure that the timestamp returned by two calls of + # func are different. This is needed on Windows where + # time.time resolution may not be accurate enough + time.sleep(0.01) + return arg, time.time() + + cached_func = memory.cache(func) + input_arg = 'arg' + arg, timestamp = cached_func(input_arg) + + # Make sure the function is correctly cached + assert arg == input_arg + + # Corrupting output.pkl to make sure that an error happens when + # loading the cached result + corrupt_single_cache_item(memory) + + # Make sure that corrupting the file causes recomputation and that + # a warning is issued. + recorded_warnings = monkeypatch_cached_func_warn(cached_func, monkeypatch) + recomputed_arg, recomputed_timestamp = cached_func(arg) + assert len(recorded_warnings) == 1 + exception_msg = 'Exception while loading results' + assert exception_msg in recorded_warnings[0] + assert recomputed_arg == arg + assert recomputed_timestamp > timestamp + + # Corrupting output.pkl to make sure that an error happens when + # loading the cached result + corrupt_single_cache_item(memory) + reference = cached_func.call_and_shelve(arg) + try: + reference.get() + raise AssertionError( + "It normally not possible to load a corrupted" + " MemorizedResult" + ) + except KeyError as e: + message = "is corrupted" + assert message in str(e.args) + + +class IncompleteStoreBackend(StoreBackendBase): + """This backend cannot be instantiated and should raise a TypeError.""" + pass + + +class DummyStoreBackend(StoreBackendBase): + """A dummy store backend that does nothing.""" + + def _open_item(self, *args, **kwargs): + """Open an item on store.""" + "Does nothing" + + def _item_exists(self, location): + """Check if an item location exists.""" + "Does nothing" + + def _move_item(self, src, dst): + """Move an item from src to dst in store.""" + "Does nothing" + + def create_location(self, location): + """Create location on store.""" + "Does nothing" + + def exists(self, obj): + """Check if an object exists in the store""" + return False + + def clear_location(self, obj): + """Clear object on store""" + "Does nothing" + + def get_items(self): + """Returns the whole list of items available in cache.""" + return [] + + def configure(self, location, *args, **kwargs): + """Configure the store""" + "Does nothing" + + +@parametrize("invalid_prefix", [None, dict(), list()]) +def test_register_invalid_store_backends_key(invalid_prefix): + # verify the right exceptions are raised when passing a wrong backend key. + with raises(ValueError) as excinfo: + register_store_backend(invalid_prefix, None) + excinfo.match(r'Store backend name should be a string*') + + +def test_register_invalid_store_backends_object(): + # verify the right exceptions are raised when passing a wrong backend + # object. + with raises(ValueError) as excinfo: + register_store_backend("fs", None) + excinfo.match(r'Store backend should inherit StoreBackendBase*') + + +def test_memory_default_store_backend(): + # test an unknown backend falls back into a FileSystemStoreBackend + with raises(TypeError) as excinfo: + Memory(location='/tmp/joblib', backend='unknown') + excinfo.match(r"Unknown location*") + + +def test_warning_on_unknown_location_type(): + class NonSupportedLocationClass: + pass + unsupported_location = NonSupportedLocationClass() + + with warns(UserWarning) as warninfo: + _store_backend_factory("local", location=unsupported_location) + + expected_mesage = ("Instantiating a backend using a " + "NonSupportedLocationClass as a location is not " + "supported by joblib") + assert expected_mesage in str(warninfo[0].message) + + +def test_instanciate_incomplete_store_backend(): + # Verify that registering an external incomplete store backend raises an + # exception when one tries to instantiate it. + backend_name = "isb" + register_store_backend(backend_name, IncompleteStoreBackend) + assert (backend_name, IncompleteStoreBackend) in _STORE_BACKENDS.items() + with raises(TypeError) as excinfo: + _store_backend_factory(backend_name, "fake_location") + excinfo.match(r"Can't instantiate abstract class IncompleteStoreBackend " + "(without an implementation for|with) abstract methods*") + + +def test_dummy_store_backend(): + # Verify that registering an external store backend works. + + backend_name = "dsb" + register_store_backend(backend_name, DummyStoreBackend) + assert (backend_name, DummyStoreBackend) in _STORE_BACKENDS.items() + + backend_obj = _store_backend_factory(backend_name, "dummy_location") + assert isinstance(backend_obj, DummyStoreBackend) + + +def test_instanciate_store_backend_with_pathlib_path(): + # Instantiate a FileSystemStoreBackend using a pathlib.Path object + path = pathlib.Path("some_folder") + backend_obj = _store_backend_factory("local", path) + assert backend_obj.location == "some_folder" + + +def test_filesystem_store_backend_repr(tmpdir): + # Verify string representation of a filesystem store backend. + + repr_pattern = 'FileSystemStoreBackend(location="{location}")' + backend = FileSystemStoreBackend() + assert backend.location is None + + repr(backend) # Should not raise an exception + + assert str(backend) == repr_pattern.format(location=None) + + # backend location is passed explicitly via the configure method (called + # by the internal _store_backend_factory function) + backend.configure(tmpdir.strpath) + + assert str(backend) == repr_pattern.format(location=tmpdir.strpath) + + repr(backend) # Should not raise an exception + + +def test_memory_objects_repr(tmpdir): + # Verify printable reprs of MemorizedResult, MemorizedFunc and Memory. + + def my_func(a, b): + return a + b + + memory = Memory(location=tmpdir.strpath, verbose=0) + memorized_func = memory.cache(my_func) + + memorized_func_repr = 'MemorizedFunc(func={func}, location={location})' + + assert str(memorized_func) == memorized_func_repr.format( + func=my_func, + location=memory.store_backend.location) + + memorized_result = memorized_func.call_and_shelve(42, 42) + + memorized_result_repr = ('MemorizedResult(location="{location}", ' + 'func="{func}", args_id="{args_id}")') + + assert str(memorized_result) == memorized_result_repr.format( + location=memory.store_backend.location, + func=memorized_result.func_id, + args_id=memorized_result.args_id) + + assert str(memory) == 'Memory(location={location})'.format( + location=memory.store_backend.location) + + +def test_memorized_result_pickle(tmpdir): + # Verify a MemoryResult object can be pickled/depickled. Non regression + # test introduced following issue + # https://github.com/joblib/joblib/issues/747 + + memory = Memory(location=tmpdir.strpath) + + @memory.cache + def g(x): + return x**2 + + memorized_result = g.call_and_shelve(4) + memorized_result_pickle = pickle.dumps(memorized_result) + memorized_result_loads = pickle.loads(memorized_result_pickle) + + assert memorized_result.store_backend.location == \ + memorized_result_loads.store_backend.location + assert memorized_result.func == memorized_result_loads.func + assert memorized_result.args_id == memorized_result_loads.args_id + assert str(memorized_result) == str(memorized_result_loads) + + +def compare(left, right, ignored_attrs=None): + if ignored_attrs is None: + ignored_attrs = [] + + left_vars = vars(left) + right_vars = vars(right) + assert set(left_vars.keys()) == set(right_vars.keys()) + for attr in left_vars.keys(): + if attr in ignored_attrs: + continue + assert left_vars[attr] == right_vars[attr] + + +@pytest.mark.parametrize('memory_kwargs', + [{'compress': 3, 'verbose': 2}, + {'mmap_mode': 'r', 'verbose': 5, + 'backend_options': {'parameter': 'unused'}}]) +def test_memory_pickle_dump_load(tmpdir, memory_kwargs): + memory = Memory(location=tmpdir.strpath, **memory_kwargs) + + memory_reloaded = pickle.loads(pickle.dumps(memory)) + + # Compare Memory instance before and after pickle roundtrip + compare(memory.store_backend, memory_reloaded.store_backend) + compare(memory, memory_reloaded, + ignored_attrs=set(['store_backend', 'timestamp', '_func_code_id'])) + assert hash(memory) == hash(memory_reloaded) + + func_cached = memory.cache(f) + + func_cached_reloaded = pickle.loads(pickle.dumps(func_cached)) + + # Compare MemorizedFunc instance before/after pickle roundtrip + compare(func_cached.store_backend, func_cached_reloaded.store_backend) + compare(func_cached, func_cached_reloaded, + ignored_attrs=set(['store_backend', 'timestamp', '_func_code_id'])) + assert hash(func_cached) == hash(func_cached_reloaded) + + # Compare MemorizedResult instance before/after pickle roundtrip + memorized_result = func_cached.call_and_shelve(1) + memorized_result_reloaded = pickle.loads(pickle.dumps(memorized_result)) + + compare(memorized_result.store_backend, + memorized_result_reloaded.store_backend) + compare(memorized_result, memorized_result_reloaded, + ignored_attrs=set(['store_backend', 'timestamp', '_func_code_id'])) + assert hash(memorized_result) == hash(memorized_result_reloaded) + + +def test_info_log(tmpdir, caplog): + caplog.set_level(logging.INFO) + x = 3 + + memory = Memory(location=tmpdir.strpath, verbose=20) + + @memory.cache + def f(x): + return x ** 2 + + _ = f(x) + assert "Querying" in caplog.text + caplog.clear() + + memory = Memory(location=tmpdir.strpath, verbose=0) + + @memory.cache + def f(x): + return x ** 2 + + _ = f(x) + assert "Querying" not in caplog.text + caplog.clear() + + +def test_deprecated_bytes_limit(tmpdir): + from joblib import __version__ + if __version__ >= "1.5": + raise DeprecationWarning( + "Bytes limit is deprecated and should be removed by 1.4" + ) + with pytest.warns(DeprecationWarning, match="bytes_limit"): + _ = Memory(location=tmpdir.strpath, bytes_limit='1K') + + +class TestCacheValidationCallback: + "Tests on parameter `cache_validation_callback`" + + @pytest.fixture() + def memory(self, tmp_path): + mem = Memory(location=tmp_path) + yield mem + mem.clear() + + def foo(self, x, d, delay=None): + d["run"] = True + if delay is not None: + time.sleep(delay) + return x * 2 + + def test_invalid_cache_validation_callback(self, memory): + "Test invalid values for `cache_validation_callback" + match = "cache_validation_callback needs to be callable. Got True." + with pytest.raises(ValueError, match=match): + memory.cache(cache_validation_callback=True) + + @pytest.mark.parametrize("consider_cache_valid", [True, False]) + def test_constant_cache_validation_callback( + self, memory, consider_cache_valid + ): + "Test expiry of old results" + f = memory.cache( + self.foo, cache_validation_callback=lambda _: consider_cache_valid, + ignore=["d"] + ) + + d1, d2 = {"run": False}, {"run": False} + assert f(2, d1) == 4 + assert f(2, d2) == 4 + + assert d1["run"] + assert d2["run"] != consider_cache_valid + + def test_memory_only_cache_long_run(self, memory): + "Test cache validity based on run duration." + + def cache_validation_callback(metadata): + duration = metadata['duration'] + if duration > 0.1: + return True + + f = memory.cache( + self.foo, cache_validation_callback=cache_validation_callback, + ignore=["d"] + ) + + # Short run are not cached + d1, d2 = {"run": False}, {"run": False} + assert f(2, d1, delay=0) == 4 + assert f(2, d2, delay=0) == 4 + assert d1["run"] + assert d2["run"] + + # Longer run are cached + d1, d2 = {"run": False}, {"run": False} + assert f(2, d1, delay=0.2) == 4 + assert f(2, d2, delay=0.2) == 4 + assert d1["run"] + assert not d2["run"] + + def test_memory_expires_after(self, memory): + "Test expiry of old cached results" + + f = memory.cache( + self.foo, cache_validation_callback=expires_after(seconds=.3), + ignore=["d"] + ) + + d1, d2, d3 = {"run": False}, {"run": False}, {"run": False} + assert f(2, d1) == 4 + assert f(2, d2) == 4 + time.sleep(.5) + assert f(2, d3) == 4 + + assert d1["run"] + assert not d2["run"] + assert d3["run"] diff --git a/testbed/joblib__joblib/joblib/test/test_missing_multiprocessing.py b/testbed/joblib__joblib/joblib/test/test_missing_multiprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..251925ced5208b4aaf09d9aab305eb44c7102818 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_missing_multiprocessing.py @@ -0,0 +1,32 @@ +""" +Pyodide and other single-threaded Python builds will be missing the +_multiprocessing module. Test that joblib still works in this environment. +""" + +import os +import subprocess +import sys + + +def test_missing_multiprocessing(tmp_path): + """ + Test that import joblib works even if _multiprocessing is missing. + + pytest has already imported everything from joblib. The most reasonable way + to test importing joblib with modified environment is to invoke a separate + Python process. This also ensures that we don't break other tests by + importing a bad `_multiprocessing` module. + """ + (tmp_path / "_multiprocessing.py").write_text( + 'raise ImportError("No _multiprocessing module!")' + ) + env = dict(os.environ) + # For subprocess, use current sys.path with our custom version of + # multiprocessing inserted. + env["PYTHONPATH"] = ":".join([str(tmp_path)] + sys.path) + subprocess.check_call( + [sys.executable, "-c", + "import joblib, math; " + "joblib.Parallel(n_jobs=1)(" + "joblib.delayed(math.sqrt)(i**2) for i in range(10))" + ], env=env) diff --git a/testbed/joblib__joblib/joblib/test/test_module.py b/testbed/joblib__joblib/joblib/test/test_module.py new file mode 100644 index 0000000000000000000000000000000000000000..a2257a4142d79996f3d299cb820927ae48a05810 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_module.py @@ -0,0 +1,53 @@ +import sys +import joblib +from joblib.testing import check_subprocess_call +from joblib.test.common import with_multiprocessing + + +def test_version(): + assert hasattr(joblib, '__version__'), ( + "There are no __version__ argument on the joblib module") + + +@with_multiprocessing +def test_no_start_method_side_effect_on_import(): + # check that importing joblib does not implicitly set the global + # start_method for multiprocessing. + code = """if True: + import joblib + import multiprocessing as mp + # The following line would raise RuntimeError if the + # start_method is already set. + mp.set_start_method("loky") + """ + check_subprocess_call([sys.executable, '-c', code]) + + +@with_multiprocessing +def test_no_semaphore_tracker_on_import(): + # check that importing joblib does not implicitly spawn a resource tracker + # or a semaphore tracker + code = """if True: + import joblib + from multiprocessing import semaphore_tracker + # The following line would raise RuntimeError if the + # start_method is already set. + msg = "multiprocessing.semaphore_tracker has been spawned on import" + assert semaphore_tracker._semaphore_tracker._fd is None, msg""" + if sys.version_info >= (3, 8): + # semaphore_tracker was renamed in Python 3.8: + code = code.replace("semaphore_tracker", "resource_tracker") + check_subprocess_call([sys.executable, '-c', code]) + + +@with_multiprocessing +def test_no_resource_tracker_on_import(): + code = """if True: + import joblib + from joblib.externals.loky.backend import resource_tracker + # The following line would raise RuntimeError if the + # start_method is already set. + msg = "loky.resource_tracker has been spawned on import" + assert resource_tracker._resource_tracker._fd is None, msg + """ + check_subprocess_call([sys.executable, '-c', code]) diff --git a/testbed/joblib__joblib/joblib/test/test_numpy_pickle.py b/testbed/joblib__joblib/joblib/test/test_numpy_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..9fee585c79ad219d3a9f8cdc6a55655b50099c09 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_numpy_pickle.py @@ -0,0 +1,1159 @@ +"""Test the numpy pickler as a replacement of the standard pickler.""" + +import copy +import os +import random +import re +import io +import sys +import warnings +import gzip +import zlib +import bz2 +import pickle +import socket +from contextlib import closing +import mmap +from pathlib import Path + +try: + import lzma +except ImportError: + lzma = None + +import pytest + +from joblib.test.common import np, with_numpy, with_lz4, without_lz4 +from joblib.test.common import with_memory_profiler, memory_used +from joblib.testing import parametrize, raises, warns + +# numpy_pickle is not a drop-in replacement of pickle, as it takes +# filenames instead of open files as arguments. +from joblib import numpy_pickle, register_compressor +from joblib.test import data + +from joblib.numpy_pickle_utils import _IO_BUFFER_SIZE +from joblib.numpy_pickle_utils import _detect_compressor +from joblib.numpy_pickle_utils import _is_numpy_array_byte_order_mismatch +from joblib.numpy_pickle_utils import _ensure_native_byte_order +from joblib.compressor import (_COMPRESSORS, _LZ4_PREFIX, CompressorWrapper, + LZ4_NOT_INSTALLED_ERROR, BinaryZlibFile) + + +############################################################################### +# Define a list of standard types. +# Borrowed from dill, initial author: Micheal McKerns: +# http://dev.danse.us/trac/pathos/browser/dill/dill_test2.py + +typelist = [] + +# testing types +_none = None +typelist.append(_none) +_type = type +typelist.append(_type) +_bool = bool(1) +typelist.append(_bool) +_int = int(1) +typelist.append(_int) +_float = float(1) +typelist.append(_float) +_complex = complex(1) +typelist.append(_complex) +_string = str(1) +typelist.append(_string) +_tuple = () +typelist.append(_tuple) +_list = [] +typelist.append(_list) +_dict = {} +typelist.append(_dict) +_builtin = len +typelist.append(_builtin) + + +def _function(x): + yield x + + +class _class: + def _method(self): + pass + + +class _newclass(object): + def _method(self): + pass + + +typelist.append(_function) +typelist.append(_class) +typelist.append(_newclass) # +_instance = _class() +typelist.append(_instance) +_object = _newclass() +typelist.append(_object) # + + +############################################################################### +# Tests + +@parametrize('compress', [0, 1]) +@parametrize('member', typelist) +def test_standard_types(tmpdir, compress, member): + # Test pickling and saving with standard types. + filename = tmpdir.join('test.pkl').strpath + numpy_pickle.dump(member, filename, compress=compress) + _member = numpy_pickle.load(filename) + # We compare the pickled instance to the reloaded one only if it + # can be compared to a copied one + if member == copy.deepcopy(member): + assert member == _member + + +def test_value_error(): + # Test inverting the input arguments to dump + with raises(ValueError): + numpy_pickle.dump('foo', dict()) + + +@parametrize('wrong_compress', [-1, 10, dict()]) +def test_compress_level_error(wrong_compress): + # Verify that passing an invalid compress argument raises an error. + exception_msg = ('Non valid compress level given: ' + '"{0}"'.format(wrong_compress)) + with raises(ValueError) as excinfo: + numpy_pickle.dump('dummy', 'foo', compress=wrong_compress) + excinfo.match(exception_msg) + + +@with_numpy +@parametrize('compress', [False, True, 0, 3, 'zlib']) +def test_numpy_persistence(tmpdir, compress): + filename = tmpdir.join('test.pkl').strpath + rnd = np.random.RandomState(0) + a = rnd.random_sample((10, 2)) + # We use 'a.T' to have a non C-contiguous array. + for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])): + filenames = numpy_pickle.dump(obj, filename, compress=compress) + + # All is cached in one file + assert len(filenames) == 1 + # Check that only one file was created + assert filenames[0] == filename + # Check that this file does exist + assert os.path.exists(filenames[0]) + + # Unpickle the object + obj_ = numpy_pickle.load(filename) + # Check that the items are indeed arrays + for item in obj_: + assert isinstance(item, np.ndarray) + # And finally, check that all the values are equal. + np.testing.assert_array_equal(np.array(obj), np.array(obj_)) + + # Now test with an array subclass + obj = np.memmap(filename + 'mmap', mode='w+', shape=4, dtype=np.float64) + filenames = numpy_pickle.dump(obj, filename, compress=compress) + # All is cached in one file + assert len(filenames) == 1 + + obj_ = numpy_pickle.load(filename) + if (type(obj) is not np.memmap and + hasattr(obj, '__array_prepare__')): + # We don't reconstruct memmaps + assert isinstance(obj_, type(obj)) + + np.testing.assert_array_equal(obj_, obj) + + # Test with an object containing multiple numpy arrays + obj = ComplexTestObject() + filenames = numpy_pickle.dump(obj, filename, compress=compress) + # All is cached in one file + assert len(filenames) == 1 + + obj_loaded = numpy_pickle.load(filename) + assert isinstance(obj_loaded, type(obj)) + np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float) + np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int) + np.testing.assert_array_equal(obj_loaded.array_obj, obj.array_obj) + + +@with_numpy +def test_numpy_persistence_bufferred_array_compression(tmpdir): + big_array = np.ones((_IO_BUFFER_SIZE + 100), dtype=np.uint8) + filename = tmpdir.join('test.pkl').strpath + numpy_pickle.dump(big_array, filename, compress=True) + arr_reloaded = numpy_pickle.load(filename) + + np.testing.assert_array_equal(big_array, arr_reloaded) + + +@with_numpy +def test_memmap_persistence(tmpdir): + rnd = np.random.RandomState(0) + a = rnd.random_sample(10) + filename = tmpdir.join('test1.pkl').strpath + numpy_pickle.dump(a, filename) + b = numpy_pickle.load(filename, mmap_mode='r') + + assert isinstance(b, np.memmap) + + # Test with an object containing multiple numpy arrays + filename = tmpdir.join('test2.pkl').strpath + obj = ComplexTestObject() + numpy_pickle.dump(obj, filename) + obj_loaded = numpy_pickle.load(filename, mmap_mode='r') + assert isinstance(obj_loaded, type(obj)) + assert isinstance(obj_loaded.array_float, np.memmap) + assert not obj_loaded.array_float.flags.writeable + assert isinstance(obj_loaded.array_int, np.memmap) + assert not obj_loaded.array_int.flags.writeable + # Memory map not allowed for numpy object arrays + assert not isinstance(obj_loaded.array_obj, np.memmap) + np.testing.assert_array_equal(obj_loaded.array_float, + obj.array_float) + np.testing.assert_array_equal(obj_loaded.array_int, + obj.array_int) + np.testing.assert_array_equal(obj_loaded.array_obj, + obj.array_obj) + + # Test we can write in memmapped arrays + obj_loaded = numpy_pickle.load(filename, mmap_mode='r+') + assert obj_loaded.array_float.flags.writeable + obj_loaded.array_float[0:10] = 10.0 + assert obj_loaded.array_int.flags.writeable + obj_loaded.array_int[0:10] = 10 + + obj_reloaded = numpy_pickle.load(filename, mmap_mode='r') + np.testing.assert_array_equal(obj_reloaded.array_float, + obj_loaded.array_float) + np.testing.assert_array_equal(obj_reloaded.array_int, + obj_loaded.array_int) + + # Test w+ mode is caught and the mode has switched to r+ + numpy_pickle.load(filename, mmap_mode='w+') + assert obj_loaded.array_int.flags.writeable + assert obj_loaded.array_int.mode == 'r+' + assert obj_loaded.array_float.flags.writeable + assert obj_loaded.array_float.mode == 'r+' + + +@with_numpy +def test_memmap_persistence_mixed_dtypes(tmpdir): + # loading datastructures that have sub-arrays with dtype=object + # should not prevent memmapping on fixed size dtype sub-arrays. + rnd = np.random.RandomState(0) + a = rnd.random_sample(10) + b = np.array([1, 'b'], dtype=object) + construct = (a, b) + filename = tmpdir.join('test.pkl').strpath + numpy_pickle.dump(construct, filename) + a_clone, b_clone = numpy_pickle.load(filename, mmap_mode='r') + + # the floating point array has been memory mapped + assert isinstance(a_clone, np.memmap) + + # the object-dtype array has been loaded in memory + assert not isinstance(b_clone, np.memmap) + + +@with_numpy +def test_masked_array_persistence(tmpdir): + # The special-case picker fails, because saving masked_array + # not implemented, but it just delegates to the standard pickler. + rnd = np.random.RandomState(0) + a = rnd.random_sample(10) + a = np.ma.masked_greater(a, 0.5) + filename = tmpdir.join('test.pkl').strpath + numpy_pickle.dump(a, filename) + b = numpy_pickle.load(filename, mmap_mode='r') + assert isinstance(b, np.ma.masked_array) + + +@with_numpy +def test_compress_mmap_mode_warning(tmpdir): + # Test the warning in case of compress + mmap_mode + rnd = np.random.RandomState(0) + a = rnd.random_sample(10) + this_filename = tmpdir.join('test.pkl').strpath + numpy_pickle.dump(a, this_filename, compress=1) + with warns(UserWarning) as warninfo: + numpy_pickle.load(this_filename, mmap_mode='r+') + debug_msg = "\n".join([str(w) for w in warninfo]) + warninfo = [w.message for w in warninfo] + assert len(warninfo) == 1, debug_msg + assert ( + str(warninfo[0]) == + 'mmap_mode "r+" is not compatible with compressed ' + f'file {this_filename}. "r+" flag will be ignored.' + ) + + +@with_numpy +@parametrize('cache_size', [None, 0, 10]) +def test_cache_size_warning(tmpdir, cache_size): + # Check deprecation warning raised when cache size is not None + filename = tmpdir.join('test.pkl').strpath + rnd = np.random.RandomState(0) + a = rnd.random_sample((10, 2)) + + warnings.simplefilter("always") + with warnings.catch_warnings(record=True) as warninfo: + numpy_pickle.dump(a, filename, cache_size=cache_size) + expected_nb_warnings = 1 if cache_size is not None else 0 + assert len(warninfo) == expected_nb_warnings + for w in warninfo: + assert w.category == DeprecationWarning + assert (str(w.message) == + "Please do not set 'cache_size' in joblib.dump, this " + "parameter has no effect and will be removed. You " + "used 'cache_size={0}'".format(cache_size)) + + +@with_numpy +@with_memory_profiler +@parametrize('compress', [True, False]) +def test_memory_usage(tmpdir, compress): + # Verify memory stays within expected bounds. + filename = tmpdir.join('test.pkl').strpath + small_array = np.ones((10, 10)) + big_array = np.ones(shape=100 * int(1e6), dtype=np.uint8) + + for obj in (small_array, big_array): + size = obj.nbytes / 1e6 + obj_filename = filename + str(np.random.randint(0, 1000)) + mem_used = memory_used(numpy_pickle.dump, + obj, obj_filename, compress=compress) + + # The memory used to dump the object shouldn't exceed the buffer + # size used to write array chunks (16MB). + write_buf_size = _IO_BUFFER_SIZE + 16 * 1024 ** 2 / 1e6 + assert mem_used <= write_buf_size + + mem_used = memory_used(numpy_pickle.load, obj_filename) + # memory used should be less than array size + buffer size used to + # read the array chunk by chunk. + read_buf_size = 32 + _IO_BUFFER_SIZE # MiB + assert mem_used < size + read_buf_size + + +@with_numpy +def test_compressed_pickle_dump_and_load(tmpdir): + expected_list = [np.arange(5, dtype=np.dtype('i8')), + np.arange(5, dtype=np.dtype('f8')), + np.array([1, 'abc', {'a': 1, 'b': 2}], dtype='O'), + np.arange(256, dtype=np.uint8).tobytes(), + u"C'est l'\xe9t\xe9 !"] + + fname = tmpdir.join('temp.pkl.gz').strpath + + dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1) + assert len(dumped_filenames) == 1 + result_list = numpy_pickle.load(fname) + for result, expected in zip(result_list, expected_list): + if isinstance(expected, np.ndarray): + expected = _ensure_native_byte_order(expected) + assert result.dtype == expected.dtype + np.testing.assert_equal(result, expected) + else: + assert result == expected + + +def _check_pickle(filename, expected_list, mmap_mode=None): + """Helper function to test joblib pickle content. + + Note: currently only pickles containing an iterable are supported + by this function. + """ + version_match = re.match(r'.+py(\d)(\d).+', filename) + py_version_used_for_writing = int(version_match.group(1)) + + py_version_to_default_pickle_protocol = {2: 2, 3: 3} + pickle_reading_protocol = py_version_to_default_pickle_protocol.get(3, 4) + pickle_writing_protocol = py_version_to_default_pickle_protocol.get( + py_version_used_for_writing, 4) + if pickle_reading_protocol >= pickle_writing_protocol: + try: + with warnings.catch_warnings(record=True) as warninfo: + warnings.simplefilter('always') + warnings.filterwarnings( + 'ignore', module='numpy', + message='The compiler package is deprecated') + result_list = numpy_pickle.load(filename, mmap_mode=mmap_mode) + filename_base = os.path.basename(filename) + expected_nb_deprecation_warnings = 1 if ( + "_0.9" in filename_base or "_0.8.4" in filename_base) else 0 + + expected_nb_user_warnings = 3 if ( + re.search("_0.1.+.pkl$", filename_base) and + mmap_mode is not None) else 0 + expected_nb_warnings = \ + expected_nb_deprecation_warnings + expected_nb_user_warnings + assert len(warninfo) == expected_nb_warnings + + deprecation_warnings = [ + w for w in warninfo if issubclass( + w.category, DeprecationWarning)] + user_warnings = [ + w for w in warninfo if issubclass( + w.category, UserWarning)] + for w in deprecation_warnings: + assert (str(w.message) == + "The file '{0}' has been generated with a joblib " + "version less than 0.10. Please regenerate this " + "pickle file.".format(filename)) + + for w in user_warnings: + escaped_filename = re.escape(filename) + assert re.search( + f"memmapped.+{escaped_filename}.+segmentation fault", + str(w.message)) + + for result, expected in zip(result_list, expected_list): + if isinstance(expected, np.ndarray): + expected = _ensure_native_byte_order(expected) + assert result.dtype == expected.dtype + np.testing.assert_equal(result, expected) + else: + assert result == expected + except Exception as exc: + # When trying to read with python 3 a pickle generated + # with python 2 we expect a user-friendly error + if py_version_used_for_writing == 2: + assert isinstance(exc, ValueError) + message = ('You may be trying to read with ' + 'python 3 a joblib pickle generated with python 2.') + assert message in str(exc) + elif filename.endswith('.lz4') and with_lz4.args[0]: + assert isinstance(exc, ValueError) + assert LZ4_NOT_INSTALLED_ERROR in str(exc) + else: + raise + else: + # Pickle protocol used for writing is too high. We expect a + # "unsupported pickle protocol" error message + try: + numpy_pickle.load(filename) + raise AssertionError('Numpy pickle loading should ' + 'have raised a ValueError exception') + except ValueError as e: + message = 'unsupported pickle protocol: {0}'.format( + pickle_writing_protocol) + assert message in str(e.args) + + +@with_numpy +def test_joblib_pickle_across_python_versions(): + # We need to be specific about dtypes in particular endianness + # because the pickles can be generated on one architecture and + # the tests run on another one. See + # https://github.com/joblib/joblib/issues/279. + expected_list = [np.arange(5, dtype=np.dtype('i8'), ('', '>f8')]), + np.arange(3, dtype=np.dtype('>i8')), + np.arange(3, dtype=np.dtype('>f8'))] + + # Verify the byteorder mismatch is correctly detected. + for array in be_arrays: + if sys.byteorder == 'big': + assert not _is_numpy_array_byte_order_mismatch(array) + else: + assert _is_numpy_array_byte_order_mismatch(array) + converted = _ensure_native_byte_order(array) + if converted.dtype.fields: + for f in converted.dtype.fields.values(): + f[0].byteorder == '=' + else: + assert converted.dtype.byteorder == "=" + + # List of numpy arrays with little endian byteorder. + le_arrays = [np.array([(1, 2.0), (3, 4.0)], + dtype=[('', ' size + np.testing.assert_array_equal(obj, memmaps) + + +def test_register_compressor(tmpdir): + # Check that registering compressor file works. + compressor_name = 'test-name' + compressor_prefix = 'test-prefix' + + class BinaryCompressorTestFile(io.BufferedIOBase): + pass + + class BinaryCompressorTestWrapper(CompressorWrapper): + + def __init__(self): + CompressorWrapper.__init__(self, obj=BinaryCompressorTestFile, + prefix=compressor_prefix) + + register_compressor(compressor_name, BinaryCompressorTestWrapper()) + + assert (_COMPRESSORS[compressor_name].fileobj_factory == + BinaryCompressorTestFile) + assert _COMPRESSORS[compressor_name].prefix == compressor_prefix + + # Remove this dummy compressor file from extra compressors because other + # tests might fail because of this + _COMPRESSORS.pop(compressor_name) + + +@parametrize('invalid_name', [1, (), {}]) +def test_register_compressor_invalid_name(invalid_name): + # Test that registering an invalid compressor name is not allowed. + with raises(ValueError) as excinfo: + register_compressor(invalid_name, None) + excinfo.match("Compressor name should be a string") + + +def test_register_compressor_invalid_fileobj(): + # Test that registering an invalid file object is not allowed. + + class InvalidFileObject(): + pass + + class InvalidFileObjectWrapper(CompressorWrapper): + def __init__(self): + CompressorWrapper.__init__(self, obj=InvalidFileObject, + prefix=b'prefix') + + with raises(ValueError) as excinfo: + register_compressor('invalid', InvalidFileObjectWrapper()) + + excinfo.match("Compressor 'fileobj_factory' attribute should implement " + "the file object interface") + + +class AnotherZlibCompressorWrapper(CompressorWrapper): + + def __init__(self): + CompressorWrapper.__init__(self, obj=BinaryZlibFile, prefix=b'prefix') + + +class StandardLibGzipCompressorWrapper(CompressorWrapper): + + def __init__(self): + CompressorWrapper.__init__(self, obj=gzip.GzipFile, prefix=b'prefix') + + +def test_register_compressor_already_registered(): + # Test registration of existing compressor files. + compressor_name = 'test-name' + + # register a test compressor + register_compressor(compressor_name, AnotherZlibCompressorWrapper()) + + with raises(ValueError) as excinfo: + register_compressor(compressor_name, + StandardLibGzipCompressorWrapper()) + excinfo.match("Compressor '{}' already registered." + .format(compressor_name)) + + register_compressor(compressor_name, StandardLibGzipCompressorWrapper(), + force=True) + + assert compressor_name in _COMPRESSORS + assert _COMPRESSORS[compressor_name].fileobj_factory == gzip.GzipFile + + # Remove this dummy compressor file from extra compressors because other + # tests might fail because of this + _COMPRESSORS.pop(compressor_name) + + +@with_lz4 +def test_lz4_compression(tmpdir): + # Check that lz4 can be used when dependency is available. + import lz4.frame + compressor = 'lz4' + assert compressor in _COMPRESSORS + assert _COMPRESSORS[compressor].fileobj_factory == lz4.frame.LZ4FrameFile + + fname = tmpdir.join('test.pkl').strpath + data = 'test data' + numpy_pickle.dump(data, fname, compress=compressor) + + with open(fname, 'rb') as f: + assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX + assert numpy_pickle.load(fname) == data + + # Test that LZ4 is applied based on file extension + numpy_pickle.dump(data, fname + '.lz4') + with open(fname, 'rb') as f: + assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX + assert numpy_pickle.load(fname) == data + + +@without_lz4 +def test_lz4_compression_without_lz4(tmpdir): + # Check that lz4 cannot be used when dependency is not available. + fname = tmpdir.join('test.nolz4').strpath + data = 'test data' + msg = LZ4_NOT_INSTALLED_ERROR + with raises(ValueError) as excinfo: + numpy_pickle.dump(data, fname, compress='lz4') + excinfo.match(msg) + + with raises(ValueError) as excinfo: + numpy_pickle.dump(data, fname + '.lz4') + excinfo.match(msg) + + +protocols = [pickle.DEFAULT_PROTOCOL] +if pickle.HIGHEST_PROTOCOL != pickle.DEFAULT_PROTOCOL: + protocols.append(pickle.HIGHEST_PROTOCOL) + + +@with_numpy +@parametrize('protocol', protocols) +def test_memmap_alignment_padding(tmpdir, protocol): + # Test that memmaped arrays returned by numpy.load are correctly aligned + fname = tmpdir.join('test.mmap').strpath + + a = np.random.randn(2) + numpy_pickle.dump(a, fname, protocol=protocol) + memmap = numpy_pickle.load(fname, mmap_mode='r') + assert isinstance(memmap, np.memmap) + np.testing.assert_array_equal(a, memmap) + assert ( + memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0) + assert memmap.flags.aligned + + array_list = [ + np.random.randn(2), np.random.randn(2), + np.random.randn(2), np.random.randn(2) + ] + + # On Windows OSError 22 if reusing the same path for memmap ... + fname = tmpdir.join('test1.mmap').strpath + numpy_pickle.dump(array_list, fname, protocol=protocol) + l_reloaded = numpy_pickle.load(fname, mmap_mode='r') + + for idx, memmap in enumerate(l_reloaded): + assert isinstance(memmap, np.memmap) + np.testing.assert_array_equal(array_list[idx], memmap) + assert ( + memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0) + assert memmap.flags.aligned + + array_dict = { + 'a0': np.arange(2, dtype=np.uint8), + 'a1': np.arange(3, dtype=np.uint8), + 'a2': np.arange(5, dtype=np.uint8), + 'a3': np.arange(7, dtype=np.uint8), + 'a4': np.arange(11, dtype=np.uint8), + 'a5': np.arange(13, dtype=np.uint8), + 'a6': np.arange(17, dtype=np.uint8), + 'a7': np.arange(19, dtype=np.uint8), + 'a8': np.arange(23, dtype=np.uint8), + } + + # On Windows OSError 22 if reusing the same path for memmap ... + fname = tmpdir.join('test2.mmap').strpath + numpy_pickle.dump(array_dict, fname, protocol=protocol) + d_reloaded = numpy_pickle.load(fname, mmap_mode='r') + + for key, memmap in d_reloaded.items(): + assert isinstance(memmap, np.memmap) + np.testing.assert_array_equal(array_dict[key], memmap) + assert ( + memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0) + assert memmap.flags.aligned diff --git a/testbed/joblib__joblib/joblib/test/test_numpy_pickle_compat.py b/testbed/joblib__joblib/joblib/test/test_numpy_pickle_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..9e95393b19e979593c7037d0d4fb740e47131dde --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_numpy_pickle_compat.py @@ -0,0 +1,16 @@ +"""Test the old numpy pickler, compatibility version.""" + +# numpy_pickle is not a drop-in replacement of pickle, as it takes +# filenames instead of open files as arguments. +from joblib import numpy_pickle_compat + + +def test_z_file(tmpdir): + # Test saving and loading data with Zfiles. + filename = tmpdir.join('test.pkl').strpath + data = numpy_pickle_compat.asbytes('Foo, \n Bar, baz, \n\nfoobar') + with open(filename, 'wb') as f: + numpy_pickle_compat.write_zfile(f, data) + with open(filename, 'rb') as f: + data_read = numpy_pickle_compat.read_zfile(f) + assert data == data_read diff --git a/testbed/joblib__joblib/joblib/test/test_numpy_pickle_utils.py b/testbed/joblib__joblib/joblib/test/test_numpy_pickle_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5c414a2227cbf6094dc594f6712139d4fd397a9d --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_numpy_pickle_utils.py @@ -0,0 +1,9 @@ +from joblib.compressor import BinaryZlibFile +from joblib.testing import parametrize + + +@parametrize('filename', ['test', u'test']) # testing str and unicode names +def test_binary_zlib_file(tmpdir, filename): + """Testing creation of files depending on the type of the filenames.""" + binary_file = BinaryZlibFile(tmpdir.join(filename).strpath, mode='wb') + binary_file.close() diff --git a/testbed/joblib__joblib/joblib/test/test_parallel.py b/testbed/joblib__joblib/joblib/test/test_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..21f06faa01c3ed93b80accad494e6a0482cc2e72 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_parallel.py @@ -0,0 +1,2034 @@ +""" +Test the parallel module. +""" + +# Author: Gael Varoquaux +# Copyright (c) 2010-2011 Gael Varoquaux +# License: BSD Style, 3 clauses. + +import os +import sys +import time +import mmap +import weakref +import warnings +import threading +from traceback import format_exception +from math import sqrt +from time import sleep +from pickle import PicklingError +from contextlib import nullcontext +from multiprocessing import TimeoutError +import pytest + +import joblib +from joblib import parallel +from joblib import dump, load + +from joblib._multiprocessing_helpers import mp + +from joblib.test.common import np, with_numpy +from joblib.test.common import with_multiprocessing +from joblib.test.common import IS_PYPY, force_gc_pypy +from joblib.testing import (parametrize, raises, check_subprocess_call, + skipif, warns) + +if mp is not None: + # Loky is not available if multiprocessing is not + from joblib.externals.loky import get_reusable_executor + +from queue import Queue + +try: + import posix +except ImportError: + posix = None + +try: + from ._openmp_test_helper.parallel_sum import parallel_sum +except ImportError: + parallel_sum = None + +try: + import distributed +except ImportError: + distributed = None + +from joblib._parallel_backends import SequentialBackend +from joblib._parallel_backends import ThreadingBackend +from joblib._parallel_backends import MultiprocessingBackend +from joblib._parallel_backends import ParallelBackendBase +from joblib._parallel_backends import LokyBackend + +from joblib.parallel import Parallel, delayed +from joblib.parallel import parallel_config +from joblib.parallel import parallel_backend +from joblib.parallel import register_parallel_backend +from joblib.parallel import effective_n_jobs, cpu_count + +from joblib.parallel import mp, BACKENDS, DEFAULT_BACKEND + + +RETURN_GENERATOR_BACKENDS = BACKENDS.copy() +RETURN_GENERATOR_BACKENDS.pop("multiprocessing", None) + +ALL_VALID_BACKENDS = [None] + sorted(BACKENDS.keys()) +# Add instances of backend classes deriving from ParallelBackendBase +ALL_VALID_BACKENDS += [BACKENDS[backend_str]() for backend_str in BACKENDS] +if mp is None: + PROCESS_BACKENDS = [] +else: + PROCESS_BACKENDS = ['multiprocessing', 'loky'] +PARALLEL_BACKENDS = PROCESS_BACKENDS + ['threading'] + +if hasattr(mp, 'get_context'): + # Custom multiprocessing context in Python 3.4+ + ALL_VALID_BACKENDS.append(mp.get_context('spawn')) + +DefaultBackend = BACKENDS[DEFAULT_BACKEND] + + +def get_workers(backend): + return getattr(backend, '_pool', getattr(backend, '_workers', None)) + + +def division(x, y): + return x / y + + +def square(x): + return x ** 2 + + +class MyExceptionWithFinickyInit(Exception): + """An exception class with non trivial __init__ + """ + def __init__(self, a, b, c, d): + pass + + +def exception_raiser(x, custom_exception=False): + if x == 7: + raise (MyExceptionWithFinickyInit('a', 'b', 'c', 'd') + if custom_exception else ValueError) + return x + + +def interrupt_raiser(x): + time.sleep(.05) + raise KeyboardInterrupt + + +def f(x, y=0, z=0): + """ A module-level function so that it can be spawn with + multiprocessing. + """ + return x ** 2 + y + z + + +def _active_backend_type(): + return type(parallel.get_active_backend()[0]) + + +def parallel_func(inner_n_jobs, backend): + return Parallel(n_jobs=inner_n_jobs, backend=backend)( + delayed(square)(i) for i in range(3)) + + +############################################################################### +def test_cpu_count(): + assert cpu_count() > 0 + + +def test_effective_n_jobs(): + assert effective_n_jobs() > 0 + + +@parametrize("context", [parallel_config, parallel_backend]) +@pytest.mark.parametrize( + "backend_n_jobs, expected_n_jobs", + [(3, 3), (-1, effective_n_jobs(n_jobs=-1)), (None, 1)], + ids=["positive-int", "negative-int", "None"] +) +@with_multiprocessing +def test_effective_n_jobs_None(context, backend_n_jobs, expected_n_jobs): + # check the number of effective jobs when `n_jobs=None` + # non-regression test for https://github.com/joblib/joblib/issues/984 + with context("threading", n_jobs=backend_n_jobs): + # when using a backend, the default of number jobs will be the one set + # in the backend + assert effective_n_jobs(n_jobs=None) == expected_n_jobs + # without any backend, None will default to a single job + assert effective_n_jobs(n_jobs=None) == 1 + + +############################################################################### +# Test parallel + +@parametrize('backend', ALL_VALID_BACKENDS) +@parametrize('n_jobs', [1, 2, -1, -2]) +@parametrize('verbose', [2, 11, 100]) +def test_simple_parallel(backend, n_jobs, verbose): + assert ([square(x) for x in range(5)] == + Parallel(n_jobs=n_jobs, backend=backend, + verbose=verbose)( + delayed(square)(x) for x in range(5))) + + +@parametrize('backend', ALL_VALID_BACKENDS) +def test_main_thread_renamed_no_warning(backend, monkeypatch): + # Check that no default backend relies on the name of the main thread: + # https://github.com/joblib/joblib/issues/180#issuecomment-253266247 + # Some programs use a different name for the main thread. This is the case + # for uWSGI apps for instance. + monkeypatch.setattr(target=threading.current_thread(), name='name', + value='some_new_name_for_the_main_thread') + + with warnings.catch_warnings(record=True) as warninfo: + results = Parallel(n_jobs=2, backend=backend)( + delayed(square)(x) for x in range(3)) + assert results == [0, 1, 4] + + # Due to the default parameters of LokyBackend, there is a chance that + # warninfo catches Warnings from worker timeouts. We remove it if it exists + warninfo = [w for w in warninfo if "worker timeout" not in str(w.message)] + + # The multiprocessing backend will raise a warning when detecting that is + # started from the non-main thread. Let's check that there is no false + # positive because of the name change. + assert len(warninfo) == 0 + + +def _assert_warning_nested(backend, inner_n_jobs, expected): + with warnings.catch_warnings(record=True) as warninfo: + warnings.simplefilter("always") + parallel_func(backend=backend, inner_n_jobs=inner_n_jobs) + + warninfo = [w.message for w in warninfo] + if expected: + if warninfo: + warnings_are_correct = all( + 'backed parallel loops cannot' in each.args[0] + for each in warninfo + ) + # With Python nogil, when the outer backend is threading, we might + # see more that one warning + warnings_have_the_right_length = ( + len(warninfo) >= 1 if getattr(sys.flags, 'nogil', False) + else len(warninfo) == 1) + return warnings_are_correct and warnings_have_the_right_length + + return False + else: + assert not warninfo + return True + + +@with_multiprocessing +@parametrize('parent_backend,child_backend,expected', [ + ('loky', 'multiprocessing', True), + ('loky', 'loky', False), + ('multiprocessing', 'multiprocessing', True), + ('multiprocessing', 'loky', True), + ('threading', 'multiprocessing', True), + ('threading', 'loky', True), +]) +def test_nested_parallel_warnings(parent_backend, child_backend, expected): + + # no warnings if inner_n_jobs=1 + Parallel(n_jobs=2, backend=parent_backend)( + delayed(_assert_warning_nested)( + backend=child_backend, inner_n_jobs=1, + expected=False) + for _ in range(5)) + + # warnings if inner_n_jobs != 1 and expected + res = Parallel(n_jobs=2, backend=parent_backend)( + delayed(_assert_warning_nested)( + backend=child_backend, inner_n_jobs=2, + expected=expected) + for _ in range(5)) + + # warning handling is not thread safe. One thread might see multiple + # warning or no warning at all. + if parent_backend == "threading": + if IS_PYPY and not any(res): + # Related to joblib#1426, should be removed once it is solved. + pytest.xfail(reason="This test often fails in PyPy.") + assert any(res) + else: + assert all(res) + + +@with_multiprocessing +@parametrize('backend', ['loky', 'multiprocessing', 'threading']) +def test_background_thread_parallelism(backend): + is_run_parallel = [False] + + def background_thread(is_run_parallel): + with warnings.catch_warnings(record=True) as warninfo: + Parallel(n_jobs=2)( + delayed(sleep)(.1) for _ in range(4)) + print(len(warninfo)) + is_run_parallel[0] = len(warninfo) == 0 + + t = threading.Thread(target=background_thread, args=(is_run_parallel,)) + t.start() + t.join() + assert is_run_parallel[0] + + +def nested_loop(backend): + Parallel(n_jobs=2, backend=backend)( + delayed(square)(.01) for _ in range(2)) + + +@parametrize('child_backend', BACKENDS) +@parametrize('parent_backend', BACKENDS) +def test_nested_loop(parent_backend, child_backend): + Parallel(n_jobs=2, backend=parent_backend)( + delayed(nested_loop)(child_backend) for _ in range(2)) + + +def raise_exception(backend): + raise ValueError + + +@with_multiprocessing +def test_nested_loop_with_exception_with_loky(): + with raises(ValueError): + with Parallel(n_jobs=2, backend="loky") as parallel: + parallel([delayed(nested_loop)("loky"), + delayed(raise_exception)("loky")]) + + +def test_mutate_input_with_threads(): + """Input is mutable when using the threading backend""" + q = Queue(maxsize=5) + Parallel(n_jobs=2, backend="threading")( + delayed(q.put)(1) for _ in range(5)) + assert q.full() + + +@parametrize('n_jobs', [1, 2, 3]) +def test_parallel_kwargs(n_jobs): + """Check the keyword argument processing of pmap.""" + lst = range(10) + assert ([f(x, y=1) for x in lst] == + Parallel(n_jobs=n_jobs)(delayed(f)(x, y=1) for x in lst)) + + +@parametrize('backend', PARALLEL_BACKENDS) +def test_parallel_as_context_manager(backend): + lst = range(10) + expected = [f(x, y=1) for x in lst] + + with Parallel(n_jobs=4, backend=backend) as p: + # Internally a pool instance has been eagerly created and is managed + # via the context manager protocol + managed_backend = p._backend + + # We make call with the managed parallel object several times inside + # the managed block: + assert expected == p(delayed(f)(x, y=1) for x in lst) + assert expected == p(delayed(f)(x, y=1) for x in lst) + + # Those calls have all used the same pool instance: + if mp is not None: + assert get_workers(managed_backend) is get_workers(p._backend) + + # As soon as we exit the context manager block, the pool is terminated and + # no longer referenced from the parallel object: + if mp is not None: + assert get_workers(p._backend) is None + + # It's still possible to use the parallel instance in non-managed mode: + assert expected == p(delayed(f)(x, y=1) for x in lst) + if mp is not None: + assert get_workers(p._backend) is None + + +@with_multiprocessing +def test_parallel_pickling(): + """ Check that pmap captures the errors when it is passed an object + that cannot be pickled. + """ + class UnpicklableObject(object): + def __reduce__(self): + raise RuntimeError('123') + + with raises(PicklingError, match=r"the task to send"): + Parallel(n_jobs=2, backend='loky')(delayed(id)( + UnpicklableObject()) for _ in range(10)) + + +@parametrize('backend', PARALLEL_BACKENDS) +def test_parallel_timeout_success(backend): + # Check that timeout isn't thrown when function is fast enough + assert len(Parallel(n_jobs=2, backend=backend, timeout=30)( + delayed(sleep)(0.001) for x in range(10))) == 10 + + +@with_multiprocessing +@parametrize('backend', PARALLEL_BACKENDS) +def test_parallel_timeout_fail(backend): + # Check that timeout properly fails when function is too slow + with raises(TimeoutError): + Parallel(n_jobs=2, backend=backend, timeout=0.01)( + delayed(sleep)(10) for x in range(10)) + + +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_error_capture(backend): + # Check that error are captured, and that correct exceptions + # are raised. + if mp is not None: + with raises(ZeroDivisionError): + Parallel(n_jobs=2, backend=backend)( + [delayed(division)(x, y) + for x, y in zip((0, 1), (1, 0))]) + + with raises(KeyboardInterrupt): + Parallel(n_jobs=2, backend=backend)( + [delayed(interrupt_raiser)(x) for x in (1, 0)]) + + # Try again with the context manager API + with Parallel(n_jobs=2, backend=backend) as parallel: + assert get_workers(parallel._backend) is not None + original_workers = get_workers(parallel._backend) + + with raises(ZeroDivisionError): + parallel([delayed(division)(x, y) + for x, y in zip((0, 1), (1, 0))]) + + # The managed pool should still be available and be in a working + # state despite the previously raised (and caught) exception + assert get_workers(parallel._backend) is not None + + # The pool should have been interrupted and restarted: + assert get_workers(parallel._backend) is not original_workers + + assert ([f(x, y=1) for x in range(10)] == + parallel(delayed(f)(x, y=1) for x in range(10))) + + original_workers = get_workers(parallel._backend) + with raises(KeyboardInterrupt): + parallel([delayed(interrupt_raiser)(x) for x in (1, 0)]) + + # The pool should still be available despite the exception + assert get_workers(parallel._backend) is not None + + # The pool should have been interrupted and restarted: + assert get_workers(parallel._backend) is not original_workers + + assert ([f(x, y=1) for x in range(10)] == + parallel(delayed(f)(x, y=1) for x in range(10))), ( + parallel._iterating, parallel.n_completed_tasks, + parallel.n_dispatched_tasks, parallel._aborting + ) + + # Check that the inner pool has been terminated when exiting the + # context manager + assert get_workers(parallel._backend) is None + else: + with raises(KeyboardInterrupt): + Parallel(n_jobs=2)( + [delayed(interrupt_raiser)(x) for x in (1, 0)]) + + # wrapped exceptions should inherit from the class of the original + # exception to make it easy to catch them + with raises(ZeroDivisionError): + Parallel(n_jobs=2)( + [delayed(division)(x, y) for x, y in zip((0, 1), (1, 0))]) + + with raises(MyExceptionWithFinickyInit): + Parallel(n_jobs=2, verbose=0)( + (delayed(exception_raiser)(i, custom_exception=True) + for i in range(30))) + + +@with_multiprocessing +@parametrize('backend', BACKENDS) +def test_error_in_task_iterator(backend): + + def my_generator(raise_at=0): + for i in range(20): + if i == raise_at: + raise ValueError("Iterator Raising Error") + yield i + + with Parallel(n_jobs=2, backend=backend) as p: + # The error is raised in the pre-dispatch phase + with raises(ValueError, match="Iterator Raising Error"): + p(delayed(square)(i) for i in my_generator(raise_at=0)) + + # The error is raised when dispatching a new task after the + # pre-dispatch (likely to happen in a different thread) + with raises(ValueError, match="Iterator Raising Error"): + p(delayed(square)(i) for i in my_generator(raise_at=5)) + + # Same, but raises long after the pre-dispatch phase + with raises(ValueError, match="Iterator Raising Error"): + p(delayed(square)(i) for i in my_generator(raise_at=19)) + + +def consumer(queue, item): + queue.append('Consumed %s' % item) + + +@parametrize('backend', BACKENDS) +@parametrize('batch_size, expected_queue', + [(1, ['Produced 0', 'Consumed 0', + 'Produced 1', 'Consumed 1', + 'Produced 2', 'Consumed 2', + 'Produced 3', 'Consumed 3', + 'Produced 4', 'Consumed 4', + 'Produced 5', 'Consumed 5']), + (4, [ # First Batch + 'Produced 0', 'Produced 1', 'Produced 2', 'Produced 3', + 'Consumed 0', 'Consumed 1', 'Consumed 2', 'Consumed 3', + # Second batch + 'Produced 4', 'Produced 5', 'Consumed 4', 'Consumed 5'])]) +def test_dispatch_one_job(backend, batch_size, expected_queue): + """ Test that with only one job, Parallel does act as a iterator. + """ + queue = list() + + def producer(): + for i in range(6): + queue.append('Produced %i' % i) + yield i + + Parallel(n_jobs=1, batch_size=batch_size, backend=backend)( + delayed(consumer)(queue, x) for x in producer()) + assert queue == expected_queue + assert len(queue) == 12 + + +@with_multiprocessing +@parametrize('backend', PARALLEL_BACKENDS) +def test_dispatch_multiprocessing(backend): + """ Check that using pre_dispatch Parallel does indeed dispatch items + lazily. + """ + manager = mp.Manager() + queue = manager.list() + + def producer(): + for i in range(6): + queue.append('Produced %i' % i) + yield i + + Parallel(n_jobs=2, batch_size=1, pre_dispatch=3, backend=backend)( + delayed(consumer)(queue, 'any') for _ in producer()) + + queue_contents = list(queue) + assert queue_contents[0] == 'Produced 0' + + # Only 3 tasks are pre-dispatched out of 6. The 4th task is dispatched only + # after any of the first 3 jobs have completed. + first_consumption_index = queue_contents[:4].index('Consumed any') + assert first_consumption_index > -1 + + produced_3_index = queue_contents.index('Produced 3') # 4th task produced + assert produced_3_index > first_consumption_index + + assert len(queue) == 12 + + +def test_batching_auto_threading(): + # batching='auto' with the threading backend leaves the effective batch + # size to 1 (no batching) as it has been found to never be beneficial with + # this low-overhead backend. + + with Parallel(n_jobs=2, batch_size='auto', backend='threading') as p: + p(delayed(id)(i) for i in range(5000)) # many very fast tasks + assert p._backend.compute_batch_size() == 1 + + +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_batching_auto_subprocesses(backend): + with Parallel(n_jobs=2, batch_size='auto', backend=backend) as p: + p(delayed(id)(i) for i in range(5000)) # many very fast tasks + + # It should be strictly larger than 1 but as we don't want heisen + # failures on clogged CI worker environment be safe and only check that + # it's a strictly positive number. + assert p._backend.compute_batch_size() > 0 + + +def test_exception_dispatch(): + """Make sure that exception raised during dispatch are indeed captured""" + with raises(ValueError): + Parallel(n_jobs=2, pre_dispatch=16, verbose=0)( + delayed(exception_raiser)(i) for i in range(30)) + + +def nested_function_inner(i): + Parallel(n_jobs=2)( + delayed(exception_raiser)(j) for j in range(30)) + + +def nested_function_outer(i): + Parallel(n_jobs=2)( + delayed(nested_function_inner)(j) for j in range(30)) + + +@with_multiprocessing +@parametrize('backend', PARALLEL_BACKENDS) +@pytest.mark.xfail(reason="https://github.com/joblib/loky/pull/255") +def test_nested_exception_dispatch(backend): + """Ensure errors for nested joblib cases gets propagated + + We rely on the Python 3 built-in __cause__ system that already + report this kind of information to the user. + """ + with raises(ValueError) as excinfo: + Parallel(n_jobs=2, backend=backend)( + delayed(nested_function_outer)(i) for i in range(30)) + + # Check that important information such as function names are visible + # in the final error message reported to the user + report_lines = format_exception(excinfo.type, excinfo.value, excinfo.tb) + report = "".join(report_lines) + assert 'nested_function_outer' in report + assert 'nested_function_inner' in report + assert 'exception_raiser' in report + + assert type(excinfo.value) is ValueError + + +class FakeParallelBackend(SequentialBackend): + """Pretends to run concurrently while running sequentially.""" + + def configure(self, n_jobs=1, parallel=None, **backend_args): + self.n_jobs = self.effective_n_jobs(n_jobs) + self.parallel = parallel + return n_jobs + + def effective_n_jobs(self, n_jobs=1): + if n_jobs < 0: + n_jobs = max(mp.cpu_count() + 1 + n_jobs, 1) + return n_jobs + + +def test_invalid_backend(): + with raises(ValueError, match="Invalid backend:"): + Parallel(backend='unit-testing') + + with raises(ValueError, match="Invalid backend:"): + with parallel_config(backend='unit-testing'): + pass + + with raises(ValueError, match="Invalid backend:"): + with parallel_config(backend='unit-testing'): + pass + + +@parametrize('backend', ALL_VALID_BACKENDS) +def test_invalid_njobs(backend): + with raises(ValueError) as excinfo: + Parallel(n_jobs=0, backend=backend)._initialize_backend() + assert "n_jobs == 0 in Parallel has no meaning" in str(excinfo.value) + + with raises(ValueError) as excinfo: + Parallel(n_jobs=0.5, backend=backend)._initialize_backend() + assert "n_jobs == 0 in Parallel has no meaning" in str(excinfo.value) + + with raises(ValueError) as excinfo: + Parallel(n_jobs="2.3", backend=backend)._initialize_backend() + assert "n_jobs could not be converted to int" in str(excinfo.value) + + with raises(ValueError) as excinfo: + Parallel(n_jobs="invalid_str", backend=backend)._initialize_backend() + assert "n_jobs could not be converted to int" in str(excinfo.value) + + +@with_multiprocessing +@parametrize('backend', PARALLEL_BACKENDS) +@parametrize('n_jobs', ['2', 2.3, 2]) +def test_njobs_converted_to_int(backend, n_jobs): + p = Parallel(n_jobs=n_jobs, backend=backend) + assert p._effective_n_jobs() == 2 + + res = p(delayed(square)(i) for i in range(10)) + assert all(r == square(i) for i, r in enumerate(res)) + + +def test_register_parallel_backend(): + try: + register_parallel_backend("test_backend", FakeParallelBackend) + assert "test_backend" in BACKENDS + assert BACKENDS["test_backend"] == FakeParallelBackend + finally: + del BACKENDS["test_backend"] + + +def test_overwrite_default_backend(): + assert _active_backend_type() == DefaultBackend + try: + register_parallel_backend("threading", BACKENDS["threading"], + make_default=True) + assert _active_backend_type() == ThreadingBackend + finally: + # Restore the global default manually + parallel.DEFAULT_BACKEND = DEFAULT_BACKEND + assert _active_backend_type() == DefaultBackend + + +@skipif(mp is not None, reason="Only without multiprocessing") +def test_backend_no_multiprocessing(): + with warns(UserWarning, + match="joblib backend '.*' is not available on.*"): + Parallel(backend='loky')(delayed(square)(i) for i in range(3)) + + # The below should now work without problems + with parallel_config(backend='loky'): + Parallel()(delayed(square)(i) for i in range(3)) + + +def check_backend_context_manager(context, backend_name): + with context(backend_name, n_jobs=3): + active_backend, active_n_jobs = parallel.get_active_backend() + assert active_n_jobs == 3 + assert effective_n_jobs(3) == 3 + p = Parallel() + assert p.n_jobs == 3 + if backend_name == 'multiprocessing': + assert type(active_backend) is MultiprocessingBackend + assert type(p._backend) is MultiprocessingBackend + elif backend_name == 'loky': + assert type(active_backend) is LokyBackend + assert type(p._backend) is LokyBackend + elif backend_name == 'threading': + assert type(active_backend) is ThreadingBackend + assert type(p._backend) is ThreadingBackend + elif backend_name.startswith('test_'): + assert type(active_backend) is FakeParallelBackend + assert type(p._backend) is FakeParallelBackend + + +all_backends_for_context_manager = PARALLEL_BACKENDS[:] +all_backends_for_context_manager.extend( + ['test_backend_%d' % i for i in range(3)] +) + + +@with_multiprocessing +@parametrize('backend', all_backends_for_context_manager) +@parametrize('context', [parallel_backend, parallel_config]) +def test_backend_context_manager(monkeypatch, backend, context): + if backend not in BACKENDS: + monkeypatch.setitem(BACKENDS, backend, FakeParallelBackend) + + assert _active_backend_type() == DefaultBackend + # check that this possible to switch parallel backends sequentially + check_backend_context_manager(context, backend) + + # The default backend is restored + assert _active_backend_type() == DefaultBackend + + # Check that context manager switching is thread safe: + Parallel(n_jobs=2, backend='threading')( + delayed(check_backend_context_manager)(context, b) + for b in all_backends_for_context_manager if not b) + + # The default backend is again restored + assert _active_backend_type() == DefaultBackend + + +class ParameterizedParallelBackend(SequentialBackend): + """Pretends to run conncurrently while running sequentially.""" + + def __init__(self, param=None): + if param is None: + raise ValueError('param should not be None') + self.param = param + + +@parametrize("context", [parallel_config, parallel_backend]) +def test_parameterized_backend_context_manager(monkeypatch, context): + monkeypatch.setitem(BACKENDS, 'param_backend', + ParameterizedParallelBackend) + assert _active_backend_type() == DefaultBackend + + with context('param_backend', param=42, n_jobs=3): + active_backend, active_n_jobs = parallel.get_active_backend() + assert type(active_backend) is ParameterizedParallelBackend + assert active_backend.param == 42 + assert active_n_jobs == 3 + p = Parallel() + assert p.n_jobs == 3 + assert p._backend is active_backend + results = p(delayed(sqrt)(i) for i in range(5)) + assert results == [sqrt(i) for i in range(5)] + + # The default backend is again restored + assert _active_backend_type() == DefaultBackend + + +@parametrize("context", [parallel_config, parallel_backend]) +def test_directly_parameterized_backend_context_manager(context): + assert _active_backend_type() == DefaultBackend + + # Check that it's possible to pass a backend instance directly, + # without registration + with context(ParameterizedParallelBackend(param=43), n_jobs=5): + active_backend, active_n_jobs = parallel.get_active_backend() + assert type(active_backend) is ParameterizedParallelBackend + assert active_backend.param == 43 + assert active_n_jobs == 5 + p = Parallel() + assert p.n_jobs == 5 + assert p._backend is active_backend + results = p(delayed(sqrt)(i) for i in range(5)) + assert results == [sqrt(i) for i in range(5)] + + # The default backend is again restored + assert _active_backend_type() == DefaultBackend + + +def sleep_and_return_pid(): + sleep(.1) + return os.getpid() + + +def get_nested_pids(): + assert _active_backend_type() == ThreadingBackend + # Assert that the nested backend does not change the default number of + # jobs used in Parallel + assert Parallel()._effective_n_jobs() == 1 + + # Assert that the tasks are running only on one process + return Parallel(n_jobs=2)(delayed(sleep_and_return_pid)() + for _ in range(2)) + + +class MyBackend(joblib._parallel_backends.LokyBackend): + """Backend to test backward compatibility with older backends""" + def get_nested_backend(self, ): + # Older backends only return a backend, without n_jobs indications. + return super(MyBackend, self).get_nested_backend()[0] + + +register_parallel_backend('back_compat_backend', MyBackend) + + +@with_multiprocessing +@parametrize('backend', ['threading', 'loky', 'multiprocessing', + 'back_compat_backend']) +@parametrize("context", [parallel_config, parallel_backend]) +def test_nested_backend_context_manager(context, backend): + # Check that by default, nested parallel calls will always use the + # ThreadingBackend + + with context(backend): + pid_groups = Parallel(n_jobs=2)( + delayed(get_nested_pids)() + for _ in range(10) + ) + for pid_group in pid_groups: + assert len(set(pid_group)) == 1 + + +@with_multiprocessing +@parametrize('n_jobs', [2, -1, None]) +@parametrize('backend', PARALLEL_BACKENDS) +@parametrize("context", [parallel_config, parallel_backend]) +def test_nested_backend_in_sequential(backend, n_jobs, context): + # Check that by default, nested parallel calls will always use the + # ThreadingBackend + + def check_nested_backend(expected_backend_type, expected_n_job): + # Assert that the sequential backend at top level, does not change the + # backend for nested calls. + assert _active_backend_type() == BACKENDS[expected_backend_type] + + # Assert that the nested backend in SequentialBackend does not change + # the default number of jobs used in Parallel + expected_n_job = effective_n_jobs(expected_n_job) + assert Parallel()._effective_n_jobs() == expected_n_job + + Parallel(n_jobs=1)( + delayed(check_nested_backend)(DEFAULT_BACKEND, 1) + for _ in range(10) + ) + + with context(backend, n_jobs=n_jobs): + Parallel(n_jobs=1)( + delayed(check_nested_backend)(backend, n_jobs) + for _ in range(10) + ) + + +def check_nesting_level(context, inner_backend, expected_level): + with context(inner_backend) as ctx: + if context is parallel_config: + backend = ctx["backend"] + if context is parallel_backend: + backend = ctx[0] + assert backend.nesting_level == expected_level + + +@with_multiprocessing +@parametrize('outer_backend', PARALLEL_BACKENDS) +@parametrize('inner_backend', PARALLEL_BACKENDS) +@parametrize("context", [parallel_config, parallel_backend]) +def test_backend_nesting_level(context, outer_backend, inner_backend): + # Check that the nesting level for the backend is correctly set + check_nesting_level(context, outer_backend, 0) + + Parallel(n_jobs=2, backend=outer_backend)( + delayed(check_nesting_level)(context, inner_backend, 1) + for _ in range(10) + ) + + with context(inner_backend, n_jobs=2): + Parallel()(delayed(check_nesting_level)(context, inner_backend, 1) + for _ in range(10)) + + +@with_multiprocessing +@parametrize("context", [parallel_config, parallel_backend]) +@parametrize('with_retrieve_callback', [True, False]) +def test_retrieval_context(context, with_retrieve_callback): + import contextlib + + class MyBackend(ThreadingBackend): + i = 0 + supports_retrieve_callback = with_retrieve_callback + + @contextlib.contextmanager + def retrieval_context(self): + self.i += 1 + yield + + register_parallel_backend("retrieval", MyBackend) + + def nested_call(n): + return Parallel(n_jobs=2)(delayed(id)(i) for i in range(n)) + + with context("retrieval") as ctx: + Parallel(n_jobs=2)( + delayed(nested_call)(i) + for i in range(5) + ) + if context is parallel_config: + assert ctx["backend"].i == 1 + if context is parallel_backend: + assert ctx[0].i == 1 + + +############################################################################### +# Test helpers + +@parametrize('batch_size', [0, -1, 1.42]) +def test_invalid_batch_size(batch_size): + with raises(ValueError): + Parallel(batch_size=batch_size) + + +@parametrize('n_tasks, n_jobs, pre_dispatch, batch_size', + [(2, 2, 'all', 'auto'), + (2, 2, 'n_jobs', 'auto'), + (10, 2, 'n_jobs', 'auto'), + (517, 2, 'n_jobs', 'auto'), + (10, 2, 'n_jobs', 'auto'), + (10, 4, 'n_jobs', 'auto'), + (200, 12, 'n_jobs', 'auto'), + (25, 12, '2 * n_jobs', 1), + (250, 12, 'all', 1), + (250, 12, '2 * n_jobs', 7), + (200, 12, '2 * n_jobs', 'auto')]) +def test_dispatch_race_condition(n_tasks, n_jobs, pre_dispatch, batch_size): + # Check that using (async-)dispatch does not yield a race condition on the + # iterable generator that is not thread-safe natively. + # This is a non-regression test for the "Pool seems closed" class of error + params = {'n_jobs': n_jobs, 'pre_dispatch': pre_dispatch, + 'batch_size': batch_size} + expected = [square(i) for i in range(n_tasks)] + results = Parallel(**params)(delayed(square)(i) for i in range(n_tasks)) + assert results == expected + + +@with_multiprocessing +def test_default_mp_context(): + mp_start_method = mp.get_start_method() + p = Parallel(n_jobs=2, backend='multiprocessing') + context = p._backend_args.get('context') + start_method = context.get_start_method() + assert start_method == mp_start_method + + +@with_numpy +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_no_blas_crash_or_freeze_with_subprocesses(backend): + if backend == 'multiprocessing': + # Use the spawn backend that is both robust and available on all + # platforms + backend = mp.get_context('spawn') + + # Check that on recent Python version, the 'spawn' start method can make + # it possible to use multiprocessing in conjunction of any BLAS + # implementation that happens to be used by numpy with causing a freeze or + # a crash + rng = np.random.RandomState(42) + + # call BLAS DGEMM to force the initialization of the internal thread-pool + # in the main process + a = rng.randn(1000, 1000) + np.dot(a, a.T) + + # check that the internal BLAS thread-pool is not in an inconsistent state + # in the worker processes managed by multiprocessing + Parallel(n_jobs=2, backend=backend)( + delayed(np.dot)(a, a.T) for i in range(2)) + + +UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_NO_MAIN = """\ +from joblib import Parallel, delayed + +def square(x): + return x ** 2 + +backend = "{}" +if backend == "spawn": + from multiprocessing import get_context + backend = get_context(backend) + +print(Parallel(n_jobs=2, backend=backend)( + delayed(square)(i) for i in range(5))) +""" + + +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_parallel_with_interactively_defined_functions(backend): + # When using the "-c" flag, interactive functions defined in __main__ + # should work with any backend. + if backend == "multiprocessing" and mp.get_start_method() != "fork": + pytest.skip("Require fork start method to use interactively defined " + "functions with multiprocessing.") + code = UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_NO_MAIN.format(backend) + check_subprocess_call( + [sys.executable, '-c', code], timeout=10, + stdout_regex=r'\[0, 1, 4, 9, 16\]') + + +UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_MAIN = """\ +import sys +# Make sure that joblib is importable in the subprocess launching this +# script. This is needed in case we run the tests from the joblib root +# folder without having installed joblib +sys.path.insert(0, {joblib_root_folder!r}) + +from joblib import Parallel, delayed + +def run(f, x): + return f(x) + +{define_func} + +if __name__ == "__main__": + backend = "{backend}" + if backend == "spawn": + from multiprocessing import get_context + backend = get_context(backend) + + callable_position = "{callable_position}" + if callable_position == "delayed": + print(Parallel(n_jobs=2, backend=backend)( + delayed(square)(i) for i in range(5))) + elif callable_position == "args": + print(Parallel(n_jobs=2, backend=backend)( + delayed(run)(square, i) for i in range(5))) + else: + print(Parallel(n_jobs=2, backend=backend)( + delayed(run)(f=square, x=i) for i in range(5))) +""" + +SQUARE_MAIN = """\ +def square(x): + return x ** 2 +""" +SQUARE_LOCAL = """\ +def gen_square(): + def square(x): + return x ** 2 + return square +square = gen_square() +""" +SQUARE_LAMBDA = """\ +square = lambda x: x ** 2 +""" + + +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS + ([] if mp is None else ['spawn'])) +@parametrize('define_func', [SQUARE_MAIN, SQUARE_LOCAL, SQUARE_LAMBDA]) +@parametrize('callable_position', ['delayed', 'args', 'kwargs']) +def test_parallel_with_unpicklable_functions_in_args( + backend, define_func, callable_position, tmpdir): + if backend in ['multiprocessing', 'spawn'] and ( + define_func != SQUARE_MAIN or sys.platform == "win32"): + pytest.skip("Not picklable with pickle") + code = UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_MAIN.format( + define_func=define_func, backend=backend, + callable_position=callable_position, + joblib_root_folder=os.path.dirname(os.path.dirname(joblib.__file__))) + code_file = tmpdir.join("unpicklable_func_script.py") + code_file.write(code) + check_subprocess_call( + [sys.executable, code_file.strpath], timeout=10, + stdout_regex=r'\[0, 1, 4, 9, 16\]') + + +INTERACTIVE_DEFINED_FUNCTION_AND_CLASS_SCRIPT_CONTENT = """\ +import sys +import faulthandler +# Make sure that joblib is importable in the subprocess launching this +# script. This is needed in case we run the tests from the joblib root +# folder without having installed joblib +sys.path.insert(0, {joblib_root_folder!r}) + +from joblib import Parallel, delayed +from functools import partial + +class MyClass: + '''Class defined in the __main__ namespace''' + def __init__(self, value): + self.value = value + + +def square(x, ignored=None, ignored2=None): + '''Function defined in the __main__ namespace''' + return x.value ** 2 + + +square2 = partial(square, ignored2='something') + +# Here, we do not need the `if __name__ == "__main__":` safeguard when +# using the default `loky` backend (even on Windows). + +# To make debugging easier +faulthandler.dump_traceback_later(30, exit=True) + +# The following baroque function call is meant to check that joblib +# introspection rightfully uses cloudpickle instead of the (faster) pickle +# module of the standard library when necessary. In particular cloudpickle is +# necessary for functions and instances of classes interactively defined in the +# __main__ module. + +print(Parallel(backend="loky", n_jobs=2)( + delayed(square2)(MyClass(i), ignored=[dict(a=MyClass(1))]) + for i in range(5) +)) +""".format(joblib_root_folder=os.path.dirname( + os.path.dirname(joblib.__file__))) + + +@with_multiprocessing +def test_parallel_with_interactively_defined_functions_loky(tmpdir): + # loky accepts interactive functions defined in __main__ and does not + # require if __name__ == '__main__' even when the __main__ module is + # defined by the result of the execution of a filesystem script. + script = tmpdir.join('joblib_interactively_defined_function.py') + script.write(INTERACTIVE_DEFINED_FUNCTION_AND_CLASS_SCRIPT_CONTENT) + check_subprocess_call( + [sys.executable, script.strpath], + stdout_regex=r'\[0, 1, 4, 9, 16\]', + timeout=None, # rely on faulthandler to kill the process + ) + + +INTERACTIVELY_DEFINED_SUBCLASS_WITH_METHOD_SCRIPT_CONTENT = """\ +import sys +# Make sure that joblib is importable in the subprocess launching this +# script. This is needed in case we run the tests from the joblib root +# folder without having installed joblib +sys.path.insert(0, {joblib_root_folder!r}) + +from joblib import Parallel, delayed, hash +import multiprocessing as mp +mp.util.log_to_stderr(5) + +class MyList(list): + '''MyList is interactively defined by MyList.append is a built-in''' + def __hash__(self): + # XXX: workaround limitation in cloudpickle + return hash(self).__hash__() + +l = MyList() + +print(Parallel(backend="loky", n_jobs=2)( + delayed(l.append)(i) for i in range(3) +)) +""".format(joblib_root_folder=os.path.dirname( + os.path.dirname(joblib.__file__))) + + +@with_multiprocessing +def test_parallel_with_interactively_defined_bound_method_loky(tmpdir): + script = tmpdir.join('joblib_interactive_bound_method_script.py') + script.write(INTERACTIVELY_DEFINED_SUBCLASS_WITH_METHOD_SCRIPT_CONTENT) + check_subprocess_call([sys.executable, script.strpath], + stdout_regex=r'\[None, None, None\]', + stderr_regex=r'LokyProcess', + timeout=15) + + +def test_parallel_with_exhausted_iterator(): + exhausted_iterator = iter([]) + assert Parallel(n_jobs=2)(exhausted_iterator) == [] + + +def _cleanup_worker(): + """Helper function to force gc in each worker.""" + force_gc_pypy() + time.sleep(.1) + + +def check_memmap(a): + if not isinstance(a, np.memmap): + raise TypeError('Expected np.memmap instance, got %r', + type(a)) + return a.copy() # return a regular array instead of a memmap + + +@with_numpy +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_auto_memmap_on_arrays_from_generator(backend): + # Non-regression test for a problem with a bad interaction between the + # GC collecting arrays recently created during iteration inside the + # parallel dispatch loop and the auto-memmap feature of Parallel. + # See: https://github.com/joblib/joblib/pull/294 + def generate_arrays(n): + for i in range(n): + yield np.ones(10, dtype=np.float32) * i + # Use max_nbytes=1 to force the use of memory-mapping even for small + # arrays + results = Parallel(n_jobs=2, max_nbytes=1, backend=backend)( + delayed(check_memmap)(a) for a in generate_arrays(100)) + for result, expected in zip(results, generate_arrays(len(results))): + np.testing.assert_array_equal(expected, result) + + # Second call to force loky to adapt the executor by growing the number + # of worker processes. This is a non-regression test for: + # https://github.com/joblib/joblib/issues/629. + results = Parallel(n_jobs=4, max_nbytes=1, backend=backend)( + delayed(check_memmap)(a) for a in generate_arrays(100)) + for result, expected in zip(results, generate_arrays(len(results))): + np.testing.assert_array_equal(expected, result) + + +def identity(arg): + return arg + + +@with_numpy +@with_multiprocessing +def test_memmap_with_big_offset(tmpdir): + fname = tmpdir.join('test.mmap').strpath + size = mmap.ALLOCATIONGRANULARITY + obj = [np.zeros(size, dtype='uint8'), np.ones(size, dtype='uint8')] + dump(obj, fname) + memmap = load(fname, mmap_mode='r') + result, = Parallel(n_jobs=2)(delayed(identity)(memmap) for _ in [0]) + assert isinstance(memmap[1], np.memmap) + assert memmap[1].offset > size + np.testing.assert_array_equal(obj, result) + + +def test_warning_about_timeout_not_supported_by_backend(): + with warnings.catch_warnings(record=True) as warninfo: + Parallel(n_jobs=1, timeout=1)(delayed(square)(i) for i in range(50)) + assert len(warninfo) == 1 + w = warninfo[0] + assert isinstance(w.message, UserWarning) + assert str(w.message) == ( + "The backend class 'SequentialBackend' does not support timeout. " + "You have set 'timeout=1' in Parallel but the 'timeout' parameter " + "will not be used.") + + +def set_list_value(input_list, index, value): + input_list[index] = value + return value + + +@pytest.mark.parametrize('n_jobs', [1, 2, 4]) +def test_parallel_return_order_with_return_as_generator_parameter(n_jobs): + # This test inserts values in a list in some expected order + # in sequential computing, and then checks that this order has been + # respected by Parallel output generator. + input_list = [0] * 5 + result = Parallel(n_jobs=n_jobs, return_as="generator", + backend='threading')( + delayed(set_list_value)(input_list, i, i) for i in range(5)) + + # Ensure that all the tasks are completed before checking the result + result = list(result) + + assert all(v == r for v, r in zip(input_list, result)) + + +def _sqrt_with_delay(e, delay): + if delay: + sleep(30) + return sqrt(e) + + +def _test_parallel_unordered_generator_returns_fastest_first(backend, n_jobs): + # This test submits 10 tasks, but the second task is super slow. This test + # checks that the 9 other tasks return before the slow task is done, when + # `return_as` parameter is set to `'generator_unordered'` + result = Parallel(n_jobs=n_jobs, return_as="generator_unordered", + backend=backend)( + delayed(_sqrt_with_delay)(i**2, (i == 1)) for i in range(10)) + + quickly_returned = sorted(next(result) for _ in range(9)) + + expected_quickly_returned = [0] + list(range(2, 10)) + + assert all( + v == r for v, r in zip(expected_quickly_returned, quickly_returned) + ) + + del result + force_gc_pypy() + + +@pytest.mark.parametrize('n_jobs', [2, 4]) +# NB: for this test to work, the backend must be allowed to process tasks +# concurrently, so at least two jobs with a non-sequential backend are +# mandatory. +@with_multiprocessing +@parametrize('backend', set(RETURN_GENERATOR_BACKENDS) - {"sequential"}) +def test_parallel_unordered_generator_returns_fastest_first(backend, n_jobs): + _test_parallel_unordered_generator_returns_fastest_first(backend, n_jobs) + + +@pytest.mark.parametrize('n_jobs', [2, -1]) +@parametrize("context", [parallel_config, parallel_backend]) +@skipif(distributed is None, reason='This test requires dask') +def test_parallel_unordered_generator_returns_fastest_first_with_dask( + n_jobs, context +): + with distributed.Client( + n_workers=2, threads_per_worker=2 + ), context("dask"): + _test_parallel_unordered_generator_returns_fastest_first(None, n_jobs) + + +@parametrize('backend', ALL_VALID_BACKENDS) +@parametrize('n_jobs', [1, 2, -2, -1]) +def test_abort_backend(n_jobs, backend): + delays = ["a"] + [10] * 100 + with raises(TypeError): + t_start = time.time() + Parallel(n_jobs=n_jobs, backend=backend)( + delayed(time.sleep)(i) for i in delays) + dt = time.time() - t_start + assert dt < 20 + + +def get_large_object(arg): + result = np.ones(int(5 * 1e5), dtype=bool) + result[0] = False + return result + + +def _test_deadlock_with_generator(backend, return_as, n_jobs): + # Non-regression test for a race condition in the backends when the pickler + # is delayed by a large object. + with Parallel(n_jobs=n_jobs, backend=backend, + return_as=return_as) as parallel: + result = parallel(delayed(get_large_object)(i) for i in range(10)) + next(result) + next(result) + del result + # The gc in pypy can be delayed. Force it to make sure this test does + # not cause timeout on the CI. + force_gc_pypy() + + +@with_numpy +@parametrize('backend', RETURN_GENERATOR_BACKENDS) +@parametrize('return_as', ["generator", "generator_unordered"]) +@parametrize('n_jobs', [1, 2, -2, -1]) +def test_deadlock_with_generator(backend, return_as, n_jobs): + _test_deadlock_with_generator(backend, return_as, n_jobs) + + +@with_numpy +@pytest.mark.parametrize('n_jobs', [2, -1]) +@parametrize('return_as', ["generator", "generator_unordered"]) +@parametrize("context", [parallel_config, parallel_backend]) +@skipif(distributed is None, reason='This test requires dask') +def test_deadlock_with_generator_and_dask(context, return_as, n_jobs): + with distributed.Client( + n_workers=2, threads_per_worker=2 + ), context("dask"): + _test_deadlock_with_generator(None, return_as, n_jobs) + + +@parametrize('backend', RETURN_GENERATOR_BACKENDS) +@parametrize('return_as', ["generator", "generator_unordered"]) +@parametrize('n_jobs', [1, 2, -2, -1]) +def test_multiple_generator_call(backend, return_as, n_jobs): + # Non-regression test that ensures the dispatch of the tasks starts + # immediately when Parallel.__call__ is called. This test relies on the + # assumption that only one generator can be submitted at a time. + with raises(RuntimeError, + match="This Parallel instance is already running"): + parallel = Parallel(n_jobs, backend=backend, return_as=return_as) + g = parallel(delayed(sleep)(1) for _ in range(10)) # noqa: F841 + t_start = time.time() + gen2 = parallel(delayed(id)(i) for i in range(100)) # noqa: F841 + + # Make sure that the error is raised quickly + assert time.time() - t_start < 2, ( + "The error should be raised immediatly when submitting a new task " + "but it took more than 2s." + ) + + del g + # The gc in pypy can be delayed. Force it to make sure this test does not + # cause timeout on the CI. + force_gc_pypy() + + +@parametrize('backend', RETURN_GENERATOR_BACKENDS) +@parametrize('return_as', ["generator", "generator_unordered"]) +@parametrize('n_jobs', [1, 2, -2, -1]) +def test_multiple_generator_call_managed(backend, return_as, n_jobs): + # Non-regression test that ensures the dispatch of the tasks starts + # immediately when Parallel.__call__ is called. This test relies on the + # assumption that only one generator can be submitted at a time. + with Parallel(n_jobs, backend=backend, + return_as=return_as) as parallel: + g = parallel(delayed(sleep)(10) for _ in range(10)) # noqa: F841 + t_start = time.time() + with raises(RuntimeError, + match="This Parallel instance is already running"): + g2 = parallel(delayed(id)(i) for i in range(100)) # noqa: F841 + + # Make sure that the error is raised quickly + assert time.time() - t_start < 2, ( + "The error should be raised immediatly when submitting a new task " + "but it took more than 2s." + ) + + # The gc in pypy can be delayed. Force it to make sure this test does not + # cause timeout on the CI. + del g + force_gc_pypy() + + +@parametrize('backend', RETURN_GENERATOR_BACKENDS) +@parametrize('return_as_1', ["generator", "generator_unordered"]) +@parametrize('return_as_2', ["generator", "generator_unordered"]) +@parametrize('n_jobs', [1, 2, -2, -1]) +def test_multiple_generator_call_separated( + backend, return_as_1, return_as_2, n_jobs +): + # Check that for separated Parallel, both tasks are correctly returned. + g = Parallel(n_jobs, backend=backend, return_as=return_as_1)( + delayed(sqrt)(i ** 2) for i in range(10) + ) + g2 = Parallel(n_jobs, backend=backend, return_as=return_as_2)( + delayed(sqrt)(i ** 2) for i in range(10, 20) + ) + + if return_as_1 == "generator_unordered": + g = sorted(g) + + if return_as_2 == "generator_unordered": + g2 = sorted(g2) + + assert all(res == i for res, i in zip(g, range(10))) + assert all(res == i for res, i in zip(g2, range(10, 20))) + + +@parametrize('backend, error', [ + ('loky', True), + ('threading', False), + ('sequential', False), +]) +@parametrize('return_as_1', ["generator", "generator_unordered"]) +@parametrize('return_as_2', ["generator", "generator_unordered"]) +def test_multiple_generator_call_separated_gc( + backend, return_as_1, return_as_2, error +): + + if (backend == 'loky') and (mp is None): + pytest.skip("Requires multiprocessing") + + # Check that in loky, only one call can be run at a time with + # a single executor. + parallel = Parallel(2, backend=backend, return_as=return_as_1) + g = parallel(delayed(sleep)(10) for i in range(10)) + g_wr = weakref.finalize(g, lambda: print("Generator collected")) + ctx = ( + raises(RuntimeError, match="The executor underlying Parallel") + if error else nullcontext() + ) + with ctx: + # For loky, this call will raise an error as the gc of the previous + # generator will shutdown the shared executor. + # For the other backends, as the worker pools are not shared between + # the two calls, this should proceed correctly. + t_start = time.time() + g = Parallel(2, backend=backend, return_as=return_as_2)( + delayed(sqrt)(i ** 2) for i in range(10, 20) + ) + + # The gc in pypy can be delayed. Force it to test the behavior when it + # will eventually be collected. + force_gc_pypy() + + if return_as_2 == "generator_unordered": + g = sorted(g) + + assert all(res == i for res, i in zip(g, range(10, 20))) + + assert time.time() - t_start < 5 + + # Make sure that the computation are stopped for the gc'ed generator + retry = 0 + while g_wr.alive and retry < 3: + retry += 1 + time.sleep(.5) + assert time.time() - t_start < 5 + + if parallel._effective_n_jobs() != 1: + # check that the first parallel object is aborting (the final _aborted + # state might be delayed). + assert parallel._aborting + + +@with_numpy +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_memmapping_leaks(backend, tmpdir): + # Non-regression test for memmapping backends. Ensure that the data + # does not stay too long in memory + tmpdir = tmpdir.strpath + + # Use max_nbytes=1 to force the use of memory-mapping even for small + # arrays + with Parallel(n_jobs=2, max_nbytes=1, backend=backend, + temp_folder=tmpdir) as p: + p(delayed(check_memmap)(a) for a in [np.random.random(10)] * 2) + + # The memmap folder should not be clean in the context scope + assert len(os.listdir(tmpdir)) > 0 + + # Cleaning of the memmap folder is triggered by the garbage + # collection. With pypy the garbage collection has been observed to be + # delayed, sometimes up until the shutdown of the interpreter. This + # cleanup job executed in the worker ensures that it's triggered + # immediately. + p(delayed(_cleanup_worker)() for _ in range(2)) + + # Make sure that the shared memory is cleaned at the end when we exit + # the context + for _ in range(100): + if not os.listdir(tmpdir): + break + sleep(.1) + else: + raise AssertionError('temporary directory of Parallel was not removed') + + # Make sure that the shared memory is cleaned at the end of a call + p = Parallel(n_jobs=2, max_nbytes=1, backend=backend) + p(delayed(check_memmap)(a) for a in [np.random.random(10)] * 2) + p(delayed(_cleanup_worker)() for _ in range(2)) + + for _ in range(100): + if not os.listdir(tmpdir): + break + sleep(.1) + else: + raise AssertionError('temporary directory of Parallel was not removed') + + +@parametrize('backend', + ([None, 'threading'] if mp is None + else [None, 'loky', 'threading']) + ) +def test_lambda_expression(backend): + # cloudpickle is used to pickle delayed callables + results = Parallel(n_jobs=2, backend=backend)( + delayed(lambda x: x ** 2)(i) for i in range(10)) + assert results == [i ** 2 for i in range(10)] + + +@with_multiprocessing +@parametrize('backend', PROCESS_BACKENDS) +def test_backend_batch_statistics_reset(backend): + """Test that a parallel backend correctly resets its batch statistics.""" + n_jobs = 2 + n_inputs = 500 + task_time = 2. / n_inputs + + p = Parallel(verbose=10, n_jobs=n_jobs, backend=backend) + p(delayed(time.sleep)(task_time) for i in range(n_inputs)) + assert (p._backend._effective_batch_size == + p._backend._DEFAULT_EFFECTIVE_BATCH_SIZE) + assert (p._backend._smoothed_batch_duration == + p._backend._DEFAULT_SMOOTHED_BATCH_DURATION) + + p(delayed(time.sleep)(task_time) for i in range(n_inputs)) + assert (p._backend._effective_batch_size == + p._backend._DEFAULT_EFFECTIVE_BATCH_SIZE) + assert (p._backend._smoothed_batch_duration == + p._backend._DEFAULT_SMOOTHED_BATCH_DURATION) + + +@with_multiprocessing +@parametrize("context", [parallel_config, parallel_backend]) +def test_backend_hinting_and_constraints(context): + for n_jobs in [1, 2, -1]: + assert type(Parallel(n_jobs=n_jobs)._backend) == DefaultBackend + + p = Parallel(n_jobs=n_jobs, prefer='threads') + assert type(p._backend) is ThreadingBackend + + p = Parallel(n_jobs=n_jobs, prefer='processes') + assert type(p._backend) is DefaultBackend + + p = Parallel(n_jobs=n_jobs, require='sharedmem') + assert type(p._backend) is ThreadingBackend + + # Explicit backend selection can override backend hinting although it + # is useless to pass a hint when selecting a backend. + p = Parallel(n_jobs=2, backend='loky', prefer='threads') + assert type(p._backend) is LokyBackend + + with context('loky', n_jobs=2): + # Explicit backend selection by the user with the context manager + # should be respected when combined with backend hints only. + p = Parallel(prefer='threads') + assert type(p._backend) is LokyBackend + assert p.n_jobs == 2 + + with context('loky', n_jobs=2): + # Locally hard-coded n_jobs value is respected. + p = Parallel(n_jobs=3, prefer='threads') + assert type(p._backend) is LokyBackend + assert p.n_jobs == 3 + + with context('loky', n_jobs=2): + # Explicit backend selection by the user with the context manager + # should be ignored when the Parallel call has hard constraints. + # In this case, the default backend that supports shared mem is + # used an the default number of processes is used. + p = Parallel(require='sharedmem') + assert type(p._backend) is ThreadingBackend + assert p.n_jobs == 1 + + with context('loky', n_jobs=2): + p = Parallel(n_jobs=3, require='sharedmem') + assert type(p._backend) is ThreadingBackend + assert p.n_jobs == 3 + + +@parametrize("context", [parallel_config, parallel_backend]) +def test_backend_hinting_and_constraints_with_custom_backends( + capsys, context +): + # Custom backends can declare that they use threads and have shared memory + # semantics: + class MyCustomThreadingBackend(ParallelBackendBase): + supports_sharedmem = True + use_threads = True + + def apply_async(self): + pass + + def effective_n_jobs(self, n_jobs): + return n_jobs + + with context(MyCustomThreadingBackend()): + p = Parallel(n_jobs=2, prefer='processes') # ignored + assert type(p._backend) is MyCustomThreadingBackend + + p = Parallel(n_jobs=2, require='sharedmem') + assert type(p._backend) is MyCustomThreadingBackend + + class MyCustomProcessingBackend(ParallelBackendBase): + supports_sharedmem = False + use_threads = False + + def apply_async(self): + pass + + def effective_n_jobs(self, n_jobs): + return n_jobs + + with context(MyCustomProcessingBackend()): + p = Parallel(n_jobs=2, prefer='processes') + assert type(p._backend) is MyCustomProcessingBackend + + out, err = capsys.readouterr() + assert out == "" + assert err == "" + + p = Parallel(n_jobs=2, require='sharedmem', verbose=10) + assert type(p._backend) is ThreadingBackend + + out, err = capsys.readouterr() + expected = ("Using ThreadingBackend as joblib backend " + "instead of MyCustomProcessingBackend as the latter " + "does not provide shared memory semantics.") + assert out.strip() == expected + assert err == "" + + with raises(ValueError): + Parallel(backend=MyCustomProcessingBackend(), require='sharedmem') + + +def test_invalid_backend_hinting_and_constraints(): + with raises(ValueError): + Parallel(prefer='invalid') + + with raises(ValueError): + Parallel(require='invalid') + + with raises(ValueError): + # It is inconsistent to prefer process-based parallelism while + # requiring shared memory semantics. + Parallel(prefer='processes', require='sharedmem') + + if mp is not None: + # It is inconsistent to ask explicitly for a process-based + # parallelism while requiring shared memory semantics. + with raises(ValueError): + Parallel(backend='loky', require='sharedmem') + with raises(ValueError): + Parallel(backend='multiprocessing', require='sharedmem') + + +def _recursive_backend_info(limit=3, **kwargs): + """Perform nested parallel calls and introspect the backend on the way""" + + with Parallel(n_jobs=2) as p: + this_level = [(type(p._backend).__name__, p._backend.nesting_level)] + if limit == 0: + return this_level + results = p(delayed(_recursive_backend_info)(limit=limit - 1, **kwargs) + for i in range(1)) + return this_level + results[0] + + +@with_multiprocessing +@parametrize('backend', ['loky', 'threading']) +@parametrize("context", [parallel_config, parallel_backend]) +def test_nested_parallelism_limit(context, backend): + with context(backend, n_jobs=2): + backend_types_and_levels = _recursive_backend_info() + + if cpu_count() == 1: + second_level_backend_type = 'SequentialBackend' + max_level = 1 + else: + second_level_backend_type = 'ThreadingBackend' + max_level = 2 + + top_level_backend_type = backend.title() + 'Backend' + expected_types_and_levels = [ + (top_level_backend_type, 0), + (second_level_backend_type, 1), + ('SequentialBackend', max_level), + ('SequentialBackend', max_level) + ] + assert backend_types_and_levels == expected_types_and_levels + + +@with_numpy +@parametrize("context", [parallel_config, parallel_backend]) +@skipif(distributed is None, reason='This test requires dask') +def test_nested_parallelism_with_dask(context): + with distributed.Client(n_workers=2, threads_per_worker=2): + # 10 MB of data as argument to trigger implicit scattering + data = np.ones(int(1e7), dtype=np.uint8) + for i in range(2): + with context('dask'): + backend_types_and_levels = _recursive_backend_info(data=data) + assert len(backend_types_and_levels) == 4 + assert all(name == 'DaskDistributedBackend' + for name, _ in backend_types_and_levels) + + # No argument + with context('dask'): + backend_types_and_levels = _recursive_backend_info() + assert len(backend_types_and_levels) == 4 + assert all(name == 'DaskDistributedBackend' + for name, _ in backend_types_and_levels) + + +def _recursive_parallel(nesting_limit=None): + """A horrible function that does recursive parallel calls""" + return Parallel()(delayed(_recursive_parallel)() for i in range(2)) + + +@pytest.mark.no_cover +@parametrize("context", [parallel_config, parallel_backend]) +@parametrize( + 'backend', (['threading'] if mp is None else ['loky', 'threading']) +) +def test_thread_bomb_mitigation(context, backend): + # Test that recursive parallelism raises a recursion rather than + # saturating the operating system resources by creating a unbounded number + # of threads. + with context(backend, n_jobs=2): + with raises(BaseException) as excinfo: + _recursive_parallel() + exc = excinfo.value + if backend == "loky": + # Local import because loky may not be importable for lack of + # multiprocessing + from joblib.externals.loky.process_executor import TerminatedWorkerError # noqa + if isinstance(exc, (TerminatedWorkerError, PicklingError)): + # The recursion exception can itself cause an error when + # pickling it to be send back to the parent process. In this + # case the worker crashes but the original traceback is still + # printed on stderr. This could be improved but does not seem + # simple to do and this is not critical for users (as long + # as there is no process or thread bomb happening). + pytest.xfail("Loky worker crash when serializing RecursionError") + + assert isinstance(exc, RecursionError) + + +def _run_parallel_sum(): + env_vars = {} + for var in ['OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', + 'VECLIB_MAXIMUM_THREADS', 'NUMEXPR_NUM_THREADS', + 'NUMBA_NUM_THREADS', 'ENABLE_IPC']: + env_vars[var] = os.environ.get(var) + return env_vars, parallel_sum(100) + + +@parametrize("backend", ([None, 'loky'] if mp is not None else [None])) +@skipif(parallel_sum is None, reason="Need OpenMP helper compiled") +def test_parallel_thread_limit(backend): + results = Parallel(n_jobs=2, backend=backend)( + delayed(_run_parallel_sum)() for _ in range(2) + ) + expected_num_threads = max(cpu_count() // 2, 1) + for worker_env_vars, omp_num_threads in results: + assert omp_num_threads == expected_num_threads + for name, value in worker_env_vars.items(): + if name.endswith("_THREADS"): + assert value == str(expected_num_threads) + else: + assert name == "ENABLE_IPC" + assert value == "1" + + +@parametrize("context", [parallel_config, parallel_backend]) +@skipif(distributed is not None, reason='This test requires dask') +def test_dask_backend_when_dask_not_installed(context): + with raises(ValueError, match='Please install dask'): + context('dask') + + +@parametrize("context", [parallel_config, parallel_backend]) +def test_zero_worker_backend(context): + # joblib.Parallel should reject with an explicit error message parallel + # backends that have no worker. + class ZeroWorkerBackend(ThreadingBackend): + def configure(self, *args, **kwargs): + return 0 + + def apply_async(self, func, callback=None): # pragma: no cover + raise TimeoutError("No worker available") + + def effective_n_jobs(self, n_jobs): # pragma: no cover + return 0 + + expected_msg = "ZeroWorkerBackend has no active worker" + with context(ZeroWorkerBackend()): + with pytest.raises(RuntimeError, match=expected_msg): + Parallel(n_jobs=2)(delayed(id)(i) for i in range(2)) + + +def test_globals_update_at_each_parallel_call(): + # This is a non-regression test related to joblib issues #836 and #833. + # Cloudpickle versions between 0.5.4 and 0.7 introduced a bug where global + # variables changes in a parent process between two calls to + # joblib.Parallel would not be propagated into the workers. + global MY_GLOBAL_VARIABLE + MY_GLOBAL_VARIABLE = "original value" + + def check_globals(): + global MY_GLOBAL_VARIABLE + return MY_GLOBAL_VARIABLE + + assert check_globals() == "original value" + + workers_global_variable = Parallel(n_jobs=2)( + delayed(check_globals)() for i in range(2)) + assert set(workers_global_variable) == {"original value"} + + # Change the value of MY_GLOBAL_VARIABLE, and make sure this change gets + # propagated into the workers environment + MY_GLOBAL_VARIABLE = "changed value" + assert check_globals() == "changed value" + + workers_global_variable = Parallel(n_jobs=2)( + delayed(check_globals)() for i in range(2)) + assert set(workers_global_variable) == {"changed value"} + + +############################################################################## +# Test environment variable in child env, in particular for limiting +# the maximal number of threads in C-library threadpools. +# + +def _check_numpy_threadpool_limits(): + import numpy as np + # Let's call BLAS on a Matrix Matrix multiplication with dimensions large + # enough to ensure that the threadpool managed by the underlying BLAS + # implementation is actually used so as to force its initialization. + a = np.random.randn(100, 100) + np.dot(a, a) + from threadpoolctl import threadpool_info + return threadpool_info() + + +def _parent_max_num_threads_for(child_module, parent_info): + for parent_module in parent_info: + if parent_module['filepath'] == child_module['filepath']: + return parent_module['num_threads'] + raise ValueError("An unexpected module was loaded in child:\n{}" + .format(child_module)) + + +def check_child_num_threads(workers_info, parent_info, num_threads): + # Check that the number of threads reported in workers_info is consistent + # with the expectation. We need to be careful to handle the cases where + # the requested number of threads is below max_num_thread for the library. + for child_threadpool_info in workers_info: + for child_module in child_threadpool_info: + parent_max_num_threads = _parent_max_num_threads_for( + child_module, parent_info) + expected = {min(num_threads, parent_max_num_threads), num_threads} + assert child_module['num_threads'] in expected + + +@with_numpy +@with_multiprocessing +@parametrize('n_jobs', [2, 4, -2, -1]) +def test_threadpool_limitation_in_child_loky(n_jobs): + # Check that the protection against oversubscription in workers is working + # using threadpoolctl functionalities. + + # Skip this test if numpy is not linked to a BLAS library + parent_info = _check_numpy_threadpool_limits() + if len(parent_info) == 0: + pytest.skip(reason="Need a version of numpy linked to BLAS") + + workers_threadpool_infos = Parallel(backend="loky", n_jobs=n_jobs)( + delayed(_check_numpy_threadpool_limits)() for i in range(2)) + + n_jobs = effective_n_jobs(n_jobs) + expected_child_num_threads = max(cpu_count() // n_jobs, 1) + + check_child_num_threads(workers_threadpool_infos, parent_info, + expected_child_num_threads) + + +@with_numpy +@with_multiprocessing +@parametrize('inner_max_num_threads', [1, 2, 4, None]) +@parametrize('n_jobs', [2, -1]) +@parametrize("context", [parallel_config, parallel_backend]) +def test_threadpool_limitation_in_child_context( + context, n_jobs, inner_max_num_threads +): + # Check that the protection against oversubscription in workers is working + # using threadpoolctl functionalities. + + # Skip this test if numpy is not linked to a BLAS library + parent_info = _check_numpy_threadpool_limits() + if len(parent_info) == 0: + pytest.skip(reason="Need a version of numpy linked to BLAS") + + with context('loky', inner_max_num_threads=inner_max_num_threads): + workers_threadpool_infos = Parallel(n_jobs=n_jobs)( + delayed(_check_numpy_threadpool_limits)() for i in range(2)) + + n_jobs = effective_n_jobs(n_jobs) + if inner_max_num_threads is None: + expected_child_num_threads = max(cpu_count() // n_jobs, 1) + else: + expected_child_num_threads = inner_max_num_threads + + check_child_num_threads(workers_threadpool_infos, parent_info, + expected_child_num_threads) + + +@with_multiprocessing +@parametrize('n_jobs', [2, -1]) +@parametrize('var_name', ["OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "OMP_NUM_THREADS"]) +@parametrize("context", [parallel_config, parallel_backend]) +def test_threadpool_limitation_in_child_override(context, n_jobs, var_name): + # Check that environment variables set by the user on the main process + # always have the priority. + + # Clean up the existing executor because we change the environment of the + # parent at runtime and it is not detected in loky intentionally. + get_reusable_executor(reuse=True).shutdown() + + def _get_env(var_name): + return os.environ.get(var_name) + + original_var_value = os.environ.get(var_name) + try: + os.environ[var_name] = "4" + # Skip this test if numpy is not linked to a BLAS library + results = Parallel(n_jobs=n_jobs)( + delayed(_get_env)(var_name) for i in range(2)) + assert results == ["4", "4"] + + with context('loky', inner_max_num_threads=1): + results = Parallel(n_jobs=n_jobs)( + delayed(_get_env)(var_name) for i in range(2)) + assert results == ["1", "1"] + + finally: + if original_var_value is None: + del os.environ[var_name] + else: + os.environ[var_name] = original_var_value + + +@with_multiprocessing +@parametrize('n_jobs', [2, 4, -1]) +def test_loky_reuse_workers(n_jobs): + # Non-regression test for issue #967 where the workers are not reused when + # calling multiple Parallel loops. + + def parallel_call(n_jobs): + x = range(10) + Parallel(n_jobs=n_jobs)(delayed(sum)(x) for i in range(10)) + + # Run a parallel loop and get the workers used for computations + parallel_call(n_jobs) + first_executor = get_reusable_executor(reuse=True) + + # Ensure that the workers are reused for the next calls, as the executor is + # not restarted. + for _ in range(10): + parallel_call(n_jobs) + executor = get_reusable_executor(reuse=True) + assert executor == first_executor diff --git a/testbed/joblib__joblib/joblib/test/test_store_backends.py b/testbed/joblib__joblib/joblib/test/test_store_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..e5db16757ea45fd6761e1b8cfd35e5f5a920752f --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_store_backends.py @@ -0,0 +1,94 @@ + +try: + # Python 2.7: use the C pickle to speed up + # test_concurrency_safe_write which pickles big python objects + import cPickle as cpickle +except ImportError: + import pickle as cpickle +import functools +from pickle import PicklingError +import time + +import pytest + +from joblib.testing import parametrize, timeout +from joblib.test.common import with_multiprocessing +from joblib.backports import concurrency_safe_rename +from joblib import Parallel, delayed +from joblib._store_backends import ( + concurrency_safe_write, + FileSystemStoreBackend, + CacheWarning, +) + + +def write_func(output, filename): + with open(filename, 'wb') as f: + cpickle.dump(output, f) + + +def load_func(expected, filename): + for i in range(10): + try: + with open(filename, 'rb') as f: + reloaded = cpickle.load(f) + break + except (OSError, IOError): + # On Windows you can have WindowsError ([Error 5] Access + # is denied or [Error 13] Permission denied) when reading the file, + # probably because a writer process has a lock on the file + time.sleep(0.1) + else: + raise + assert expected == reloaded + + +def concurrency_safe_write_rename(to_write, filename, write_func): + temporary_filename = concurrency_safe_write(to_write, + filename, write_func) + concurrency_safe_rename(temporary_filename, filename) + + +@timeout(0) # No timeout as this test can be long +@with_multiprocessing +@parametrize('backend', ['multiprocessing', 'loky', 'threading']) +def test_concurrency_safe_write(tmpdir, backend): + # Add one item to cache + filename = tmpdir.join('test.pkl').strpath + + obj = {str(i): i for i in range(int(1e5))} + funcs = [functools.partial(concurrency_safe_write_rename, + write_func=write_func) + if i % 3 != 2 else load_func for i in range(12)] + Parallel(n_jobs=2, backend=backend)( + delayed(func)(obj, filename) for func in funcs) + + +def test_warning_on_dump_failure(tmpdir): + # Check that a warning is raised when the dump fails for any reason but + # a PicklingError. + class UnpicklableObject(object): + def __reduce__(self): + raise RuntimeError("some exception") + + backend = FileSystemStoreBackend() + backend.location = tmpdir.join('test_warning_on_pickling_error').strpath + backend.compress = None + + with pytest.warns(CacheWarning, match="some exception"): + backend.dump_item("testpath", UnpicklableObject()) + + +def test_warning_on_pickling_error(tmpdir): + # This is separate from test_warning_on_dump_failure because in the + # future we will turn this into an exception. + class UnpicklableObject(object): + def __reduce__(self): + raise PicklingError("not picklable") + + backend = FileSystemStoreBackend() + backend.location = tmpdir.join('test_warning_on_pickling_error').strpath + backend.compress = None + + with pytest.warns(FutureWarning, match="not picklable"): + backend.dump_item("testpath", UnpicklableObject()) diff --git a/testbed/joblib__joblib/joblib/test/test_testing.py b/testbed/joblib__joblib/joblib/test/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..e8095aa67040ce868849b89927b325895b5d8e34 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_testing.py @@ -0,0 +1,75 @@ +import sys +import re + +from joblib.testing import raises, check_subprocess_call + + +def test_check_subprocess_call(): + code = '\n'.join(['result = 1 + 2 * 3', + 'print(result)', + 'my_list = [1, 2, 3]', + 'print(my_list)']) + + check_subprocess_call([sys.executable, '-c', code]) + + # Now checking stdout with a regex + check_subprocess_call([sys.executable, '-c', code], + # Regex needed for platform-specific line endings + stdout_regex=r'7\s{1,2}\[1, 2, 3\]') + + +def test_check_subprocess_call_non_matching_regex(): + code = '42' + non_matching_pattern = '_no_way_this_matches_anything_' + + with raises(ValueError) as excinfo: + check_subprocess_call([sys.executable, '-c', code], + stdout_regex=non_matching_pattern) + excinfo.match('Unexpected stdout.+{}'.format(non_matching_pattern)) + + +def test_check_subprocess_call_wrong_command(): + wrong_command = '_a_command_that_does_not_exist_' + with raises(OSError): + check_subprocess_call([wrong_command]) + + +def test_check_subprocess_call_non_zero_return_code(): + code_with_non_zero_exit = '\n'.join([ + 'import sys', + 'print("writing on stdout")', + 'sys.stderr.write("writing on stderr")', + 'sys.exit(123)']) + + pattern = re.compile('Non-zero return code: 123.+' + 'Stdout:\nwriting on stdout.+' + 'Stderr:\nwriting on stderr', re.DOTALL) + + with raises(ValueError) as excinfo: + check_subprocess_call([sys.executable, '-c', code_with_non_zero_exit]) + excinfo.match(pattern) + + +def test_check_subprocess_call_timeout(): + code_timing_out = '\n'.join([ + 'import time', + 'import sys', + 'print("before sleep on stdout")', + 'sys.stdout.flush()', + 'sys.stderr.write("before sleep on stderr")', + 'sys.stderr.flush()', + # We need to sleep for at least 2 * timeout seconds in case the SIGKILL + # is triggered. + 'time.sleep(10)', + 'print("process should have be killed before")', + 'sys.stdout.flush()']) + + pattern = re.compile('Non-zero return code:.+' + 'Stdout:\nbefore sleep on stdout\\s+' + 'Stderr:\nbefore sleep on stderr', + re.DOTALL) + + with raises(ValueError) as excinfo: + check_subprocess_call([sys.executable, '-c', code_timing_out], + timeout=1) + excinfo.match(pattern) diff --git a/testbed/joblib__joblib/joblib/test/test_utils.py b/testbed/joblib__joblib/joblib/test/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4999a212c462bdb6c10e9e08fdfba74d03b05294 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/test_utils.py @@ -0,0 +1,27 @@ +import pytest + +from joblib._utils import eval_expr + + +@pytest.mark.parametrize( + "expr", + ["exec('import os')", "print(1)", "import os", "1+1; import os", "1^1"], +) +def test_eval_expr_invalid(expr): + with pytest.raises( + ValueError, match="is not a valid or supported arithmetic" + ): + eval_expr(expr) + + +@pytest.mark.parametrize( + "expr, result", + [ + ("2*6", 12), + ("2**6", 64), + ("1 + 2*3**(4) / (6 + -7)", -161.0), + ("(20 // 3) % 5", 1), + ], +) +def test_eval_expr_valid(expr, result): + assert eval_expr(expr) == result diff --git a/testbed/joblib__joblib/joblib/test/testutils.py b/testbed/joblib__joblib/joblib/test/testutils.py new file mode 100644 index 0000000000000000000000000000000000000000..20ec8c1ba0a50da6be9fce3686ac1950b1a55ab5 --- /dev/null +++ b/testbed/joblib__joblib/joblib/test/testutils.py @@ -0,0 +1,8 @@ +def return_slice_of_data(arr, start_idx, end_idx): + return arr[start_idx:end_idx] + + +def print_filename_and_raise(arr): + from joblib._memmapping_reducer import _get_backing_memmap + print(_get_backing_memmap(arr).filename) + raise ValueError diff --git a/testbed/joblib__joblib/joblib/testing.py b/testbed/joblib__joblib/joblib/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..caab7d2903c710534596f2248de4b6c0642f9526 --- /dev/null +++ b/testbed/joblib__joblib/joblib/testing.py @@ -0,0 +1,99 @@ +""" +Helper for testing. +""" + +import sys +import warnings +import os.path +import re +import subprocess +import threading + +import pytest +import _pytest + + +raises = pytest.raises +warns = pytest.warns +SkipTest = _pytest.runner.Skipped +skipif = pytest.mark.skipif +fixture = pytest.fixture +parametrize = pytest.mark.parametrize +timeout = pytest.mark.timeout +xfail = pytest.mark.xfail +param = pytest.param + + +def warnings_to_stdout(): + """ Redirect all warnings to stdout. + """ + showwarning_orig = warnings.showwarning + + def showwarning(msg, cat, fname, lno, file=None, line=0): + showwarning_orig(msg, cat, os.path.basename(fname), line, sys.stdout) + + warnings.showwarning = showwarning + # warnings.simplefilter('always') + + +def check_subprocess_call(cmd, timeout=5, stdout_regex=None, + stderr_regex=None): + """Runs a command in a subprocess with timeout in seconds. + + A SIGTERM is sent after `timeout` and if it does not terminate, a + SIGKILL is sent after `2 * timeout`. + + Also checks returncode is zero, stdout if stdout_regex is set, and + stderr if stderr_regex is set. + """ + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + def terminate_process(): # pragma: no cover + """ + Attempt to terminate a leftover process spawned during test execution: + ideally this should not be needed but can help avoid clogging the CI + workers in case of deadlocks. + """ + warnings.warn(f"Timeout running {cmd}") + proc.terminate() + + def kill_process(): # pragma: no cover + """ + Kill a leftover process spawned during test execution: ideally this + should not be needed but can help avoid clogging the CI workers in + case of deadlocks. + """ + warnings.warn(f"Timeout running {cmd}") + proc.kill() + + try: + if timeout is not None: + terminate_timer = threading.Timer(timeout, terminate_process) + terminate_timer.start() + kill_timer = threading.Timer(2 * timeout, kill_process) + kill_timer.start() + stdout, stderr = proc.communicate() + stdout, stderr = stdout.decode(), stderr.decode() + if proc.returncode != 0: + message = ( + 'Non-zero return code: {}.\nStdout:\n{}\n' + 'Stderr:\n{}').format( + proc.returncode, stdout, stderr) + raise ValueError(message) + + if (stdout_regex is not None and + not re.search(stdout_regex, stdout)): + raise ValueError( + "Unexpected stdout: {!r} does not match:\n{!r}".format( + stdout_regex, stdout)) + if (stderr_regex is not None and + not re.search(stderr_regex, stderr)): + raise ValueError( + "Unexpected stderr: {!r} does not match:\n{!r}".format( + stderr_regex, stderr)) + + finally: + if timeout is not None: + terminate_timer.cancel() + kill_timer.cancel() diff --git a/testbed/joblib__joblib/pyproject.toml b/testbed/joblib__joblib/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..207f64f3d9b6566c6637410f8523c6dbe143fa0c --- /dev/null +++ b/testbed/joblib__joblib/pyproject.toml @@ -0,0 +1,102 @@ +[build-system] +requires = ["setuptools>=61.2"] +build-backend = "setuptools.build_meta" + +[project] +name = "joblib" +authors = [{name = "Gael Varoquaux", email = "gael.varoquaux@normalesup.org"}] +license = {text = "BSD 3-Clause"} +description = "Lightweight pipelining with Python functions" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "Intended Audience :: Education", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Scientific/Engineering", + "Topic :: Utilities", + "Topic :: Software Development :: Libraries", +] +requires-python = ">=3.8" +dynamic = ["version"] + +[project.readme] +file = "README.rst" +content-type = "text/x-rst" + +[project.urls] +Homepage = "https://joblib.readthedocs.io" +Source = "https://github.com/joblib/joblib" + +[tool.setuptools] +packages = [ + "joblib", + "joblib.test", + "joblib.test.data", + "joblib.externals", + "joblib.externals.cloudpickle", + "joblib.externals.loky", + "joblib.externals.loky.backend", +] +platforms = ["any"] +include-package-data = false + +[tool.setuptools.package-data] +"joblib.test" = [ + "data/*.gz", + "data/*.gzip", + "data/*.bz2", + "data/*.xz", + "data/*.lzma", + "data/*.pkl", + "data/*.npy", + "data/*.npy.z", +] + +[tool.setuptools.dynamic] +version = {attr = "joblib.__version__"} + + +[aliases] +release = "egg_info -RDb ''" +# Make sure the docs are uploaded when we do an upload +upload = "upload upload_docs --upload-dir doc/_build/html" + +[bdist_rpm] +doc_files = "doc" + + +[tool.pytest.ini_options] +doctest_optionflags = [ + "NORMALIZE_WHITESPACE", + "ELLIPSIS" +] +addopts = [ + "--doctest-glob='doc/*.rst'", + "--doctest-modules", + "--color=yes", +] +testpaths = "joblib" +norecursedirs = "joblib/externals/*" + +[tool.coverage.run] +source = [ + "joblib" +] +omit = [ + "joblib/test/data/*", + "joblib/test/_openmp_test_helper/setup.py", + "*/joblib/externals/*", +] +relative_files = true + +[tool.coverage.report] +show_missing = true diff --git a/testbed/joblib__joblib/setup.cfg b/testbed/joblib__joblib/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..56e8f46a601a4f542d614a673ee004bea5478e7d --- /dev/null +++ b/testbed/joblib__joblib/setup.cfg @@ -0,0 +1,12 @@ +# The prefered config file is pyproject.toml. The use of setup.cfg is +# mostly for compatibility with flake8 so it should not be used if possible. + +[flake8] +exclude= + joblib/externals/*, + doc/auto_examples, + doc/_build, + +per-file-ignores = + examples/*: E402, + doc/conf.py: E402, diff --git a/testbed/joblib__joblib/setup.py b/testbed/joblib__joblib/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..25536050b29963bbfbb07ad400439bb16afbb82a --- /dev/null +++ b/testbed/joblib__joblib/setup.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python + +from setuptools import setup + +if __name__ == "__main__": + setup() diff --git a/testbed/joke2k__faker/.bumpversion.cfg b/testbed/joke2k__faker/.bumpversion.cfg new file mode 100644 index 0000000000000000000000000000000000000000..a3bfef1cdfeccb9a758cafda0ebe383d3b336fbe --- /dev/null +++ b/testbed/joke2k__faker/.bumpversion.cfg @@ -0,0 +1,6 @@ +[bumpversion] +current_version = 4.0.0 +files = VERSION faker/__init__.py docs/conf.py +commit = True +tag = True + diff --git a/testbed/joke2k__faker/.circleci/config.yml b/testbed/joke2k__faker/.circleci/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..3286acf3a4bcdbc7290391a844d3fc2807badfd8 --- /dev/null +++ b/testbed/joke2k__faker/.circleci/config.yml @@ -0,0 +1,10 @@ +version: 2 + +jobs: + build: + docker: + - image: circleci/python:latest-node-browsers + steps: + - checkout + - run: pip install --user tox + - run: tox diff --git a/testbed/joke2k__faker/.coveragerc b/testbed/joke2k__faker/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..6d0ffb2a3f42f085c1d3dd38f814bd9cddfcafcb --- /dev/null +++ b/testbed/joke2k__faker/.coveragerc @@ -0,0 +1,3 @@ +[paths] +source = faker/ +omit = faker/build_docs.py diff --git a/testbed/joke2k__faker/.dockerignore b/testbed/joke2k__faker/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..198b23ecbbcceaf57bc2c3674690b7037b61d66f --- /dev/null +++ b/testbed/joke2k__faker/.dockerignore @@ -0,0 +1,16 @@ +.git/ + +build +dist +*.egg-info +*.egg/ +*.pyc +*.swp + +.tox +.coverage +html/* +__pycache__ + +# Compiled Documentation +docs/_build diff --git a/testbed/joke2k__faker/.gitignore b/testbed/joke2k__faker/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ad8222c2e4243d96709b39ec27b5bfb7c1131bbd --- /dev/null +++ b/testbed/joke2k__faker/.gitignore @@ -0,0 +1,54 @@ +__pycache__/ +.mypy_cache/ +*.py[cod] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +docs/_build +docs/locales.rst +docs/locales/*.rst +docs/providers.rst +docs/providers/*.rst +eggs +.eggs +parts +var +sdist +develop-eggs +.installed.cfg +lib +lib64 + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox +nosetests.xml + +# Translations +*.mo + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject +.python-version +.idea +.projectile +.ropeproject +.DS_Store +.venv + +# IDE +*.sw[po] +*.iml +*.ipr +venv/ diff --git a/testbed/joke2k__faker/.isort.cfg b/testbed/joke2k__faker/.isort.cfg new file mode 100644 index 0000000000000000000000000000000000000000..7a6dabca27e285b836bc34feef6e18a3eddc19c5 --- /dev/null +++ b/testbed/joke2k__faker/.isort.cfg @@ -0,0 +1,8 @@ +[settings] +line_length=120 +multi_line_output=3 +known_first_party=faker +sections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER +use_parentheses=true +include_trailing_comma=true +lines_between_types=1 diff --git a/testbed/joke2k__faker/.travis.yml b/testbed/joke2k__faker/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..fcbe3f80bfddeae745a047f277f6a7529fb80abb --- /dev/null +++ b/testbed/joke2k__faker/.travis.yml @@ -0,0 +1,36 @@ +dist: xenial +language: python +sudo: false +cache: pip +branches: + only: + - master + +matrix: + include: + - python: 3.7 + env: TOXENV=flake8 + - python: 3.7 + env: TOXENV=checkmanifest + - env: TOXENV=isort + - python: 3.5 + env: TOXENV=py35 + - python: 3.6 + env: TOXENV=py36 + - python: 3.7 + env: TOXENV=py37 + - python: 3.8 + env: TOXENV=py38 + - python: pypy3.5-6.0 + env: TOXENV=pypy3 + - python: 3.7 + os: linux + env: TOXENV=32bit TEST_32BIT=1 + +install: + - pip install tox +script: + - tox +after_success: + - pip install coveralls + - coveralls diff --git a/testbed/joke2k__faker/CHANGELOG.rst b/testbed/joke2k__faker/CHANGELOG.rst new file mode 100644 index 0000000000000000000000000000000000000000..2ddce5d1e6a1331f9fa113b67c8b5ef572d9698b --- /dev/null +++ b/testbed/joke2k__faker/CHANGELOG.rst @@ -0,0 +1,841 @@ +Changelog +========= + +`4.0.0 - 14-January-2019 `__ +------------------------------------------------------------------------------------- + +* Breaking change: Remove support for end-of-life Python 2.7. + +`3.0.1 - 14-January-2019 `__ +------------------------------------------------------------------------------------- + +**NOTE**: This is the last release to support Python 2.7.x. + +* Add provider methods ``zip`` and ``tar`` for generating zip and tar files. + Thanks @malefice. +* Add ``en-CA`` ``postcode_in_province()`` method. Thanks @oeuftete. +* Update Address and Automotive provider for Russian locale. Thanks @valestel. +* Add provider methods for dsv files: ``csv``, ``tsv``, ``psv`` and generic + ``dsv``. Thanks @malefice. +* Remove parenthesis from city name in ``de_DE`` ``address`` provider. Thanks + @jerr0328. +* Add ``NIP`` generator in ``pl_PL``. Thanks @IlfirinPL. +* Fix ``Faker.random_number`` intermittent exceptions. Thanks @Jengah. + + +`3.0.0 - 04-December-2019 `__ +-------------------------------------------------------------------------------------- + +* Breaking change: Add support for multiple locale data generation. + Thanks @malefice. + +`2.0.5 - 03-December-2019 `__ +-------------------------------------------------------------------------------------- + +* Add Iranian credit card. Thanks @abtinmo. +* Improve color provider. Thanks @malefice. +* Add counties (concelhos) for locale ``pt_PT``. Thanks @tng10. +* Change NY zipcode range. Thanks @arielkaluzhny. +* Fix pyfloat out of min/max range. Thanks @bryan-brancotte. + +`2.0.4 - 12-November-2019 `__ +-------------------------------------------------------------------------------------- + +* Drop python 3.4. +* Fix master card number generator. Thanks @nkthanh98. +* Add provider for Finnish IBAN numbers. Thanks @sitomani. +* Add color in Thai language. Thanks @mesodiar. +* Split first names into male/female for ``person/de_AT``. Thanks @Jayday. +* Extend data for ``de_AT`` and ``it_IT`` person providers. Thanks @Jayday. +* Add ``ta_IN`` support. Thanks @jcopps. +* Add ``*_PH`` locales. Thanks @malefice. +* Add Thai lorem. Thanks @mesodiar. +* Add job in ``ja_JP``. Thanks @shmokmt. +* Optimize IPv4 address generation. Thanks @malefice. +* Increase bban_format length for ``en_GB``. Thanks @Necrathex. +* Fix occasional errors in ISBN provider. Thanks @malefice. +* Add more phone numbers to ``fa_IR`` locale. Thanks @abtinmo. +* Add support for token-based string generation. Thanks @malefice. +* Improve barcode provider. Thanks @malefice. +* Fix for pyfloat empty randrange. Thanks @jcardali. + +`2.0.3 - 14-October-2019 `__ +------------------------------------------------------------------------------------- + +* Use the provider's RNG instead of the random module in ``invalid_ssn``. Thanks @luser. +* Fix ``randomize_nb_elements`` ``max`` argument. Thanks @jorrit-wehelp. +* Add ``de_DE`` jobs. Thanks @CodeAndChoke. +* Add ``pt_PT`` automotive plates. Thanks @rubenandre. +* Add ``el_GR`` jobs. Thanks @athaks. +* Add police id for ``el_GR``. Thanks @athaks. +* Add jobs for for ``pt_PT``. Thanks @rubenandre. + +`2.0.2 - 17-September-2019 `__ +--------------------------------------------------------------------------------------- + +* Fix typos, misspellings. Add locations, names, dates in ``hi_IN`` providers. Thanks @kathawala. +* Bump required version ``text-unidecode`` to 1.3. Thanks @moggers87. +* Bug fix for ``pyfloat`` going over ``max_value``. Thanks @fgs-dbudwin. + +`2.0.1 - 20-August-2019 `__ +------------------------------------------------------------------------------------ + +* Add nationalities for locale ``pt_PT``. Thanks @tng10. +* Add ``ios()`` and ``android()`` to ``user_agent`` provider. Thanks @gsilvan. +* Update ``zh_CN`` provinces. Thanks @casen27. + +`2.0.0 - 15-July-2019 `__ +---------------------------------------------------------------------------------- +* Breaking change: Only allow providers to use ``OrderedDict`` s, to avoid any more ``PYTHONHASHSEED`` problems. Thanks @adamchainz. + +`1.0.8 - 15-July-2019 `__ +---------------------------------------------------------------------------------- + +* Rename ``pyint`` ``min`` and ``max`` to ``min_value`` and ``max_value``. + Thanks @francoisfreitag. +* Remove some validations from Faker and delegate it to an external library, + ``validators``. Thanks @kingbuzzman. +* Add an "Invalid SSN" generator to the ``en_US`` SSN Provider. + Thanks @darrylwhiting. +* Include "Praia" as street_prefix in ``pr_BR`` address Provider. + Thanks @G5Olivieri. +* Loosen version restrictions on ``freezegun`` and ``random2``. + Thanks @timokau. +* Add SSN provider for ``es_MX``. Thanks @mrfunnyshoes. +* Add ``pwz`` generator for ``pl_PL``. Thanks @torm89. +* Add ``date_of_birth`` and ``sex`` argument to ``pesel`` Provider (`pl_PL`). + Thanks @torm89. +* Fix datetime parsing on environments with negative offsets. + Thanks @bluesheeptoken. + +`1.0.7 - 14-May-2019 `__ +--------------------------------------------------------------------------------- + +* Remove dead url from ``image_placeholder_services``. Thanks @Monstrofil. +* Fix missing ``first_names`` in Romanian person provider. Thanks @xlotlu. +* Add Catalan, adds doi/nie/nif/cif to Spain ssn. Thanks @kingbuzzman. +* Add ``texts`` to generate list of texts. Thanks @pishchalnikov. +* Add provider for ``pl_PL`` automotive and Polish pesel number. + Thanks @adwojak. +* Corrected behavior for ``pyfloat``. Thanks @ariksu. + +`1.0.6 - 26-April-2019 `__ +----------------------------------------------------------------------------------- + +* Add missing commas to company/nl_NL provider. Thanks @francoisfreitag. +* Add bounds to ``pyint``. Thanks @francoisfreitag. +* Accept step argument in ``random_int()``. Thanks @francoisfreitag. + +`1.0.5 - 12-April-2019 `__ +----------------------------------------------------------------------------------- + +* Add min and max values for ``pyfloat`` and ``pydecimal``. Thanks @Lrcezimbra. +* Add ``months`` and ``M`` to the syntax for ``start_date`` and ``end_date``. + Thanks @anneclairebrld. +* Add support for ``PyInstaller``. Thanks @arossert. +* Add Dutch company names. Thanks @MathynS. +* Fix some invalid French phone numbers starting with ``+33 8x``. + Thanks @stephane. +* Add Armenian locale ``hy_AM``. Thanks @hovikman. + +`1.0.4 - 12-March-2019 `__ +----------------------------------------------------------------------------------- + +* Fix erratic test. + +`1.0.3 - 12-March-2019 `__ +----------------------------------------------------------------------------------- + +* Fix ``AttributeError`` in ``user_Agent`` provider. Thanks @Mattwmaster58 for + the report. +* Update ``zh_TW`` ``person`` provider. Thanks @TimeFinger. +* Add street data & remove ``street_prefixes`` from ``id_ID`` address provider. + Thanks @codenoid. +* Fix parsing of timedeltas in ``date_time`` provider. Thanks @riconnon for + the report. +* Split name formats into ``formats_male`` and ``formats_female`` for ``de_DE`` + provider. Thanks @petro-zdebskyi. +* Pin ``more-itertools`` to a version compatible with Python 2.7. + Thanks @canarduck. +* Fix ``fr_FR`` ``postcodes_format``. Thanks @canarduck. +* Fix hex code for ``yellowgreen`` color. Thanks @hovikman. +* Add Brazilian RG (identity card). Thanks @davizucon. +* Allow overriding of random generator class. + +`1.0.2 - 22-January-2019 `__ +------------------------------------------------------------------------------------- + +* Fix state abbreviations for ``id_ID`` to be 2-letters. Thanks @dt-ap. +* Fix format for ``city_with_postcode`` on ``de_DE`` locale. Thanks @TZanke. +* Update ``person`` providers for ``zh_CN``. Thanks @TimeFinger. +* Implement ``zipcode_in_state`` and aliases in ``en_US`` locale for generating + a zipcode for a specified state. Thanks @mattyg. +* Group first names by gender on ``zh_CN`` provider. Thanks @TimeFinger. + +`1.0.1 - 12-December-2018 `__ +-------------------------------------------------------------------------------------- + +* Fix number of digits in ``phone_number`` provider for ``no_NO``. + Thanks @aleksanb. +* Add categories to ``jp_JP`` company provider. Thanks @shirakia. +* Add trunk prefix for ``ru_RU`` phone numbers. thanks @pishchalnikov. + +`1.0.0 - 13-November-2018 `__ +-------------------------------------------------------------------------------------- + +* Breaking change: ``latlng``, ``latitude`` and ``longitude`` no longer return + coordinates that are close the locale's country. Use the ``local_latlng``, + ``local_latitude`` and ``local_longitude`` instead. +* Add ``location_on_land`` provider. Thanks @shacker. + +`0.9.3 - 13-November-2018 `__ +-------------------------------------------------------------------------------------- + +* Add ``cellphone_number`` method for ``pt_BR``. Thanks @Newman101. +* Fix urls generated by from `image_url`. Thanks @tsiaGeorge. +* Add job provider for ``th_TH``. Thanks @mesodiar. +* Add phone number provider for ``th_TH``. Thanks @zkan. +* Add bank provider for ``pl_PL`` locale. Thanks @andrzej3393. +* Add lorem provider for ``pl_PL`` locale. Thanks @andrzej3393. +* Add Postcode and City format for ``de_DE`` provider. Thanks @Newman101. +* Add ``vat_id`` to ``ssn`` providers for ``bg_BG``, ``cs_CZ``, ``de_AT``, + ``de_CH``, ``de_de``, ``dk_DK``, ``el_CY``, ``el_GR``, ``en_GB``, ``en_IE``, + ``es_ES``, ``et_EE``, ``fi_FI``, ``fr_CH``, ``fr_FR``, ``hr_HR``, ``hu_HU``, + ``it_IT``, ``lb_LU``, ``lt_LT``, ``lv_LV``, ``mt_MT``, ``nl_BE``, ``nl_NL``, + ``no_NO``, ``pl_PL``, ``pt_PT``, ``ro_RO``, ``sk_SK``, ``sl_SI`` and + ``sv_SE``. Thanks @mastacheata. +* Add ``postcode`` and ``city_with_postcode`` for ``cs_CZ``. Thanks @Newman101. +* Add ``postcode`` and ``city_with_postcode`` for ``de_AT``. Thanks @Newman101. +* Add ``license_plate`` for ``ru_RU``. Thanks @codaver. +* Remove incorrect phone number formats from ``en_US``. Thanks @stephenross. +* Add job provider for ``bs_BA``. Thanks @elahmo. +* Add ``hostname`` provider. Thanks @ediblesushi. +* Add license plates for ``sv_SE``. Thanks @vilhelmmelkstam. +* Allow ``uuid4`` to return a ``UUID`` object. Thanks @ediblesushi. + +`0.9.2 - 12-October-2018 `__ +------------------------------------------------------------------------------------- + +* Add company names to ``pl_PL`` provider. Thanks @@twkrol. +* Add replacements for non-ascii characters in ``pt_BR``. Thanks @clarmso. +* Add some more placeholder image services. Thanks @clarmso. +* Separate male name and female name formats in ``cs_CZ`` provider. + Thanks @clarmso. +* Add second level domains (mostly provinces) for ``cn`` top level domain. + Thanks @clarmso. +* Add ``fr_FR`` localization to ``lorem`` provider. Thanks @tristandeborde. +* Lots of work on internal cleanup and optimizing the CI. Thanks @jdufresne. +* Add ``flake8`` to the CI. Thanks @andrzej3393. + +`0.9.1 - 13-September-2018 `__ +--------------------------------------------------------------------------------------- + +* Fix missing and misplaced comma's in many providers. Thanks @153957. +* Refactor IPv4 address generation to leverage ``ipaddress`` module. + Thanks @maticomp. +* An ``en_NZ`` provider for addresses, phone numbers and email addresses. + Thanks @doctorlard. +* Add ``unique`` argument to ``words()`` for returning unique words. + Thanks @micahstrube. +* Allow US territories to be excluded from ``state_abbr()`` for ``en_US`` + provider. Thanks @micahstrube. +* Add support for Python 3.7. Thanks @michael-k. + +`0.9.0 - 13-August-2018 `__ +------------------------------------------------------------------------------------- + +* ``.random_sample()`` now returns a list of unique elements instead of a set. +* ``.random_sample_unique()`` is removed in favor of ``.random_sample()``. +* Added ``random_choices()``, ``random_elements()`` and ``random_letters()``. +* Added ``faker.utils.distribution.choices_distribution_unique()``. +* ``words()``, ``password()``, ``uri_path`` and ``pystr()`` now use the new the + ``random_choices()`` method. + +`0.8.18 - 13-August-2018 `__ +--------------------------------------------------------------------------------------- + +* Change blood group from ``0`` (zero) to ``O`` (capital letter O). Some + locales do use 'zero', but ``O`` is more common and it is the medical + standard. Thanks @mohi7solanki. +* Fix alpha-2 country code for Haiti. Thanks @sevens-ef for the report. +* Fix abbreviation for Nunavut. Thanks @straz for the report. +* Standardized ``postcode`` in address providers. Now all locales are + guaranteed to have a ``postcode`` method and may have a localized alias for + it (eg: ``zipcode``). Thanks @straz for the report. +* Fix typo in ``pt_BR`` Person perovider. Thanks @Nichlas. +* Fix timezone handling. Thanks @Fraterius. +* Use tzinfo when provided in ``date_of_birth``. Thanks @Kelledin. + + +`0.8.17 - 12-July-2018 `__ +------------------------------------------------------------------------------------- + +* Add ``ein``, ``itin`` and refactored ``ssn`` Provider for ``en_US``. + Thanks @crd. +* Add ``job`` provider for ``zh_CN``. Thanks @ramwin. +* Add ``date_of_birth`` provider. Thanks @cdr. +* Add alpha-3 representation option for ``country-code`` provider. Thanks @cdr. + +`0.8.16 - 15-June-2018 `__ +------------------------------------------------------------------------------------- + +* Fix test for CPF (Brazilian SSN). Thanks Rubens Takiguti Ribeiro. +* Fix Canadian SIN generation. Thanks @crd. +* Fix Norwegian SSN date portion. Thanks @frangiz. +* Add ``start_datetime`` argument for ``unix_time()``. Thanks @crd. + +`0.8.15 - 14-May-2018 `__ +------------------------------------------------------------------------------------ + +* Change logging level to ``DEBUG``. + +`0.8.14 - 11-May-2018 `__ +------------------------------------------------------------------------------------ + +* Add possibility to make artificial ssn numbers for ``FI_fi``. Thanks @kivipe. +* Update ``ko_KR`` person data based on statistics. Thanks @unace. +* Improved logging. Thanks @confirmationbias616. + + +`0.8.13 - 12-April-2018 `__ +-------------------------------------------------------------------------------------- + +* Add ``no_NO`` bank provider. Thanks @cloveras. +* Add ``ipv4_network_class``, ``ipv4_private``, ``ipv4_public`` providers. + Thanks @ZuluPro. +* Add ``address_class`` and ``private`` arguments to ``ipv4`` provider. + Thanks @ZuluPro. +* Add ``currency``, ``currency_name``, ``cryptocurrency``, + ``cryptocurrency_code`` and ``cryptocurrency_name`` to currency provider. + Thanks @ZuluPro. +* Add automotive provider for ``de_DE``. Thanks @gsilvan. +* Fix edgecases for Finnish ``ssn`` provider. Thanks @sanga. +* Add job provider for ``pt_BR``. Thanks @paladini. +* Add ``unix_device`` and ``unix_partition`` to ``file`` provider. + Thanks @ZuluPro. +* Add ``random_lowercase_letter`` and ``random_uppercase_letter`` to the base + provider. Thanks @ZuluPro. +* Clarify CLI help. Thanks @confirmationbias616. + + +`0.8.12 - 12-March-2018 `__ +-------------------------------------------------------------------------------------- + +* Fix issue with ``cx_Freeze``. Thanks @sedominik. +* Add dutch ``nl_NL`` bank provider. Thanks @PatSousa. +* Add ``distrito`` and ``freguesia`` to ``pt_PT`` ``address`` provider. + Thanks @ZuluPro. +* Fix unicode issues with the ``person`` provider. Thanks @karthikarul20. +* Add ``en_SG`` ``person`` provider. Thanks @karthikarul20. +* Add street names to the Ukrainian address provider. Thanks @cadmi. +* Add ``de_AT`` address provider. Thanks @bessl. +* Fix credit card prefixes. Thanks @jphalip. +* Fix capitalization in ``no_NO`` address provider. Thanks @cloveras. +* Fix deprecated syntax for raw strings. Thanks @dchudz. +* Add ``latitude`` and ``longitude`` to ``de_AT`` ``address`` provider. + Thanks @bessl. +* Fix incorrect value in list of middle name for locale ``ru_RU``. + Thanks @damirazo. + +`0.8.11 - 12-February-2018 `__ +----------------------------------------------------------------------------------------- + +* Add scheme selection for internet ``url`` provider. Thanks @ProvoK. +* Increase lower bound on AD date generation. Thanks @prophile. +* Add the ability to specify the min and max age for some ssn locales. + Thanks @frangiz. + +`0.8.10 - 16-January-2018 `__ +--------------------------------------------------------------------------------------- + +* Pass ``python_requires`` argument to ``setuptools``. Thanks @jdufresne. +* Remove some words from ``en_US`` lorem ipsum provider. Thanks @Pomax. + +`0.8.9 - 12-January-2018 `__ +------------------------------------------------------------------------------------- + +* Remove support for Python 3.3. Thanks @jdufresne. +* Allow past dates within a second. Thanks @DanEEstar. +* Added phone number formatting to ``en_GB`` localisation to ensure no genuine + phone numbers are generated. Thanks @TheSapper. +* Added ``en_GB`` localisation for SSN (UK National Insurance Number). + Thanks @TheSapper. +* Added ``ro_RO`` person Provider. Thanks @vasilesmartup. +* Added ``domain`` argument to ``email`` provider. Thanks @lcd1232. + + +`0.8.8 - 19-December-2017 `__ +-------------------------------------------------------------------------------------- + +* made ``seed_instance`` return ``self`` for chainability. +* Add ``en_US`` locale for ``lorem``. Thanks @shacker. +* ``fi_FI`` gender specific data added. Thanks @mikkhola. +* ``fi_FI`` address and job lists updated. Thanks @mikkhola. +* Add ``iban`` provider. Thanks @cdaller. + +`0.8.7 - 14-November-2017 `__ +-------------------------------------------------------------------------------------- + +* Corrected some issues with the Hungarian (``hu_HU``) providers, such as + incorrectly capitalized company suffixes, street/road type names and place + names. Thanks @chrisvoncsefalvay. +* The Hungarian locale's ``providers.job.job`` provider now returns Hungarian + job names, taken from the Hungarian National Statistical Office (KSH)'s 2008 + survey nomenclature of employment (FEOR '08). Thanks @chrisvoncsefalvay. +* Added ``he_IL`` locale. Thanks @bjesus. +* Fix possible infinite loop in ``random_sample_unique``. Thanks @153957. +* Add aliases to make ``pt_BR`` address provider compatible ``with en_US``. + Thanks @diegoholiveira. +* Fix ResourceWarning in ``setup.py``. Thanks @jdufresne. +* Update test requirements. + +`0.8.6 - 16-October-2017 `__ +------------------------------------------------------------------------------------- + +* Replace ``unidecode`` dependency in favor of ``text-unidecode``. Faker now + requires `text-unidecode `_. + +`0.8.5 - 13-October-2017 `__ +------------------------------------------------------------------------------------- + +* Add ASCII emails. Thanks @barseghyanartur. +* Add ``id_ID`` Providers. Thanks Sidi Ahmad. +* Fix ``date_time.time_series()`` to ensure start and end bounds are inclusive. + Thanks @bijanvakili. +* Create a provider to Brazilian license plates. Thanks @diegoholiveira. +* Use a proper international format for Ukrainian phone numbers. + Thanks @illia-v. +* Faker now requires Unidecode_. + +.. _Unidecode: https://pypi.org/project/Unidecode/ + +`0.8.4 - 22-September-2017 `__ +--------------------------------------------------------------------------------------- + +* Move ``email_validator`` to ``test_requires`` and unpinned the + version number. +* Date feature parity with datetime. Thanks @noirbizarre. +* Add ``MSISDN`` in the ``phone_number`` provider. Thanks @patrickporto. +* Add Arabic locales. Thanks @ahmedaljazzar. +* Fix datetime issue on Windows. Thanks @kungfu71186. + +`0.8.3 - 05-September-2017 `__ +--------------------------------------------------------------------------------------- + +* Fix release build. + +`0.8.2 - 05-September-2017 `__ +--------------------------------------------------------------------------------------- + +* Revert name change of ``faker.generator.random``. Thanks @adamchainz. +* Document the global shared ``random.Random`` and ``seed_instance()``. + Thanks @adamchainz. + +`0.8.1 - 28-August-2017 `__ +------------------------------------------------------------------------------------ + +* Rolled back breaking change in ``randomize_nb_elements``. + +`0.8.0 - 28-August-2017 `__ +------------------------------------------------------------------------------------- +* Add ``identity_card_number`` for ``pl_PL`` ``person`` provider. Thanks @pdaw. +* More descriptive error message when a formatter is not found. + Thanks @fcurella. +* Add ``time_series`` provider. Thanks @fcurella. +* Add per-instance seeding via ``.seed_instance`` method. Thanks @reverbc. +* Fix ``tz_TW`` ``address`` provider. Thanks @clarmso. + +`0.7.18 - 19-July-2017 `__ +------------------------------------------------------------------------------------- + +* Generate proper dates before 1970. Thanks @kungfu71186. +* Made it possible to seed ``.binary()``. Thanks @kungfu71186. +* Add color names for ``hr_HR``. Thanks @mislavcimpersak. +* Add implementation of ``ssn`` provider for the ``pl_PL`` locale. + Thanks @pdaw. +* Add ``pt_BR`` colors localization. Thanks @ppcmiranda. +* Create a method for codes of cryptocurrencies in the currency provider. + Thanks @illia-v. +* Fix female name format typo in ``hu_HU`` person provider. Thanks @swilcox. +* Fix deprecated usage of ``print`` statement in README. Thanks @cclauss. +* Add gender-specific names for ``sv_SE`` person provider. Thanks @swilcox. +* Add an implementation of `regon` for ``pl_PL`` company provider. + Thanks @pdaw. +* Addi an implementation of ``local_regon`` for ``pl_PL`` company provider. + Thanks @pdaw. +* Replace deprecated ``getargspec`` on py3. Thanks @fcurella. +* Add new ``automotive`` provider. Thanks @zafarali. +* Add an implementation of ``company_vat`` for ``pl_PL`` company provider. + Thanks @pdaw. +* Add Taiwan/Traditional character support for internet and lorem providers. + Thanks @bearnun. +* Use ``random.choices`` when available for better performance. + Thanks @catleeball. +* Refactor RGB color methods. Thanks @catleeball. + +`0.7.17 - 12-June-2017 `__ +------------------------------------------------------------------------------------- + +* Fix a timezone issue with the ``date_time_between_dates`` provider. + +`0.7.16 - 09-June-2017 `__ +------------------------------------------------------------------------------------- + +* fix timezone issues with ``date_time_between`` provider. +* Add ``ext_word_list`` parameter to methods in the `Lorem` generator. + Thanks @guinslym. + +`0.7.15 - 02-June-2017 `__ +------------------------------------------------------------------------------------- + +* fix start and end date for datetime provider methods. + +`0.7.14 - 02-June-2017 `__ +------------------------------------------------------------------------------------- + +* fix ``future_date``, `and ``past_date`` bounds. + +`0.7.13 - 02-June-2017 `__ +------------------------------------------------------------------------------------- + +* Remove capitalisation from ``hu_HU`` addresses. Thanks @Newman101. +* Add ``et_EE`` (Estonian) provider: names and ssn. Thanks @trtd. +* Proper prefix for gender in ``pl_PL`` names. Thanks @zgoda. +* Add DateTime provider for ``pl_PL``. Thanks @zgoda. +* Add ``pl_PL`` internet data provider. Thanks @zgoda. +* Fix diacritics in ``pl_PL`` street names. Thanks @zgoda. +* Add ``future_date``, ``future_datetime``, ``past_date`` and ``past_datetime`` + to DateTime Provider + + +`0.7.12 - 10-May-2017 `__ +------------------------------------------------------------------------------------ + +* Add Japanese lorem provider. Thanks @richmondwang. +* Add hr_HR names of month and names of days. Thanks @mislavcimpersak. +* Add sl_SI names of month and names of days. Thanks @mislavcimpersak. +* Update the provider ``user_agent``. Thanks @illia-v. +* Add russian words for date_time. Thanks @iskhomutov. +* Add Georgian (``ka_GE``) person and address providers. + Thanks @GeorgeLubaretsi. +* Add company provider to hu_HU locale. Thanks @Newman101. +* Allow subdomains for ``domain_name`` provider. Thanks @hiagofigueiro. +* Implement hu_HU months + days. Thanks @Newman101. +* Replacement rules for emails à->a, è->e in `de_DE` internet provider. + Thanks @Bergil32. + + +`0.7.11 - 09-April-2017 `__ +-------------------------------------------------------------------------------------- + +* Added french words for days and months. Thanks @sblondon. +* Reorganized tests. Thanks @grantbachman. +* Added file path provider. Thanks @diegommarino. +* Fixed packaging issue with tests module. Thanks @eukreign for the report. + +`0.7.10 - 13-March-2017 `__ +------------------------------------------------------------------------------------- + +* Add ISBN-10 and ISBN-13. Thanks @grantbachman. +* Add colors for `fr_FR`. Thanks @sblondon. + +`0.7.9 - 24-February-2017 `__ +-------------------------------------------------------------------------------------- + +* Fix packaging isssue. Thanks @jorti. + +`0.7.8 - 24-February-2017 `__ +-------------------------------------------------------------------------------------- + +* Add a Russian language to color provider. Thanks @kotyara1005. +* Correct UnboundLocalError in Finnish SSN generator. Thanks @lamby. +* Create internet IT provider. Thanks @GlassGruber. +* Add `fix_len` parameter to 'random_number'. Thanks @vlad-ki. +* Support zh_CN lorem. Thanks @yihuang. +* Customize chinese word connector. Thanks @yihuang. +* Add more company data to `fa_IR`. Thanks @aminalaee. +* Python 3.6 support. Thanks @stephane. +* Add `hu_HU` providers. Thanks @chrisvoncsefalvay. +* Fix tests failures. + +`0.7.7 - 20-December-2016 `__ +-------------------------------------------------------------------------------------- + +* Fix no_NO postcodes. Thanks @kdeldycke. +* Fix fa_IR city generator. Thanks @kdeldycke. + +`0.7.6 - 19-December-2016 `__ +-------------------------------------------------------------------------------------- + +* Fix packaging issue with `docs` directory. Thanks @wyattanderson. + +`0.7.5 - 16-December-2016 `__ +-------------------------------------------------------------------------------------- + +* Deprecate ``facke-factory`` package on PyPI. + +`0.7.4 - 16-December-2016 `__ +-------------------------------------------------------------------------------------- + +* Add Ukrainian ``address`` provider. Thanks @illia-v. +* Add Ukrainian ``internet`` provider. Thanks @illia-v. +* Middle name support for ``person.ru_RU`` provider. Thanks @zeal18. +* Add ``address``, ``company``, ``internet`` ans ``SSN`` provider for + ``ru_RU``. Thanks @zeal18. +* Improved ``address.pl_PL`` provider. Thanks @pkisztelinski. +* Add date and time object providers. Thanks @jtojnar. +* Refactor Korean address methods. Thanks @item4. +* Add provider for locale `nl_BE` (address, phone, ssn). Thanks @vema. +* Add additional job titles. Thanks @wontonst. +* Add Ukrainian color provider. Thanks @illia-v. +* Add support to brazilian company IDs (CNPJ). Thanks @lamenezes. +* Improve the Internet provider. Thanks@illia-v. +* Improve the Ukrainian person provider. Thanks @illia-v. +* Improve some SSN providers. Thanks @illia-v. +* Improve code samples in `README.rst` and `docs/index.rst`. Thanks @illia-v. +* Improve the method `locale`. Thanks @illia-v. +* Fix `pyfloat`. Thanks @illia-v. +* Allow left/right_digits=0 for pyfloat. Thanks @mnalt. +* update fa_IR person names and phone numbers. Thanks @aminalaee. + +`0.7.3 - 16-September-2016 `__ +--------------------------------------------------------------------------------------- + +* ``date_time_this_century`` now returns ``datetime`` s outside the current + decade. Thanks @JarUrb. +* Add support for localized jobs for ``hr_HR``. Thanks @mislavcimpersak. +* Adding support for Croatian ``hr_HR`` ssn (oib). Thanks @mislavcimpersak. +* Rename PyPI package to ``Faker``. + +`0.6.0 - 09-August-2016 `__ +------------------------------------------------------------------------------------- + +* Dropped Python 2.6 support + + +`0.5.11 - 09-August-2016 `__ +--------------------------------------------------------------------------------------- + +* Add optional parameter `sex` to `profile` and `simple_profile`. + Thanks @navyad. +* Fix whitespace in dk_DK provider last_names/last_name. Thanks @iAndriy. +* Fix utf8 coding issue with ``address/fi_FI`` provider. Thanks @delneg. +* ! Latest version to support Python 2.6 + +`0.5.10 - 01-August-2016 `__ +-------------------------------------------------------------------------------------- + +* Fix random_sample_unique. Thanks @cecedille1. + +`0.5.9 - 08-July-2016 `__ +---------------------------------------------------------------------------------- + +* Add more ``pt_BR`` names. Thanks @cuducos. +* Added ``en_GB`` names. Thanks @jonny5532. +* Add romanized internet provider for ``zh_CN``. +* Add ``fr_CH`` providers. Thanks @gfavre. + +`0.5.8 - 28-June-2016 `__ +---------------------------------------------------------------------------------- + +* Improve CLI output and help. Thanks @cbaines. +* Update ``en_US`` anmes to be more realistic. Thanks @dethpickle. +* Modify pystr provider to accept a minimum number of characters. + Thanks @tamarbuta. +* Add `job` Provider for ``zh_TW``. Thanks @weihanglo. +* Modify ``zh_TW`` phone number for a more valid format. Thanks @weihanglo. +* Reduce the maximum value of start timestamps. Thanks @cbaines. +* Add `random_sample` and `random_sample_unique`. Thanks @bengolder. + +`0.5.7 - 07-March-2016 `__ +----------------------------------------------------------------------------------- + +* Repackage to resolve PyPI issue. + +`0.5.6 - 07-March-2016 `__ +----------------------------------------------------------------------------------- + +* Add date handling for datetime functions. Thanks @rpkilby. +* Discern male and female first names in pt_BR. Thanks @gabrielusvicente. + +`0.5.5 - 29-February-2016 `__ +-------------------------------------------------------------------------------------- + +* Specify help text for command line. Thanks @cbaines. + +`0.5.4 - 29-February-2016 `__ +-------------------------------------------------------------------------------------- + +* Expose Provider's random instance. Thank @gsingers for the suggestion. +* Make sure required characters are in the password. Thanks @craig552uk. +* Add ``internet`` and ``job`` Providers for ``fa_IR``. Thanks @hamidfzm. +* Correct Poland phone numbers. Thanks @fizista. +* Fix brittly tests due to seconds elapsed in-between comparison +* Allow unicode in emails and domains. Thanks @zdelagrange for the report. +* Use ``dateutil`` for computing next_month. Thanks @mark-love, @rshk. +* Fix tests module import. Thanks @jorti for the report. +* Handle unexpected length in ``ean()``. Thanks @michaelcho. +* Add internet provider for ``ja_JP``. Thanks @massa142. +* Add Romanized Japanese person name. Thanks @massa142. +* Add tzinfo support to datetime methods. Thanks @j0hnsmith. +* Add an 'office' file extensions category. Thanks @j0hnsmith. +* Generate name according to profile's sex. Thanks @Dutcho for the report. +* Add ``bs_BA`` phone number and internet provider. Thanks @elahmo. +* Add a SSN provider for ``zh_CN``. Thanks @felixonmars. +* Differentiate male and female first names in ``fr_FR`` locale. + Thanks @GregoryVds +* Add Maestro credit card. Thanks @anthonylauzon. +* Add ``hr_HR`` localization. Thanks @mislavcimpersak. +* Update ``de_DE`` first names. Thanks @WarrenFaith and @mschoebel. +* Allow generation of IPv4 and IPv6 network address with valid CIDR. + Thanks @kdeldycke. +* Unittest IPv4 and IPv6 address and network generation. Thanks @kdeldycke. +* Add a new provider to generate random binary blob. Thanks @kdeldycke. +* Check that randomly produced language codes are parseable as locale by the + factory constructor. Thanks @kdeldycke. +* Fix chinese random language code. Thanks @kdeldycke. +* Remove duplicate words from Lorem provider. Thanks @jeffwidman. + +`0.5.3 - 21-September-2015 `__ +--------------------------------------------------------------------------------------- + +* Added ``company_vat`` to company ``fi_FI`` provider. Thanks @kivipe. +* Seed a Random instance instead of the module. Thanks Amy Hanlon. +* Fixed en_GB postcodes to be more realistic. Thanks @mapleoin for the report. +* Fixed support for Python 3 in the python provider. Thanks @derekjamescurtis. +* Fixed U.S. SSN generation. Thanks @jschaf. +* Use environment markers for wheels. Thanks @RonnyPfannschmidt +* Fixed Python3 issue in ``pyiterable`` and ``pystruct`` providers. + Thanks @derekjamescurtis. +* Fixed ``en_GB`` postcodes to be more realistic. Thanks @mapleoin. +* Fixed and improved performance of credit card number provider. Thanks @0x000. +* Added Brazilian SSN, aka CPF. Thanks @ericchaves. +* Added female and male names for ``fa_IR``. Thanks @afshinrodgar. +* Fixed issues with Decimal objects as input to geo_coordinate. Thanks @davy. +* Fixed bug for ``center`` set to ``None`` in geo_coordinate. Thanks @davy. +* Fixed deprecated image URL placeholder services. +* Fixed provider's example formatting in documentation. +* Added en_AU provider. Thanks @xfxf. + +`0.5.2 - 11-June-2015 `__ +---------------------------------------------------------------------------------- + +* Added ``uuid4`` to ``misc`` provider. Thanks Jared Culp. +* Fixed ``jcb15`` and ``jcb16`` in ``credit_card`` provider. + Thanks Rodrigo Braz. +* Fixed CVV and CID code generation in `credit_card` provider. + Thanks Kevin Stone. +* Added ``--include`` flag to command line tool. Thanks Flavio Curella. +* Added ``country_code`` to `address`` provider. Thanks @elad101 and Tobin Brown. + + +`0.5.1 - 21-May-2015 `__ +------------------------------------------------------------------------------- + +* Fixed egg installation. Thanks David R. MacIver, @kecaps +* Updated person names for ``ru_RU``. Thanks @mousebaiker. +* Updated ko_KR locale. Thanks Lee Yeonjae. +* Fixed installation to install importlib on Python 2.6. + Thanks Guillaume Thomas. +* Improved tests. Thanks Aarni Koskela, @kecaps, @kaushal. +* Made Person ``prefixes``/``suffixes`` always return strings. + Thanks Aarni Koskela. +* ``pl_PL`` jobs added. Thanks Dariusz Choruży. +* Added ``ja_JP`` provider. Thanks Tatsuji Tsuchiya, Masato Ohba. +* Localized remaining providers for consistency. Thanks Flavio Curella. +* List of providers in compiled on runtime and is not hardcoded anymore. + Thanks Flavio Curella. +* Fixed State names in ``en_US``. Thanks Greg Meece. +* Added ``time_delta`` method to ``date_time`` provider. Thanks Tobin Brown. +* Added filename and file extension methods to ``file`` provider. + Thanks Tobin Brown. +* Added Finnish ssn (HETU) provider. Thanks @kivipe. +* Fixed person names for ``pl_PL``. Thanks Marek Bleschke. +* Added ``sv_SE`` locale providers. + Thanks Tome Cvitan. +* ``pt_BR`` Provider: Added ``catch_phrase`` to Company provider and fixed + names in Person Provider. Thanks Marcelo Fonseca Tambalo. +* Added ``sk_SK`` localized providers. Thanks @viktormaruna. +* Removed ``miscelleneous`` provider. It is superceded by the + ``misc`` provider. + +`0.5.0 - 16-Feb-2015 `__ +------------------------------------------------------------------------------- + +* Localized providers +* Updated ``ko_KR`` provider. Thanks Lee Yeonjae. +* Added ``pt_PT`` provider. Thanks João Delgado. +* Fixed mispellings for ``en_US`` company provider. Thanks Greg Meece. +* Added currency provider. Thanks Wiktor Ślęczka +* Ensure choice_distribution always uses floats. Thanks Katy Lavallee. +* Added ``uk_UA`` provider. Thanks Cyril Tarasenko. +* Fixed encoding issues with README, CHANGELOG and setup.py. + Thanks Sven-Hendrik Haase. +* Added Turkish person names and phone number patterns. Thanks Murat Çorlu. +* Added ``ne_NP`` provider. Thanks Sudip Kafle. +* Added provider for Austrian ``de_AT``. Thanks Bernhard Essl. + +`0.4.2 - 20-Aug-2014 `__ +--------------------------------------------------------------------------------- + +* Fixed setup + +`0.4.1 - 20-Aug-2014 `__ +------------------------------------------------------------------------------- + +* Added MAC address provider. Thanks Sébastien Béal. +* Added ``lt_LT`` and ``lv_LV`` localized providers. Thanks Edgar Gavrik. +* Added ``nl_NL`` localized providers. Thanks @LolkeAB, @mdxs. +* Added ``bg_BG`` localized providers. Thanks Bret B. +* Added ``sl_SI``. Thanks to @janezkranjc +* Added distribution feature. Thanks to @fcurella +* Relative date time. Thanks to @soobrosa +* Fixed ``date_time_ad`` on 32bit Linux. Thanks @mdxs. +* Fixed ``domain_word`` to output slugified strings. + +`0.4 - 30-Mar-2014 `__ +----------------------------------------------------------------------------- + +* Modified en_US ``person.py`` to ouput female and male names. + Thanks Adrian Klaver. +* Added SSN provider for ``en_US`` and ``en_CA``. Thanks Scott (@milliquet). +* Added ``hi_IN`` localized provider. Thanks Pratik Kabra. +* Refactoring of command line + +0.3.2 - 11-Nov-2013 +------------------- + +* New provider: Credit card generator +* Improved Documentor + + +0.3.1 +----- + +* FIX setup.py + + +0.3 - 18-Oct-2013 +----------------- + +* PEP8 style conversion (old camelCased methods are deprecated!) +* New language: ``pt_BR`` (thanks to @rvnovaes) +* all localized provider now uses ``from __future__ import unicode_literals`` +* documentor prints localized provider after all defaults +* FIX tests for python 2.6 + + +0.2 - 01-Dec-2012 +----------------- + +* New providers: ``Python``, ``File`` +* Providers imported with ``__import__`` +* Module is runnable with ``python -m faker [name] [*args]`` +* Rewrite fake generator system (allow autocompletation) +* New language: French +* Rewrite module ``__main__`` and new Documentor class + +0.1 - 13-Nov-2012 +----------------- + +* First release diff --git a/testbed/joke2k__faker/CONTRIBUTING.rst b/testbed/joke2k__faker/CONTRIBUTING.rst new file mode 100644 index 0000000000000000000000000000000000000000..dd586cb1295bbad897ae4e0334b6e2b5f0b80089 --- /dev/null +++ b/testbed/joke2k__faker/CONTRIBUTING.rst @@ -0,0 +1,47 @@ +How to contribute +================= + +We love pull requests. Here's a quick guide: + +Getting Started +--------------- + +- Make sure you have a `GitHub account `__ +- Submit a ticket for your issue, assuming one does not already exist. +- Clearly describe the issue including steps to reproduce when it is a bug. +- Make sure you fill in the earliest version that you know has the issue. +- Fork the repository on GitHub + +Making Changes +-------------- + +- Create a topic branch from where you want to base your work. +- This is usually the master branch. +- Only target release branches if you are certain your fix must be on + that branch. +- To quickly create a topic branch based on master; + ``git branch fix/master/my_contribution master`` then checkout + the new branch with ``git checkout fix/master/my_contribution``. + Please avoid working directly on the ``master`` branch. +- Make commits of logical units. +- Follow our `coding style`_. +- Check for unnecessary whitespace with ``git diff --check`` before + committing. +- Make sure you have added the necessary tests for your changes. +- Run *all* the tests to assure nothing else was accidentally broken. + +Submitting Changes +------------------ + +- Push your changes to a topic branch in your fork of the repository. +- Submit a pull request to the repository. + +Additional Resources +==================== + +- `General GitHub documentation `__ +- `GitHub pull request + documentation `__ + + +.. _`coding style`: https://github.com/joke2k/faker/blob/master/docs/coding_style.rst diff --git a/testbed/joke2k__faker/ISSUE_TEMPLATE.md b/testbed/joke2k__faker/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..6f69df9179f4d99fef07773a2a907682c477c345 --- /dev/null +++ b/testbed/joke2k__faker/ISSUE_TEMPLATE.md @@ -0,0 +1,18 @@ +* Faker version: +* OS: + +Brief summary of the issue goes here. + +### Steps to reproduce + +1. step 1 +1. step 2 +1. step 3 + +### Expected behavior + +X should be ... + +### Actual behavior + +X is ... diff --git a/testbed/joke2k__faker/LICENSE.txt b/testbed/joke2k__faker/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ed0d5676eb7cc0abafcf06da941e5abd2c06006 --- /dev/null +++ b/testbed/joke2k__faker/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2012 Daniele Faraglia + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE 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 THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/testbed/joke2k__faker/MANIFEST.in b/testbed/joke2k__faker/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..22165b579b8dc71c7e1058ed3e74cfcf39a4eb56 --- /dev/null +++ b/testbed/joke2k__faker/MANIFEST.in @@ -0,0 +1,16 @@ +include README.rst +include LICENSE.txt +include CONTRIBUTING.rst +include CHANGELOG.rst +include RELEASE_PROCESS.rst +include VERSION +recursive-include tests *.json +recursive-include tests *.py + +global-exclude *.py[cod] __pycache__ *.so +exclude Makefile tox.ini .coveragerc .bumpversion.cfg .dockerignore .isort.cfg +exclude ISSUE_TEMPLATE.md PULL_REQUEST_TEMPLATE.md +exclude appveyor.yml readthedocs.yml +exclude build32bit.sh +prune docs +prune .circleci diff --git a/testbed/joke2k__faker/Makefile b/testbed/joke2k__faker/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..a20806207dedadbe2996982e106a4dc46962c63f --- /dev/null +++ b/testbed/joke2k__faker/Makefile @@ -0,0 +1,12 @@ +test: + tox -e py + +isort: + isort -rc --atomic . + +release: + check-manifest + rm -rf build dist + python setup.py sdist bdist_wheel + git push --tags + twine upload dist/* diff --git a/testbed/joke2k__faker/PULL_REQUEST_TEMPLATE.md b/testbed/joke2k__faker/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..bd870f1095cf322d88220a7dcc8df607d2205801 --- /dev/null +++ b/testbed/joke2k__faker/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +### What does this changes + +Brief summary of the changes + +### What was wrong + +Description of what was the root cause of the issue. + +### How this fixes it + +Description of how the changes fix the issue. + +Fixes #... diff --git a/testbed/joke2k__faker/README.rst b/testbed/joke2k__faker/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..cbfbb55d1e364dc75d3f11d8d02d62c2ae65d702 --- /dev/null +++ b/testbed/joke2k__faker/README.rst @@ -0,0 +1,448 @@ +*Faker* is a Python package that generates fake data for you. Whether +you need to bootstrap your database, create good-looking XML documents, +fill-in your persistence to stress test it, or anonymize data taken from +a production service, Faker is for you. + +Faker is heavily inspired by `PHP Faker`_, `Perl Faker`_, and by `Ruby Faker`_. + +---- + +:: + + _|_|_|_| _| + _| _|_|_| _| _| _|_| _| _|_| + _|_|_| _| _| _|_| _|_|_|_| _|_| + _| _| _| _| _| _| _| + _| _|_|_| _| _| _|_|_| _| + +|pypi| |unix_build| |windows_build| |coverage| |license| + +---- + +For more details, see the `extended docs`_, especially if you are upgrading +from version ``2.0.4`` and below as there might be breaking changes. + +Basic Usage +----------- + +Install with pip: + +.. code:: bash + + pip install Faker + +*Note: this package was previously called* ``fake-factory``. + +Use ``faker.Faker()`` to create and initialize a faker +generator, which can generate data by accessing properties named after +the type of data you want. + +.. code:: python + + from faker import Faker + fake = Faker() + + fake.name() + # 'Lucy Cechtelar' + + fake.address() + # '426 Jordy Lodge + # Cartwrightshire, SC 88120-6700' + + fake.text() + # 'Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi + # beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt + # amet quidem. Iusto deleniti cum autem ad quia aperiam. + # A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui + # quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur + # voluptatem sit aliquam. Dolores voluptatum est. + # Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est. + # Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati. + # Et sint et. Ut ducimus quod nemo ab voluptatum.' + +Each call to method ``fake.name()`` yields a different (random) result. +This is because faker forwards ``faker.Generator.method_name()`` calls +to ``faker.Generator.format(method_name)``. + +.. code:: python + + for _ in range(10): + print(fake.name()) + + # 'Adaline Reichel' + # 'Dr. Santa Prosacco DVM' + # 'Noemy Vandervort V' + # 'Lexi O'Conner' + # 'Gracie Weber' + # 'Roscoe Johns' + # 'Emmett Lebsack' + # 'Keegan Thiel' + # 'Wellington Koelpin II' + # 'Ms. Karley Kiehn V' + +Providers +--------- + +Each of the generator properties (like ``name``, ``address``, and +``lorem``) are called "fake". A faker generator has many of them, +packaged in "providers". + +.. code:: python + + from faker import Faker + from faker.providers import internet + + fake = Faker() + fake.add_provider(internet) + + print(fake.ipv4_private()) + + +Check the `extended docs`_ for a list of `bundled providers`_ and a list of +`community providers`_. + +Localization +------------ + +``faker.Faker`` can take a locale as an argument, to return localized +data. If no localized provider is found, the factory falls back to the +default en\_US locale. + +.. code:: python + + from faker import Faker + fake = Faker('it_IT') + for _ in range(10): + print(fake.name()) + + # 'Elda Palumbo' + # 'Pacifico Giordano' + # 'Sig. Avide Guerra' + # 'Yago Amato' + # 'Eustachio Messina' + # 'Dott. Violante Lombardo' + # 'Sig. Alighieri Monti' + # 'Costanzo Costa' + # 'Nazzareno Barbieri' + # 'Max Coppola' + +``faker.Faker`` also supports multiple locales. New in v3.0.0. + +.. code:: python + + from faker import Faker + fake = Faker(['it_IT', 'en_US', 'ja_JP']) + for _ in range(10): + print(fake.name()) + + # 鈴木 陽一 + # Leslie Moreno + # Emma Williams + # 渡辺 裕美子 + # Marcantonio Galuppi + # Martha Davis + # Kristen Turner + # 中津川 春香 + # Ashley Castillo + # 山田 桃子 + +You can check available Faker locales in the source code, under the +providers package. The localization of Faker is an ongoing process, for +which we need your help. Please don't hesitate to create a localized +provider for your own locale and submit a Pull Request (PR). + +Included localized providers: + +- `ar\_EG `__ - Arabic (Egypt) +- `ar\_PS `__ - Arabic (Palestine) +- `ar\_SA `__ - Arabic (Saudi Arabia) +- `bg\_BG `__ - Bulgarian +- `bs\_BA `__ - Bosnian +- `cs\_CZ `__ - Czech +- `de\_DE `__ - German +- `dk\_DK `__ - Danish +- `el\_GR `__ - Greek +- `en\_AU `__ - English (Australia) +- `en\_CA `__ - English (Canada) +- `en\_GB `__ - English (Great Britain) +- `en\_NZ `__ - English (New Zealand) +- `en\_US `__ - English (United States) +- `es\_ES `__ - Spanish (Spain) +- `es\_MX `__ - Spanish (Mexico) +- `et\_EE `__ - Estonian +- `fa\_IR `__ - Persian (Iran) +- `fi\_FI `__ - Finnish +- `fr\_FR `__ - French +- `hi\_IN `__ - Hindi +- `hr\_HR `__ - Croatian +- `hu\_HU `__ - Hungarian +- `hy\_AM `__ - Armenian +- `it\_IT `__ - Italian +- `ja\_JP `__ - Japanese +- `ka\_GE `__ - Georgian (Georgia) +- `ko\_KR `__ - Korean +- `lt\_LT `__ - Lithuanian +- `lv\_LV `__ - Latvian +- `ne\_NP `__ - Nepali +- `nl\_NL `__ - Dutch (Netherlands) +- `no\_NO `__ - Norwegian +- `pl\_PL `__ - Polish +- `pt\_BR `__ - Portuguese (Brazil) +- `pt\_PT `__ - Portuguese (Portugal) +- `ro\_RO `__ - Romanian +- `ru\_RU `__ - Russian +- `sl\_SI `__ - Slovene +- `sv\_SE `__ - Swedish +- `tr\_TR `__ - Turkish +- `uk\_UA `__ - Ukrainian +- `zh\_CN `__ - Chinese (China) +- `zh\_TW `__ - Chinese (Taiwan) + +Command line usage +------------------ + +When installed, you can invoke faker from the command-line: + +.. code:: bash + + faker [-h] [--version] [-o output] + [-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}] + [-r REPEAT] [-s SEP] + [-i {package.containing.custom_provider otherpkg.containing.custom_provider}] + [fake] [fake argument [fake argument ...]] + +Where: + +- ``faker``: is the script when installed in your environment, in + development you could use ``python -m faker`` instead + +- ``-h``, ``--help``: shows a help message + +- ``--version``: shows the program's version number + +- ``-o FILENAME``: redirects the output to the specified filename + +- ``-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}``: allows use of a localized + provider + +- ``-r REPEAT``: will generate a specified number of outputs + +- ``-s SEP``: will generate the specified separator after each + generated output + +- ``-i {my.custom_provider other.custom_provider}`` list of additional custom + providers to use. Note that is the import path of the package containing + your Provider class, not the custom Provider class itself. + +- ``fake``: is the name of the fake to generate an output for, such as + ``name``, ``address``, or ``text`` + +- ``[fake argument ...]``: optional arguments to pass to the fake (e.g. the + profile fake takes an optional list of comma separated field names as the + first argument) + +Examples: + +.. code:: bash + + $ faker address + 968 Bahringer Garden Apt. 722 + Kristinaland, NJ 09890 + + $ faker -l de_DE address + Samira-Niemeier-Allee 56 + 94812 Biedenkopf + + $ faker profile ssn,birthdate + {'ssn': u'628-10-1085', 'birthdate': '2008-03-29'} + + $ faker -r=3 -s=";" name + Willam Kertzmann; + Josiah Maggio; + Gayla Schmitt; + +How to create a Provider +------------------------ + +.. code:: python + + from faker import Faker + fake = Faker() + + # first, import a similar Provider or use the default one + from faker.providers import BaseProvider + + # create new provider class. Note that the class name _must_ be ``Provider``. + class Provider(BaseProvider): + def foo(self): + return 'bar' + + # then add new provider to faker instance + fake.add_provider(Provider) + + # now you can use: + fake.foo() + # 'bar' + +How to customize the Lorem Provider +----------------------------------- + +You can provide your own sets of words if you don't want to use the +default lorem ipsum one. The following example shows how to do it with a list of words picked from `cakeipsum `__ : + +.. code:: python + + from faker import Faker + fake = Faker() + + my_word_list = [ + 'danish','cheesecake','sugar', + 'Lollipop','wafer','Gummies', + 'sesame','Jelly','beans', + 'pie','bar','Ice','oat' ] + + fake.sentence() + # 'Expedita at beatae voluptatibus nulla omnis.' + + fake.sentence(ext_word_list=my_word_list) + # 'Oat beans oat Lollipop bar cheesecake.' + + +How to use with Factory Boy +--------------------------- + +`Factory Boy` already ships with integration with ``Faker``. Simply use the +``factory.Faker`` method of ``factory_boy``: + +.. code:: python + + import factory + from myapp.models import Book + + class BookFactory(factory.Factory): + class Meta: + model = Book + + title = factory.Faker('sentence', nb_words=4) + author_name = factory.Faker('name') + +Accessing the `random` instance +------------------------------- + +The ``.random`` property on the generator returns the instance of +``random.Random`` used to generate the values: + +.. code:: python + + from faker import Faker + fake = Faker() + fake.random + fake.random.getstate() + +By default all generators share the same instance of ``random.Random``, which +can be accessed with ``from faker.generator import random``. Using this may +be useful for plugins that want to affect all faker instances. + +Seeding the Generator +--------------------- + +When using Faker for unit testing, you will often want to generate the same +data set. For convenience, the generator also provide a ``seed()`` method, +which seeds the shared random number generator. Calling the same methods with +the same version of faker and seed produces the same results. + +.. code:: python + + from faker import Faker + fake = Faker() + Faker.seed(4321) + + print(fake.name()) + # 'Margaret Boehm' + +Each generator can also be switched to its own instance of ``random.Random``, +separate to the shared one, by using the ``seed_instance()`` method, which acts +the same way. For example: + +.. code:: python + + from faker import Faker + fake = Faker() + fake.seed_instance(4321) + + print(fake.name()) + # 'Margaret Boehm' + +Please note that as we keep updating datasets, results are not guaranteed to be +consistent across patch versions. If you hardcode results in your test, make sure +you pinned the version of ``Faker`` down to the patch number. + +Tests +----- + +Run tests: + +.. code:: bash + + $ tox + +Write documentation for providers: + +.. code:: bash + + $ python -m faker > docs.txt + + +Contribute +---------- + +Please see `CONTRIBUTING`_. + +License +------- + +Faker is released under the MIT License. See the bundled `LICENSE`_ file +for details. + +Credits +------- + +- `FZaninotto`_ / `PHP Faker`_ +- `Distribute`_ +- `Buildout`_ +- `modern-package-template`_ + + +.. _FZaninotto: https://github.com/fzaninotto +.. _PHP Faker: https://github.com/fzaninotto/Faker +.. _Perl Faker: http://search.cpan.org/~jasonk/Data-Faker-0.07/ +.. _Ruby Faker: https://github.com/stympy/faker +.. _Distribute: https://pypi.org/project/distribute/ +.. _Buildout: http://www.buildout.org/ +.. _modern-package-template: https://pypi.org/project/modern-package-template/ +.. _extended docs: https://faker.readthedocs.io/en/stable/ +.. _bundled providers: https://faker.readthedocs.io/en/stable/providers.html +.. _community providers: https://faker.readthedocs.io/en/stable/communityproviders.html +.. _LICENSE: https://github.com/joke2k/faker/blob/master/LICENSE.txt +.. _CONTRIBUTING: https://github.com/joke2k/faker/blob/master/CONTRIBUTING.rst +.. _Factory Boy: https://github.com/FactoryBoy/factory_boy + +.. |pypi| image:: https://img.shields.io/pypi/v/Faker.svg?style=flat-square&label=version + :target: https://pypi.org/project/Faker/ + :alt: Latest version released on PyPI + +.. |coverage| image:: https://img.shields.io/coveralls/joke2k/faker/master.svg?style=flat-square + :target: https://coveralls.io/r/joke2k/faker?branch=master + :alt: Test coverage + +.. |unix_build| image:: https://img.shields.io/travis/joke2k/faker/master.svg?style=flat-square&label=unix%20build + :target: http://travis-ci.org/joke2k/faker + :alt: Build status of the master branch on Mac/Linux + +.. |windows_build| image:: https://img.shields.io/appveyor/ci/joke2k/faker/master.svg?style=flat-square&label=windows%20build + :target: https://ci.appveyor.com/project/joke2k/faker + :alt: Build status of the master branch on Windows + +.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square + :target: https://raw.githubusercontent.com/joke2k/faker/master/LICENSE.txt + :alt: Package license diff --git a/testbed/joke2k__faker/RELEASE_PROCESS.rst b/testbed/joke2k__faker/RELEASE_PROCESS.rst new file mode 100644 index 0000000000000000000000000000000000000000..0c393c7e35073621108133f1b11496f668000e5a --- /dev/null +++ b/testbed/joke2k__faker/RELEASE_PROCESS.rst @@ -0,0 +1,10 @@ +Release Process +--------------- + +1. Compile entries in ``CHANGELOG.rst``. Each entry should: + * Be in the past tense (eg "Fix datetime on Windows") + * End with acknowledging the PR author(s): "Thanks @." + +2. Run ``bumpversion ``. +3. Check the commit generated by ``bumpversion``, then ``git push``. +4. Run ``make release``. diff --git a/testbed/joke2k__faker/VERSION b/testbed/joke2k__faker/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..fcdb2e109f68cff5600955a73908885fe8599bb4 --- /dev/null +++ b/testbed/joke2k__faker/VERSION @@ -0,0 +1 @@ +4.0.0 diff --git a/testbed/joke2k__faker/appveyor.yml b/testbed/joke2k__faker/appveyor.yml new file mode 100644 index 0000000000000000000000000000000000000000..952046dd59c0fbd0bc288f5a34bff08aa911bcf3 --- /dev/null +++ b/testbed/joke2k__faker/appveyor.yml @@ -0,0 +1,47 @@ +# https://ci.appveyor.com/project/joke2k/faker +build: false + +environment: + matrix: + - PYTHON: "C:\\Python35" + PYTHON_VERSION: "3.5.x" + PYTHON_ARCH: "32" + + - PYTHON: "C:\\Python36" + PYTHON_VERSION: "3.6.x" + PYTHON_ARCH: "32" + + - PYTHON: "C:\\Python37" + PYTHON_VERSION: "3.7.x" + PYTHON_ARCH: "32" + + - PYTHON: "C:\\Python38" + PYTHON_VERSION: "3.8.x" + PYTHON_ARCH: "32" + + - PYTHON: "C:\\Python35-x64" + PYTHON_VERSION: "3.5.x" + PYTHON_ARCH: "64" + + - PYTHON: "C:\\Python36-x64" + PYTHON_VERSION: "3.6.x" + PYTHON_ARCH: "64" + + - PYTHON: "C:\\Python37-x64" + PYTHON_VERSION: "3.7.x" + PYTHON_ARCH: "64" + + - PYTHON: "C:\\Python38-x64" + PYTHON_VERSION: "3.8.x" + PYTHON_ARCH: "64" + +init: + - "ECHO %PYTHON%" + - ps: "ls C:/Python*" + +test_script: + - "%PYTHON%/Scripts/pip.exe --version" + - "%PYTHON%/Scripts/pip.exe freeze" + - "%PYTHON%/python.exe --version" + - "%PYTHON%/Scripts/pip.exe install tox" + - "%PYTHON%/python.exe -m tox -e py" diff --git a/testbed/joke2k__faker/build32bit.sh b/testbed/joke2k__faker/build32bit.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ec921f3d25053ea48fd4517017592e68ea523ae --- /dev/null +++ b/testbed/joke2k__faker/build32bit.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +if [[ -z "${TEST_32BIT}" ]]; then + echo "Not on Travis" + exit 0 +fi + +docker run -v ${PWD}:/code -e INSTALL_REQUIREMENTS=${INSTALL_REQUIREMENTS} i386/ubuntu bash -c " + apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -yq python3 locales python3-pip debianutils \ + && pip3 install tox coveralls \ + && locale-gen en_US.UTF-8 \ + && export LANG='en_US.UTF-8' \ + && cd /code \ + && tox -e py \ + && coverage report" diff --git a/testbed/joke2k__faker/docs/Makefile b/testbed/joke2k__faker/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..e1d917aef41f60ab7d66f38c3c08219936e42e55 --- /dev/null +++ b/testbed/joke2k__faker/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Faker.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Faker.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/Faker" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Faker" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/testbed/joke2k__faker/docs/_templates/breadcrumbs.html b/testbed/joke2k__faker/docs/_templates/breadcrumbs.html new file mode 100644 index 0000000000000000000000000000000000000000..35068887dee972cf6b9b2dfdfeba842aae791d44 --- /dev/null +++ b/testbed/joke2k__faker/docs/_templates/breadcrumbs.html @@ -0,0 +1,7 @@ +{%- extends "sphinx_rtd_theme/breadcrumbs.html" %} + +{% block breadcrumbs_aside %} + {% if not meta or meta.get('github_url') != 'hide' %} + {{ super() }} + {% endif %} +{% endblock %} diff --git a/testbed/joke2k__faker/docs/coding_style.rst b/testbed/joke2k__faker/docs/coding_style.rst new file mode 100644 index 0000000000000000000000000000000000000000..a635cc83f76f3d49360985b4cb9bc5785592f814 --- /dev/null +++ b/testbed/joke2k__faker/docs/coding_style.rst @@ -0,0 +1,25 @@ +Coding Style +============ + +Lines length should not exceed 120 characters. Please use trailing commas. + +You can find our complete flake8 configuration in the tox.ini_ file. + + +Data Sets +--------- + +For each data set, please provide a comment with reference to the source +and/or origin of the data. + +We only accept new data if it's coming from statistical sources, such as census or government institutions. This include names and their distribution. + + +Name Lists +---------- + +When you have long lists of names, please order them alphabetically. Keep the lines length as close as possible to 120 characters, without exceeding the limit. + +.. _`tox.ini`: https://github.com/joke2k/faker/blob/master/tox.ini +.. _`pep 8`: https://python.org/dev/peps/pep-0008 +.. _`pep 263`: https://python.org/dev/peps/pep-0263 diff --git a/testbed/joke2k__faker/docs/communityproviders.rst b/testbed/joke2k__faker/docs/communityproviders.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f71f59e6534753507a904a18a97c2fec40d585c --- /dev/null +++ b/testbed/joke2k__faker/docs/communityproviders.rst @@ -0,0 +1,44 @@ +.. ref-communityproviders: + +Community Providers +=================== + +Here's a list of Providers written by the community: + ++---------------+--------------------------+----------------------------------+ +| Provider name | Description | URL | ++===============+==========================+==================================+ +| WebProvider | Web-related data such as | `faker_web`_ + +| | mime-type and web server | + +| | versions. | + ++---------------+--------------------------+----------------------------------+ +| CloudProvider | Cloud-related data | `faker_cloud`_ + +| | generic or specialized | + +| | by cloud. | + ++---------------+--------------------------+----------------------------------+ +| Wi-Fi ESSID | Fake Wi-Fi ESSIDs. | `faker_wifi_essid`_ + ++---------------+--------------------------+----------------------------------+ +| Credit Score | Fake credit score data | `faker_credit_score`_ | +| | for testing purposes | | ++---------------+--------------------------+----------------------------------+ +| Microservice | Fake microservice names | `faker_microservice`_ | ++---------------+--------------------------+----------------------------------+ + +If you want to add your own provider to this list, please submit a Pull Request to our `repo`_. + +In order to be inlcuded, your provider must satisfy these requirement: + +* it must have tests. +* it must be published on PyPI. +* it must have an `OSI-Approved`_ License. +* it must not duplicate any functionality already present in ``Faker``. +* it must not contain any profanity, either in code or in documentation. +* it must not contain any malicious nor any kind of telemetry code. + +.. _repo: https://github.com/joke2k/faker/ +.. _OSI-Approved: https://opensource.org/licenses/alphabetical +.. _faker_web: https://pypi.org/project/faker_web/ +.. _faker_cloud: https://pypi.org/project/faker-cloud/ +.. _faker_wifi_essid: https://pypi.org/project/faker-wifi-essid/ +.. _faker_credit_score: https://pypi.org/project/faker-credit-score/ +.. _faker_microservice: https://pypi.org/project/faker-microservice/ diff --git a/testbed/joke2k__faker/docs/conf.py b/testbed/joke2k__faker/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbac938f8bae604f783719a7d8346a3b504e939 --- /dev/null +++ b/testbed/joke2k__faker/docs/conf.py @@ -0,0 +1,257 @@ +# +# Faker documentation build configuration file, created by +# sphinx-quickstart on Tue Mar 11 11:25:48 2014. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.todo', + 'faker.build_docs', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'Faker' +copyright = '2014, Daniele Faraglia' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '4.0.0' +# The full version, including alpha/beta/rc tags. +release = '4.0.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Fakerdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'Faker.tex', 'Faker Documentation', + 'Daniele Faraglia', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'faker', 'Faker Documentation', + ['Daniele Faraglia'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'Faker', 'Faker Documentation', + 'Daniele Faraglia', 'Faker', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/testbed/joke2k__faker/docs/fakerclass.rst b/testbed/joke2k__faker/docs/fakerclass.rst new file mode 100644 index 0000000000000000000000000000000000000000..c7a13304d1d99e354915141a8fab073271a83a40 --- /dev/null +++ b/testbed/joke2k__faker/docs/fakerclass.rst @@ -0,0 +1,289 @@ +Using the Faker Class +===================== + +In version ``2.0.4`` and below, the ``Faker`` object is just a shortcut for the class method +``Factory.create``, and that method creates a ``Generator`` object with access to the wide +selection of provider methods. Because of how everything was set up, it was difficult to do +certain things without going through the ``Factory`` and ``Generator`` internals and without +potentially breaking a lot of things that will be difficult for users to fix when they upgrade. + +The solution was to introduce a new ``Faker`` proxy class that will, for the most part, behave +just like the old ``Faker`` shortcut but with support for multiple locales while providing the +option to subclass and a very simple upgrade path should old code be affected. For the purposes +of this document, the terms new ``Faker`` and old ``Faker`` will be used where the former refers +to the new proxy class, and the latter refers to the ``Factory.create`` shortcut. + +Breaking Change +--------------- + +Any codebase that uses the ``Faker.seed()`` method will be affected, because while both old and +new ``Faker.seed()`` points to ``Generator.seed()``, in new ``Faker``, invocation of the method +from a ``Faker`` object instance has been disabled, and attempting to do so will raise a +``TypeError`` as shown below. + +.. code:: python + + TypeError: Calling `.seed()` on instances is deprecated. Use the class method `Faker.seed()` instead. + +The rationale can be found in `the relevant PR`_, but the goal is to deal with a non-explicit +legacy behavior involving a shared ``random.Random`` instance that we believe can only become +more confusing once new ``Faker`` is added. + +Upgrade Guide +------------- + +Suppose that the affected code looks something like this: + +.. code:: python + + from faker import Faker + fake = Faker() + fake.seed(0) # This will raise a TypeError + +Just replace all `seed()` method calls from instances with ``Faker.seed()`` as shown below. This +is all that is needed to start using the new ``Faker`` class and its features, even if additional +arguments are passed to ``Faker``, because the arguments expected by new ``Faker`` and old +``Faker`` are the same. + +.. code:: python + + from faker import Faker + fake = Faker() + Faker.seed(0) + +A conservative approach is to redefine ``Faker`` as the old shortcut shown below. This will skip +using the new proxy class, but the code will still be able to use any new provider methods moving +forward while being unaffected by new bugs. Of course, that also means there will be no multiple +locale support and no option to subclass. + +.. code:: python + + from faker.factory import Factory + Faker = Factory.create + fake = Faker() + fake.seed(0) + +Proxy Class Implementation Details +---------------------------------- + +A new ``Faker`` instance is just a proxy object that has references to ``Generator`` objects, +one for each unique locale specified at instantiation. Those ``Generator`` objects are just +"instances" of old ``Faker``. If there is only one internal ``Generator`` object, the new +``Faker`` instance is running in single locale mode. If there is more than one, then it is +running in multiple locale mode. + +In single locale mode, a new ``Faker`` instance can easily be forced to behave like an instance +created using old ``Faker``, because a similar interface can be exposed on the new ``Faker`` +instance, and then proxy calls to methods, properties, and attributes to the sole ``Generator`` +object in a 1:1 fashion. In fact, that is how it is implemented and how backwards compatibility +was preserved (save for ``Faker.seed``). + +In multiple locale mode, however, that 1:1 mapping is no longer present, and how calls are proxied +depends on whether the attribute is a provider method or some attribute present in ``Generator`` +objects. It is possible to provide sane default implementations that will map neatly like what +we did for ``seed_instance``, but the rest like `add_provider` and the `random` getter and setter +are more dependent on specific use cases or are potentially dangerous. + +In those cases, it is better for users to create their own subclass with their implementation or to +directly call those methods from the internal ``Generator`` objects themselves. Multiple locale mode +will be discussed in more detail in its `dedicated section`_. + +Proxy Class Attribute Name Resolution +------------------------------------- + +The proxy class has a fairly involved attribute name resolution behavior that runs in this order: + +1. If the attribute name is ``seed``, raise a TypeError. This prevents the class method ``seed`` + from being called from an instance. +2. If #1 does not apply, check if the attribute name matches an attribute present in the proxy + class instance. If there is one, return the matching attribute. +3. If #2 failed, check if the instance is in single locale mode. If yes, proxy the call to the + sole internal ``Generator`` object, and attempt to return a matching attribute. +4. If #3 does not apply, the instance is henceforth known to be in multiple locale mode. Proceed + by checking if the attribute name matches a ``Generator`` attribute. If it does, raise a + NotImplementedError. +5. If #4 does not apply, check if the attribute name matches a cache pattern regex. If it does not, + raise an AttributeError, since it should already have been handled by #2 if one does exist. +6. If everything else has failed or does not apply, assume that the attribute name might be + referring to a provider method and perform factory/generator selection, and proxy the call + to the selected ``Generator`` object. + +Factory/generator selection will be discussed in more detail under multiple locale mode's +`dedicated section`_. + +Locale Normalization +-------------------- + +Depending on the ``locale`` value passed, a new ``Faker`` instance will either operate in single +locale mode or multiple locale mode. The value of ``locale`` can be one of the following: + +1. Any empty value like ``None`` (automatically defaults to ``en_US``) +2. A valid locale string, underscored or hyphenated +3. A list, tuple, or set with valid locale strings, underscored or hyphenated +4. An OrderedDict with key-value pairs of valid locale strings (underscored or + hyphenated) and weights + +The first two are options already expected by old ``Faker``, so it is pretty much the same for new +``Faker``. Using any of those two options will always result in a new ``Faker`` instance that is +in single locale mode. In that mode, there is really no need to retrieve a reference to the +internal ``Generator`` object because of the 1:1 proxying behavior discussed earlier. + +The potential pitfalls lie in multiple locale mode and when there is a need to access the internal +``Generator`` objects individually. Since locale strings can be written underscored (``en_US``) or +hyphenated (``en-US``), this can lead to confusion and errors, so locale strings have to be normalized +to provide consistent results without duplicates. + +During instantiation, new ``Faker`` will normalize locale strings to the underscore format, and it +will also store them as such. In other words, the locale string ``en_US`` will be treated the same +as ``en-US``, and when both are specified, the last to be processed will be treated as a duplicate +and will be discarded. The same normalization is also performed when accessing the internal +``Generator`` object via key index. + +For example, the code below will create a new ``Faker`` instance that is in single locale mode +even if four locales were specified. + +.. code:: python + + from faker import Faker + fake = Faker(['en-US', 'en_US', 'en_US', 'en-US']) + + # Will return ['en_US'] + fake.locales + + # Get reference to en_US generator + us1 = fake['en_US'] + + # Get reference to en-US generator + us2 = fake['en-US'] + + # Will return True + us1 == us2 + +.. _dedicated section: + +Multiple Locale Mode +-------------------- + +To enable multiple locale mode, the value of ``locale`` argument must be a list, tuple, set, or +OrderedDict with more than one valid locale, post-normalization. For example: + +.. code:: python + + from collections import OrderedDict + from faker import Faker + + locale_list = ['en-US', 'ja-JP', 'en_US'] + fake1 = Faker(locale_list) + + # Will return ['en_US', 'ja_JP'] + fake1.locales + + locale_odict = OrderedDict([ + ('en-US', 1), + ('ja-JP', 2), + ('en_US', 2), + ]) + fake2 = Faker(odict) + + # Will return ['en_US', 'ja_JP'] + fake1.locales + +In this mode, calling a prospective provider method from the new ``Faker`` instance will run +factory/selection logic in this order: + +1. Check if a cached mapping already exists for the provider method. If yes, use that mapping, + and skip to #3. +2. If #1 does not apply, check which ``Generator`` objects support the provider method. Cache + the results of the mapping, along with corresponding weights if they were provided during + instantiation. +3. If no generator supports the provider method, an AttributeError will be raised just as it + would have been raised using old ``Faker``. +4. If there is only one generator that supports the provider method, return the only generator. +5. If there is more than one applicable generator, and no weights were provided, randomly select + a generator using a uniform distribution, i.e. ``random.choice``. +6. If there is more than one applicable generator, and weights were provided, randomly select + a generator using a distribution defined by the provided weights. + +Other than being able to customize probabilities based on locales and minimizing performance +penalties, the factory selection logic guarantees that invoking a provider method will not fail, +for as long as at least there is at least one internal ``Generator`` object supports it. + +Examples +-------- + +There are times when it is much easier to show than it is to explain in words, so here is +a cheatsheet for new ``Faker`` in multiple locale mode. + +.. code:: python + + from collections import OrderedDict + from faker import Faker + locales = OrderedDict([ + ('en-US', 1), + ('en-PH', 2), + ('ja_JP', 3), + ]) + fake = Faker(locales) + + # Get the list of locales specified during instantiation + fake.locales + + # Get the list of internal generators of this `Faker` instance + fake.factories + + # Get the internal generator for 'en_US' locale + fake['en_US'] + + # Get the internal generator for 'en_PH' locale + fake['en_PH'] + + # Get the internal generator for 'ja_JP' locale + fake['ja_JP'] + + # Will raise a KeyError as 'en_GB' was not included + fake['en_GB'] + + # Set the seed value of the shared `random.Random` object + # across all internal generators that will ever be created + Faker.seed(0) + + # Creates and seeds a unique `random.Random` object for + # each internal generator of this `Faker` instance + fake.seed_instance(0) + + # Creates and seeds a unique `random.Random` object for + # the en_US internal generator of this `Faker` instance + fake.seed_locale('en_US', 0) + + # Generate a name based on the provided weights + # en_US - 16.67% of the time (1 / (1 + 2 + 3)) + # en_PH - 33.33% of the time (2 / (1 + 2 + 3)) + # ja_JP - 50.00% of the time (3 / (1 + 2 + 3)) + fake.name() + + # Generate a name under the en_US locale + fake['en-US'].name() + + # Generate a zipcode based on the provided weights + # Note: en_PH does not support the zipcode provider method + # en_US - 25% of the time (1 / (1 + 3)) + # ja_JP - 75% of the time (3 / (1 + 3)) + fake.zipcode() + + # Generate a zipcode under the ja_JP locale + fake['ja_JP'].zipcode() + + # Will raise an AttributeError + fake['en_PH'].zipcode() + + # Generate a Luzon province name + # Note: only en_PH out of the three supports this provider method + fake.luzon_province() + + # Generate a Luzon province name + fake['en_PH'].luzon_province() + + # Will raise an AttributeError + fake['ja_JP'].luzon_province() + +.. _the relevant PR: https://github.com/joke2k/faker/pull/1052#issuecomment-557170225 diff --git a/testbed/joke2k__faker/docs/index.rst b/testbed/joke2k__faker/docs/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..855d591afb1585da4fdc7f20df1b48a85e036930 --- /dev/null +++ b/testbed/joke2k__faker/docs/index.rst @@ -0,0 +1,31 @@ +.. Faker documentation master file, created by + sphinx-quickstart on Tue Mar 11 11:25:48 2014. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Faker's documentation! +================================= + +.. include:: ../README.rst + + +Contents +-------- + +.. toctree:: + :maxdepth: 2 + + fakerclass + providers + communityproviders + locales + coding_style + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/testbed/joke2k__faker/docs/locales/.happygit b/testbed/joke2k__faker/docs/locales/.happygit new file mode 100644 index 0000000000000000000000000000000000000000..e73518c6a8f0ce18c3e18df526c2a8e4189dc285 --- /dev/null +++ b/testbed/joke2k__faker/docs/locales/.happygit @@ -0,0 +1 @@ +# this file is intentionally empty so that git can keep track of this directory \ No newline at end of file diff --git a/testbed/joke2k__faker/docs/make.bat b/testbed/joke2k__faker/docs/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..2be0f0d5445bbef52249eb1e33d584c08bd46556 --- /dev/null +++ b/testbed/joke2k__faker/docs/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Faker.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Faker.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/testbed/joke2k__faker/docs/providers/.happygit b/testbed/joke2k__faker/docs/providers/.happygit new file mode 100644 index 0000000000000000000000000000000000000000..e73518c6a8f0ce18c3e18df526c2a8e4189dc285 --- /dev/null +++ b/testbed/joke2k__faker/docs/providers/.happygit @@ -0,0 +1 @@ +# this file is intentionally empty so that git can keep track of this directory \ No newline at end of file diff --git a/testbed/joke2k__faker/faker/__init__.py b/testbed/joke2k__faker/faker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d2b0aa2a316afcb83cfd636bcb5867127f4339 --- /dev/null +++ b/testbed/joke2k__faker/faker/__init__.py @@ -0,0 +1,5 @@ +from faker.factory import Factory # noqa F401 +from faker.generator import Generator # noqa F401 +from faker.proxy import Faker # noqa F401 + +VERSION = '4.0.0' diff --git a/testbed/joke2k__faker/faker/__main__.py b/testbed/joke2k__faker/faker/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..091c5ce75c1489134e7b0d65b057bf9866fee6e1 --- /dev/null +++ b/testbed/joke2k__faker/faker/__main__.py @@ -0,0 +1,3 @@ +if __name__ == "__main__": + from faker.cli import execute_from_command_line + execute_from_command_line() diff --git a/testbed/joke2k__faker/faker/build_docs.py b/testbed/joke2k__faker/faker/build_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..7df1ab683c343a065edd8e03c61735982befba7b --- /dev/null +++ b/testbed/joke2k__faker/faker/build_docs.py @@ -0,0 +1,121 @@ +import os +import pprint +import sys + +DOCS_ROOT = os.path.abspath(os.path.join('..', 'docs')) + + +def write(fh, s): + return fh.write(s.encode()) + + +def write_base_provider(fh, doc, base_provider): + formatters = doc.get_provider_formatters(base_provider) + write(fh, ':github_url: hide\n\n') + write_provider(fh, doc, base_provider, formatters) + + +def write_provider(fh, doc, provider, formatters, excludes=None): + + if excludes is None: + excludes = [] + + write(fh, '\n') + title = "``{}``".format(doc.get_provider_name(provider)) + write(fh, '%s\n' % title) + write(fh, "-" * len(title)) + write(fh, '\n\n::\n') + + for signature, example in formatters.items(): + if signature in excludes: + continue + try: + # `pprint` can't format sets of heterogenous types. + if not isinstance(example, set): + example = pprint.pformat(example, indent=4) + lines = str(example).expandtabs().splitlines() + except UnicodeEncodeError: + msg = 'error on "{}" with value "{}"'.format(signature, example) + raise Exception(msg) + write(fh, '\n') + write(fh, "\t{fake}\n{example}\n".format( + fake=signature, + example='\n'.join(['\t# ' + line for line in lines]), + )) + + +def write_docs(*args, **kwargs): + from faker import Faker, documentor + from faker.config import DEFAULT_LOCALE, AVAILABLE_LOCALES + from faker.providers import BaseProvider + + fake = Faker(locale=DEFAULT_LOCALE) + doc = documentor.Documentor(fake) + + # Write docs for fakers.providers.BaseProvider + base_provider = BaseProvider(fake) + fname = os.path.join(DOCS_ROOT, 'providers', 'BaseProvider.rst') + with open(fname, 'wb') as fh: + write_base_provider(fh, doc, base_provider) + + # Write docs for default locale providers + base_provider_formatters = list(dir(BaseProvider)) + formatters = doc.get_formatters(with_args=True, with_defaults=True, + excludes=base_provider_formatters) + for provider, fakers in formatters: + provider_name = doc.get_provider_name(provider) + fname = os.path.join(DOCS_ROOT, 'providers', '%s.rst' % provider_name) + with open(fname, 'wb') as fh: + write(fh, ':github_url: hide\n\n') + write_provider(fh, doc, provider, fakers) + + # Write providers index page + with open(os.path.join(DOCS_ROOT, 'providers.rst'), 'wb') as fh: + write(fh, ':github_url: hide\n\n') + write(fh, 'Providers\n') + write(fh, '=========\n') + write(fh, '.. toctree::\n') + write(fh, ' :maxdepth: 2\n\n') + write(fh, ' providers/BaseProvider\n') + [write(fh, ' providers/%s\n' % doc.get_provider_name(provider)) + for provider, fakers in formatters] + + # Write docs for locale-specific providers + AVAILABLE_LOCALES = sorted(AVAILABLE_LOCALES) + for lang in AVAILABLE_LOCALES: + fname = os.path.join(DOCS_ROOT, 'locales', '%s.rst' % lang) + with open(fname, 'wb') as fh: + write(fh, ':github_url: hide\n\n') + title = 'Language {}\n'.format(lang) + write(fh, title) + write(fh, '=' * len(title)) + write(fh, '\n') + fake = Faker(locale=lang) + d = documentor.Documentor(fake) + + for p, fs in d.get_formatters(with_args=True, with_defaults=True, + locale=lang, + excludes=base_provider_formatters): + write_provider(fh, d, p, fs) + + # Write locales index page + with open(os.path.join(DOCS_ROOT, 'locales.rst'), 'wb') as fh: + write(fh, ':github_url: hide\n\n') + write(fh, 'Locales\n') + write(fh, '=======\n') + write(fh, '.. toctree::\n') + write(fh, ' :maxdepth: 2\n\n') + [write(fh, ' locales/%s\n' % lang) for lang in AVAILABLE_LOCALES] + + +# wrappers for sphinx +def _main(app, *args, **kwargs): + return write_docs(*args, **kwargs) + + +def setup(app): + app.connect('builder-inited', _main) + + +if __name__ == "__main__": + write_docs(*sys.argv[1:]) diff --git a/testbed/joke2k__faker/faker/cli.py b/testbed/joke2k__faker/faker/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..9b687737054b3eeabeab6bdb168b3a41f2dbf477 --- /dev/null +++ b/testbed/joke2k__faker/faker/cli.py @@ -0,0 +1,266 @@ +import argparse +import logging +import os +import random +import sys + +from faker import VERSION, Faker, documentor +from faker.config import AVAILABLE_LOCALES, DEFAULT_LOCALE, META_PROVIDERS_MODULES + +__author__ = 'joke2k' + + +def print_provider(doc, provider, formatters, excludes=None, output=None): + output = output or sys.stdout + if excludes is None: + excludes = [] + + print(file=output) + print("### {}".format( + doc.get_provider_name(provider)), file=output) + print(file=output) + + for signature, example in formatters.items(): + if signature in excludes: + continue + try: + lines = str(example).expandtabs().splitlines() + except UnicodeDecodeError: + # The example is actually made of bytes. + # We could coerce to bytes, but that would fail anyway when we wiil + # try to `print` the line. + lines = [""] + except UnicodeEncodeError: + raise Exception('error on "{}" with value "{}"'.format( + signature, example)) + margin = max(30, doc.max_name_len + 1) + remains = 150 - margin + separator = '#' + for line in lines: + for i in range(0, (len(line) // remains) + 1): + print("\t{fake:<{margin}}{separator} {example}".format( + fake=signature, + separator=separator, + example=line[i * remains:(i + 1) * remains], + margin=margin, + ), file=output) + signature = separator = ' ' + + +def print_doc(provider_or_field=None, + args=None, lang=DEFAULT_LOCALE, output=None, seed=None, + includes=None): + args = args or [] + output = output or sys.stdout + fake = Faker(locale=lang, includes=includes) + fake.seed_instance(seed) + + from faker.providers import BaseProvider + base_provider_formatters = list(dir(BaseProvider)) + + if provider_or_field: + if '.' in provider_or_field: + parts = provider_or_field.split('.') + locale = parts[-2] if parts[-2] in AVAILABLE_LOCALES else lang + fake = Faker(locale, providers=[ + provider_or_field], includes=includes) + fake.seed_instance(seed) + doc = documentor.Documentor(fake) + doc.already_generated = base_provider_formatters + print_provider( + doc, + fake.get_providers()[0], + doc.get_provider_formatters(fake.get_providers()[0]), + output=output) + else: + try: + print( + fake.format( + provider_or_field, + *args), + end='', + file=output) + except AttributeError: + raise ValueError('No faker found for "{}({})"'.format( + provider_or_field, args)) + + else: + doc = documentor.Documentor(fake) + + formatters = doc.get_formatters(with_args=True, with_defaults=True) + + for provider, fakers in formatters: + + print_provider(doc, provider, fakers, output=output) + + for language in AVAILABLE_LOCALES: + if language == lang: + continue + print(file=output) + print('## LANGUAGE {}'.format(language), file=output) + fake = Faker(locale=language) + fake.seed_instance(seed) + d = documentor.Documentor(fake) + + for p, fs in d.get_formatters(with_args=True, with_defaults=True, + locale=language, + excludes=base_provider_formatters): + print_provider(d, p, fs, output=output) + + +class Command: + + def __init__(self, argv=None): + self.argv = argv or sys.argv[:] + self.prog_name = os.path.basename(self.argv[0]) + + def execute(self): + """ + Given the command-line arguments, this creates a parser appropriate + to that command, and runs it. + """ + + # retrieve default language from system environment + default_locale = os.environ.get('LANG', 'en_US').split('.')[0] + if default_locale not in AVAILABLE_LOCALES: + default_locale = DEFAULT_LOCALE + + epilog = """supported locales: + + {0} + + Faker can take a locale as an optional argument, to return localized data. If + no locale argument is specified, the factory falls back to the user's OS + locale as long as it is supported by at least one of the providers. + - for this user, the default locale is {1}. + + If the optional argument locale and/or user's default locale is not available + for the specified provider, the factory falls back to faker's default locale, + which is {2}. + +examples: + + $ faker address + 968 Bahringer Garden Apt. 722 + Kristinaland, NJ 09890 + + $ faker -l de_DE address + Samira-Niemeier-Allee 56 + 94812 Biedenkopf + + $ faker profile ssn,birthdate + {{'ssn': u'628-10-1085', 'birthdate': '2008-03-29'}} + + $ faker -r=3 -s=";" name + Willam Kertzmann; + Josiah Maggio; + Gayla Schmitt; + +""".format(', '.join(sorted(AVAILABLE_LOCALES)), + default_locale, + DEFAULT_LOCALE) + + formatter_class = argparse.RawDescriptionHelpFormatter + parser = argparse.ArgumentParser( + prog=self.prog_name, + description='{} version {}'.format(self.prog_name, VERSION), + epilog=epilog, + formatter_class=formatter_class) + + parser.add_argument("--version", action="version", + version="%(prog)s {}".format(VERSION)) + + parser.add_argument('-v', + '--verbose', + action='store_true', + help="show INFO logging events instead " + "of CRITICAL, which is the default. These logging " + "events provide insight into localization of " + "specific providers.") + + parser.add_argument('-o', metavar="output", + type=argparse.FileType('w'), + default=sys.stdout, + help="redirect output to a file") + + parser.add_argument('-l', '--lang', + choices=AVAILABLE_LOCALES, + default=default_locale, + metavar='LOCALE', + help="specify the language for a localized " + "provider (e.g. de_DE)") + parser.add_argument('-r', '--repeat', + default=1, + type=int, + help="generate the specified number of outputs") + parser.add_argument('-s', '--sep', + default='\n', + help="use the specified separator after each " + "output") + + parser.add_argument('--seed', metavar='SEED', + type=int, + help="specify a seed for the random generator so " + "that results are repeatable. Also compatible " + "with 'repeat' option") + + parser.add_argument('-i', + '--include', + default=META_PROVIDERS_MODULES, + nargs='*', + help="list of additional custom providers to " + "user, given as the import path of the module " + "containing your Provider class (not the provider " + "class itself)") + + parser.add_argument('fake', + action='store', + nargs='?', + help="name of the fake to generate output for " + "(e.g. profile)") + + parser.add_argument('fake_args', + metavar="fake argument", + action='store', + nargs='*', + help="optional arguments to pass to the fake " + "(e.g. the profile fake takes an optional " + "list of comma separated field names as the " + "first argument)") + + arguments = parser.parse_args(self.argv[1:]) + + if arguments.verbose: + logging.basicConfig(level=logging.DEBUG) + else: + logging.basicConfig(level=logging.CRITICAL) + + random.seed(arguments.seed) + seeds = random.sample(range(arguments.repeat*10), arguments.repeat) + + for i in range(arguments.repeat): + + print_doc(arguments.fake, + arguments.fake_args, + lang=arguments.lang, + output=arguments.o, + seed=seeds[i], + includes=arguments.include, + ) + print(arguments.sep, file=arguments.o) + + if not arguments.fake: + # repeat not supported for all docs + break + + +def execute_from_command_line(argv=None): + """A simple method that runs a Command.""" + if sys.stdout.encoding is None: + print('please set python env PYTHONIOENCODING=UTF-8, example: ' + 'export PYTHONIOENCODING=UTF-8, when writing to stdout', + file=sys.stderr) + exit(1) + + command = Command(argv) + command.execute() diff --git a/testbed/joke2k__faker/faker/config.py b/testbed/joke2k__faker/faker/config.py new file mode 100644 index 0000000000000000000000000000000000000000..306f9de4690bcb00241bf3d10a116a60e90e17ae --- /dev/null +++ b/testbed/joke2k__faker/faker/config.py @@ -0,0 +1,14 @@ +from importlib import import_module + +from faker.utils.loading import find_available_locales, find_available_providers + +DEFAULT_LOCALE = 'en_US' + +META_PROVIDERS_MODULES = [ + 'faker.providers', +] + +PROVIDERS = find_available_providers( + [import_module(path) for path in META_PROVIDERS_MODULES]) + +AVAILABLE_LOCALES = find_available_locales(PROVIDERS) diff --git a/testbed/joke2k__faker/faker/documentor.py b/testbed/joke2k__faker/faker/documentor.py new file mode 100644 index 0000000000000000000000000000000000000000..8b25e0f91a0af3276ee04eaed2e3c3cecbfdd02e --- /dev/null +++ b/testbed/joke2k__faker/faker/documentor.py @@ -0,0 +1,98 @@ +import inspect + + +class Documentor: + + def __init__(self, generator): + """ + :param generator: a localized Generator with providers filled, + for which to write the documentation + :type generator: faker.Generator() + """ + self.generator = generator + self.max_name_len = 0 + self.already_generated = [] + + def get_formatters(self, locale=None, excludes=None, **kwargs): + self.max_name_len = 0 + self.already_generated = [] if excludes is None else excludes[:] + formatters = [] + providers = self.generator.get_providers() + for provider in providers[::-1]: # reverse + if locale and provider.__lang__ != locale: + continue + formatters.append( + (provider, self.get_provider_formatters(provider, **kwargs)), + ) + return formatters + + def get_provider_formatters(self, provider, prefix='fake.', + with_args=True, with_defaults=True): + + formatters = {} + + for name, method in inspect.getmembers(provider, inspect.ismethod): + # skip 'private' method and inherited methods + if name.startswith('_') or name in self.already_generated: + continue + + arguments = [] + faker_args = [] + faker_kwargs = {} + + if name == 'binary': + faker_kwargs['length'] = 1024 + elif name in ['zip', 'tar']: + faker_kwargs.update({ + 'uncompressed_size': 1024, + 'min_file_size': 512, + }) + + if with_args: + # retrieve all parameter + argspec = inspect.getfullargspec(method) + + lst = [x for x in argspec.args if x not in ['self', 'cls']] + for i, arg in enumerate(lst): + + if argspec.defaults and with_defaults: + + try: + default = argspec.defaults[i] + if isinstance(default, str): + default = repr(default) + else: + # TODO check default type + default = "{}".format(default) + + arg = "{}={}".format(arg, default) + + except IndexError: + pass + + arguments.append(arg) + if with_args == 'first': + break + + if with_args != 'first': + if argspec.varargs: + arguments.append('*' + argspec.varargs) + if argspec.varkw: + arguments.append('**' + argspec.varkw) + + # build fake method signature + signature = "{}{}({})".format(prefix, name, ", ".join(arguments)) + + # make a fake example + example = self.generator.format(name, *faker_args, **faker_kwargs) + + formatters[signature] = example + + self.max_name_len = max(self.max_name_len, len(signature)) + self.already_generated.append(name) + + return formatters + + @staticmethod + def get_provider_name(provider_class): + return provider_class.__provider__ diff --git a/testbed/joke2k__faker/faker/factory.py b/testbed/joke2k__faker/faker/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..b898e3b2a779e3c0c84a64f6e7445c78596e9113 --- /dev/null +++ b/testbed/joke2k__faker/faker/factory.py @@ -0,0 +1,124 @@ +import locale as pylocale +import logging +import sys + +from importlib import import_module + +from faker.config import AVAILABLE_LOCALES, DEFAULT_LOCALE, PROVIDERS +from faker.generator import Generator +from faker.utils.loading import list_module + +logger = logging.getLogger(__name__) + +# identify if python is being run in interactive mode. If so, disable logging. +inREPL = bool(getattr(sys, 'ps1', False)) +if inREPL: + logger.setLevel(logging.CRITICAL) +else: + logger.debug('Not in REPL -> leaving logger event level as is.') + + +class Factory: + + @classmethod + def create( + cls, + locale=None, + providers=None, + generator=None, + includes=None, + **config): + if includes is None: + includes = [] + + # fix locale to package name + locale = locale.replace('-', '_') if locale else DEFAULT_LOCALE + locale = pylocale.normalize(locale).split('.')[0] + if locale not in AVAILABLE_LOCALES: + msg = 'Invalid configuration for faker locale `{}`'.format(locale) + raise AttributeError(msg) + + config['locale'] = locale + providers = providers or PROVIDERS + + providers += includes + + faker = generator or Generator(**config) + + for prov_name in providers: + if prov_name == 'faker.providers': + continue + + prov_cls, lang_found = cls._get_provider_class(prov_name, locale) + provider = prov_cls(faker) + provider.__provider__ = prov_name + provider.__lang__ = lang_found + faker.add_provider(provider) + + return faker + + @classmethod + def _get_provider_class(cls, provider, locale=''): + + provider_class = cls._find_provider_class(provider, locale) + + if provider_class: + return provider_class, locale + + if locale and locale != DEFAULT_LOCALE: + # fallback to default locale + provider_class = cls._find_provider_class(provider, DEFAULT_LOCALE) + if provider_class: + return provider_class, DEFAULT_LOCALE + + # fallback to no locale + provider_class = cls._find_provider_class(provider) + if provider_class: + return provider_class, None + + msg = 'Unable to find provider `{}` with locale `{}`'.format( + provider, locale) + raise ValueError(msg) + + @classmethod + def _find_provider_class(cls, provider_path, locale=None): + + provider_module = import_module(provider_path) + + if getattr(provider_module, 'localized', False): + + logger.debug('Looking for locale `{}` in provider `{}`.'.format( + locale, provider_module.__name__)) + + available_locales = list_module(provider_module) + if not locale or locale not in available_locales: + unavailable_locale = locale + locale = getattr( + provider_module, 'default_locale', DEFAULT_LOCALE) + logger.debug('Specified locale `{}` is not available for ' + 'provider `{}`. Locale reset to `{}` for this ' + 'provider.'.format( + unavailable_locale, provider_module.__name__, locale), + ) + else: + logger.debug('Provider `{}` has been localized to `{}`.'.format( + provider_module.__name__, locale)) + + path = "{provider_path}.{locale}".format( + provider_path=provider_path, + locale=locale, + ) + provider_module = import_module(path) + + else: + + logger.debug('Provider `{}` does not feature localization. ' + 'Specified locale `{}` is not utilized for this ' + 'provider.'.format( + provider_module.__name__, locale), + ) + + if locale is not None: + provider_module = import_module(provider_path) + + return provider_module.Provider diff --git a/testbed/joke2k__faker/faker/generator.py b/testbed/joke2k__faker/faker/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..0402659b86e145d0ace7e207bef177c6b993b418 --- /dev/null +++ b/testbed/joke2k__faker/faker/generator.py @@ -0,0 +1,108 @@ +import random as random_module +import re + +_re_token = re.compile(r'\{\{(\s?)(\w+)(\s?)\}\}') +random = random_module.Random() +mod_random = random # compat with name released in 0.8 + + +class Generator: + + __config = {} + + def __init__(self, **config): + self.providers = [] + self.__config = dict( + list(self.__config.items()) + list(config.items())) + self.__random = random + + def add_provider(self, provider): + + if isinstance(provider, type): + provider = provider(self) + + self.providers.insert(0, provider) + + for method_name in dir(provider): + # skip 'private' method + if method_name.startswith('_'): + continue + + faker_function = getattr(provider, method_name) + + if callable(faker_function): + # add all faker method to generator + self.set_formatter(method_name, faker_function) + + def provider(self, name): + try: + lst = [p for p in self.get_providers() + if p.__provider__ == name.lower()] + return lst[0] + except IndexError: + return None + + def get_providers(self): + """Returns added providers.""" + return self.providers + + @property + def random(self): + return self.__random + + @random.setter + def random(self, value): + self.__random = value + + def seed_instance(self, seed=None): + """Calls random.seed""" + if self.__random == random: + # create per-instance random obj when first time seed_instance() is + # called + self.__random = random_module.Random() + self.__random.seed(seed) + return self + + @classmethod + def seed(cls, seed=None): + random.seed(seed) + + def format(self, formatter, *args, **kwargs): + """ + This is a secure way to make a fake from another Provider. + """ + # TODO: data export? + return self.get_formatter(formatter)(*args, **kwargs) + + def get_formatter(self, formatter): + try: + return getattr(self, formatter) + except AttributeError: + if 'locale' in self.__config: + msg = 'Unknown formatter "{}" with locale "{}"'.format( + formatter, self.__config['locale'], + ) + else: + raise AttributeError('Unknown formatter "{}"'.format( + formatter, + )) + raise AttributeError(msg) + + def set_formatter(self, name, method): + """ + This method adds a provider method to generator. + Override this method to add some decoration or logging stuff. + """ + setattr(self, name, method) + + def parse(self, text): + """ + Replaces tokens (like '{{ tokenName }}' or '{{tokenName}}') + with the result from the token method call. + """ + return _re_token.sub(self.__format_token, text) + + def __format_token(self, matches): + formatter = list(matches.groups()) + formatter[1] = str(self.format(formatter[1])) + return ''.join(formatter) diff --git a/testbed/joke2k__faker/faker/providers/__init__.py b/testbed/joke2k__faker/faker/providers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0088a07d4bdc72cb054dcb4383cb4c2613122254 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/__init__.py @@ -0,0 +1,352 @@ +import re +import string + +from collections import OrderedDict + +from faker.utils.distribution import choices_distribution, choices_distribution_unique + +_re_hash = re.compile(r'#') +_re_perc = re.compile(r'%') +_re_excl = re.compile(r'!') +_re_at = re.compile(r'@') +_re_qm = re.compile(r'\?') +_re_cir = re.compile(r'\^') + + +class BaseProvider: + + __provider__ = 'base' + __lang__ = None + + # Locales supported by Linux Mint from `/usr/share/i18n/SUPPORTED` + language_locale_codes = { + 'aa': ('DJ', 'ER', 'ET'), 'af': ('ZA',), 'ak': ('GH',), 'am': ('ET',), + 'an': ('ES',), 'apn': ('IN',), + 'ar': ('AE', 'BH', 'DJ', 'DZ', 'EG', 'EH', 'ER', 'IL', 'IN', + 'IQ', 'JO', 'KM', 'KW', 'LB', 'LY', 'MA', 'MR', 'OM', + 'PS', 'QA', 'SA', 'SD', 'SO', 'SS', 'SY', 'TD', 'TN', + 'YE'), + 'as': ('IN',), 'ast': ('ES',), 'ayc': ('PE',), 'az': ('AZ', 'IN'), + 'be': ('BY',), 'bem': ('ZM',), 'ber': ('DZ', 'MA'), 'bg': ('BG',), + 'bhb': ('IN',), 'bho': ('IN',), 'bn': ('BD', 'IN'), 'bo': ('CN', 'IN'), + 'br': ('FR',), 'brx': ('IN',), 'bs': ('BA',), 'byn': ('ER',), + 'ca': ('AD', 'ES', 'FR', 'IT'), 'ce': ('RU',), 'ckb': ('IQ',), + 'cmn': ('TW',), 'crh': ('UA',), 'cs': ('CZ',), 'csb': ('PL',), + 'cv': ('RU',), 'cy': ('GB',), 'da': ('DK',), + 'de': ('AT', 'BE', 'CH', 'DE', 'LI', 'LU'), 'doi': ('IN',), + 'dv': ('MV',), 'dz': ('BT',), 'el': ('GR', 'CY'), + 'en': ('AG', 'AU', 'BW', 'CA', 'DK', 'GB', 'HK', 'IE', 'IN', 'NG', + 'NZ', 'PH', 'SG', 'US', 'ZA', 'ZM', 'ZW'), + 'eo': ('US',), + 'es': ('AR', 'BO', 'CL', 'CO', 'CR', 'CU', 'DO', 'EC', 'ES', 'GT', + 'HN', 'MX', 'NI', 'PA', 'PE', 'PR', 'PY', 'SV', 'US', 'UY', 'VE', + ), 'et': ('EE',), 'eu': ('ES', 'FR'), 'fa': ('IR',), + 'ff': ('SN',), 'fi': ('FI',), 'fil': ('PH',), 'fo': ('FO',), + 'fr': ('CA', 'CH', 'FR', 'LU'), 'fur': ('IT',), 'fy': ('NL', 'DE'), + 'ga': ('IE',), 'gd': ('GB',), 'gez': ('ER', 'ET'), 'gl': ('ES',), + 'gu': ('IN',), 'gv': ('GB',), 'ha': ('NG',), 'hak': ('TW',), + 'he': ('IL',), 'hi': ('IN',), 'hne': ('IN',), 'hr': ('HR',), + 'hsb': ('DE',), 'ht': ('HT',), 'hu': ('HU',), 'hy': ('AM',), + 'ia': ('FR',), 'id': ('ID',), 'ig': ('NG',), 'ik': ('CA',), + 'is': ('IS',), 'it': ('CH', 'IT'), 'iu': ('CA',), 'iw': ('IL',), + 'ja': ('JP',), 'ka': ('GE',), 'kk': ('KZ',), 'kl': ('GL',), + 'km': ('KH',), 'kn': ('IN',), 'ko': ('KR',), 'kok': ('IN',), + 'ks': ('IN',), 'ku': ('TR',), 'kw': ('GB',), 'ky': ('KG',), + 'lb': ('LU',), 'lg': ('UG',), 'li': ('BE', 'NL'), 'lij': ('IT',), + 'ln': ('CD',), 'lo': ('LA',), 'lt': ('LT',), 'lv': ('LV',), + 'lzh': ('TW',), 'mag': ('IN',), 'mai': ('IN',), 'mg': ('MG',), + 'mhr': ('RU',), 'mi': ('NZ',), 'mk': ('MK',), 'ml': ('IN',), + 'mn': ('MN',), 'mni': ('IN',), 'mr': ('IN',), 'ms': ('MY',), + 'mt': ('MT',), 'my': ('MM',), 'nan': ('TW',), 'nb': ('NO',), + 'nds': ('DE', 'NL'), 'ne': ('NP',), 'nhn': ('MX',), + 'niu': ('NU', 'NZ'), 'nl': ('AW', 'BE', 'NL'), 'nn': ('NO',), + 'nr': ('ZA',), 'nso': ('ZA',), 'oc': ('FR',), 'om': ('ET', 'KE'), + 'or': ('IN',), 'os': ('RU',), 'pa': ('IN', 'PK'), + 'pap': ('AN', 'AW', 'CW'), 'pl': ('PL',), 'ps': ('AF',), + 'pt': ('BR', 'PT'), 'quz': ('PE',), 'raj': ('IN',), 'ro': ('RO',), + 'ru': ('RU', 'UA'), 'rw': ('RW',), 'sa': ('IN',), 'sat': ('IN',), + 'sc': ('IT',), 'sd': ('IN', 'PK'), 'se': ('NO',), 'shs': ('CA',), + 'si': ('LK',), 'sid': ('ET',), 'sk': ('SK',), 'sl': ('SI',), + 'so': ('DJ', 'ET', 'KE', 'SO'), 'sq': ('AL', 'ML'), 'sr': ('ME', 'RS'), + 'ss': ('ZA',), 'st': ('ZA',), 'sv': ('FI', 'SE'), 'sw': ('KE', 'TZ'), + 'szl': ('PL',), 'ta': ('IN', 'LK'), 'tcy': ('IN',), 'te': ('IN',), + 'tg': ('TJ',), 'th': ('TH',), 'the': ('NP',), 'ti': ('ER', 'ET'), + 'tig': ('ER',), 'tk': ('TM',), 'tl': ('PH',), 'tn': ('ZA',), + 'tr': ('CY', 'TR'), 'ts': ('ZA',), 'tt': ('RU',), 'ug': ('CN',), + 'uk': ('UA',), 'unm': ('US',), 'ur': ('IN', 'PK'), 'uz': ('UZ',), + 've': ('ZA',), 'vi': ('VN',), 'wa': ('BE',), 'wae': ('CH',), + 'wal': ('ET',), 'wo': ('SN',), 'xh': ('ZA',), 'yi': ('US',), + 'yo': ('NG',), 'yue': ('HK',), 'zh': ('CN', 'HK', 'SG', 'TW'), + 'zu': ('ZA',), + } + + def __init__(self, generator): + self.generator = generator + + def locale(self): + language_code = self.language_code() + return language_code + '_' + self.random_element( + BaseProvider.language_locale_codes[language_code], + ) + + def language_code(self): + return self.random_element(BaseProvider.language_locale_codes.keys()) + + def random_int(self, min=0, max=9999, step=1): + """ + Returns a random integer between two values. + + :param min: lower bound value (inclusive; default=0) + :param max: upper bound value (inclusive; default=9999) + :param step: range step (default=1) + :returns: random integer between min and max + """ + return self.generator.random.randrange(min, max + 1, step) + + def random_digit(self): + """ + Returns a random digit/number + between 0 and 9. + """ + return self.generator.random.randint(0, 9) + + def random_digit_not_null(self): + """ + Returns a random non-zero digit/number + between 1 and 9. + """ + return self.generator.random.randint(1, 9) + + def random_digit_or_empty(self): + """ + Returns a random digit/number + between 0 and 9 or an empty string. + """ + if self.generator.random.randint(0, 1): + return self.generator.random.randint(0, 9) + else: + return '' + + def random_digit_not_null_or_empty(self): + """ + Returns a random non-zero digit/number + between 1 and 9 or and empty string. + """ + if self.generator.random.randint(0, 1): + return self.generator.random.randint(1, 9) + else: + return '' + + def random_number(self, digits=None, fix_len=False): + """ + Returns a random number with 1 digit (default, when digits==None), + a random number with 0 to given number of digits, or a random number + with given number to given number of digits (when ``fix_len==True``). + + :param digits: maximum number of digits + :param fix_len: should the number have fixed length? + :returns: random number with 0 to given number of digits or + fixed length number + """ + if digits is None: + digits = self.random_digit_not_null() + if digits < 0: + raise ValueError("The digit parameter must be greater than or equal to 0.") + if fix_len: + if digits > 0: + return self.generator.random.randint( + pow(10, digits - 1), pow(10, digits) - 1) + else: + raise ValueError("A number of fixed length cannot have less than 1 digit in it.") + else: + return self.generator.random.randint(0, pow(10, digits) - 1) + + def random_letter(self): + """Returns a random letter (between a-z and A-Z).""" + return self.generator.random.choice( + getattr(string, 'letters', string.ascii_letters)) + + def random_letters(self, length=16): + """Returns a random letter (between a-z and A-Z).""" + return self.random_choices( + getattr(string, 'letters', string.ascii_letters), + length=length, + ) + + def random_lowercase_letter(self): + """Returns a random lowercase letter (between a-z).""" + return self.generator.random.choice(string.ascii_lowercase) + + def random_uppercase_letter(self): + """Returns a random letter (between A-Z).""" + return self.generator.random.choice(string.ascii_uppercase) + + def random_elements(self, elements=('a', 'b', 'c'), length=None, unique=False): + if isinstance(elements, dict) and not isinstance(elements, OrderedDict): + raise ValueError("Use OrderedDict only to avoid dependency on PYTHONHASHSEED (See #363).") + + fn = choices_distribution_unique if unique else choices_distribution + + if length is None: + length = self.generator.random.randint(1, len(elements)) + + if unique and length > len(elements): + raise ValueError( + "Sample length cannot be longer than the number of unique elements to pick from.") + + if isinstance(elements, dict): + choices = elements.keys() + probabilities = elements.values() + else: + if unique: + # shortcut + return self.generator.random.sample(elements, length) + choices = elements + probabilities = [1.0 for _ in range(len(choices))] + + return fn( + list(choices), + list(probabilities), + self.generator.random, + length=length, + ) + + def random_choices(self, elements=('a', 'b', 'c'), length=None): + """ + Returns a list of random, non-unique elements from a passed object. + + If `elements` is an OrderedDict, the value will be used as a weighting + element. For example:: + + random_element(OrderedDict([ + ("{{variable_1}}", 0.5), + ("{{variable_2}}", 0.2), + ("{{variable_3}}", 0.2), + ("{{variable_4}}": 0.1) + ]) + + will have the following distribution: + * `variable_1`: 50% probability + * `variable_2`: 20% probability + * `variable_3`: 20% probability + * `variable_4`: 10% probability + + """ + return self.random_elements(elements, length, unique=False) + + def random_element(self, elements=('a', 'b', 'c')): + """ + Returns a random element from a passed object. + + If `elements` is an OrderedDict, the value will be used as a weighting + element. For example:: + + random_element(OrderedDict([ + ("{{variable_1}}", 0.5), + ("{{variable_2}}", 0.2), + ("{{variable_3}}", 0.2), + ("{{variable_4}}": 0.1) + ]) + + will have the following distribution: + * `variable_1`: 50% probability + * `variable_2`: 20% probability + * `variable_3`: 20% probability + * `variable_4`: 10% probability + + """ + + return self.random_elements(elements, length=1)[0] + + def random_sample(self, elements=('a', 'b', 'c'), length=None): + """ + Returns a list of random unique elements for the specified length. + Multiple occurrences of the same value increase its probability to be in the output. + """ + return self.random_elements(elements, length, unique=True) + + def randomize_nb_elements( + self, + number=10, + le=False, + ge=False, + min=None, + max=None): + """ + Returns a random value near number. + + :param number: value to which the result must be near + :param le: result must be lower or equal to number + :param ge: result must be greater or equal to number + :returns: a random int near number + """ + if le and ge: + return number + _min = 100 if ge else 60 + _max = 100 if le else 140 + nb = int(number * self.generator.random.randint(_min, _max) / 100) + if min is not None and nb < min: + nb = min + if max is not None and nb > max: + nb = max + return nb + + def numerify(self, text='###'): + """ + Replaces all placeholders in given text with randomized values, + replacing: all hash sign ('#') occurrences with a random digit + (from 0 to 9); all percentage sign ('%') occurrences with a + random non-zero digit (from 1 to 9); all exclamation mark ('!') + occurrences with a random digit (from 0 to 9) or an empty string; + and all at symbol ('@') occurrences with a random non-zero digit + (from 1 to 9) or an empty string. + + :param text: string to be parsed + :returns: string with all numerical placeholders filled in + """ + text = _re_hash.sub( + lambda x: str(self.random_digit()), + text) + text = _re_perc.sub( + lambda x: str(self.random_digit_not_null()), + text) + text = _re_excl.sub( + lambda x: str(self.random_digit_or_empty()), + text) + text = _re_at.sub( + lambda x: str(self.random_digit_not_null_or_empty()), + text) + return text + + def lexify(self, text='????', letters=string.ascii_letters): + """ + Replaces all question mark ('?') occurrences with a random letter. + + :param text: string to be parsed + :param letters: a set of letters to choose from. + :returns: string with all letter placeholders filled in + """ + return _re_qm.sub(lambda x: self.random_element(letters), text) + + def bothify(self, text='## ??', letters=string.ascii_letters): + """ + Replaces all placeholders with random numbers and letters. + + :param text: string to be parsed + :returns: string with all numerical and letter placeholders filled in + """ + return self.lexify(self.numerify(text), letters=letters) + + def hexify(self, text='^^^^', upper=False): + """ + Replaces all circumflex ('^') occurrences with a random + hexadecimal character. + + :param text: string to be parsed + :param upper: Format as uppercase hexadecimal + :returns: string with all letter placeholders filled in + """ + letters = string.hexdigits[:-6] + if upper: + letters = letters.upper() + return _re_cir.sub(lambda x: self.random_element(letters), text) diff --git a/testbed/joke2k__faker/faker/providers/address/__init__.py b/testbed/joke2k__faker/faker/providers/address/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f18f666152ff1320f94a3d7104b681959b234e2a --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/__init__.py @@ -0,0 +1,84 @@ +from .. import BaseProvider, date_time + +localized = True + + +class Provider(BaseProvider): + city_suffixes = ['Ville'] + street_suffixes = ['Street'] + city_formats = ('{{first_name}} {{city_suffix}}', ) + street_name_formats = ('{{last_name}} {{street_suffix}}', ) + street_address_formats = ('{{building_number}} {{street_name}}', ) + address_formats = ('{{street_address}} {{postcode}} {{city}}', ) + building_number_formats = ('##', ) + postcode_formats = ('#####', ) + countries = [tz['name'] for tz in date_time.Provider.countries] + + ALPHA_2 = 'alpha-2' + ALPHA_3 = 'alpha-3' + + alpha_2_country_codes = [tz['alpha-2-code'] for tz in date_time.Provider.countries] + alpha_3_country_codes = [tz['alpha-3-code'] for tz in date_time.Provider.countries] + + def city_suffix(self): + """ + :example 'town' + """ + return self.random_element(self.city_suffixes) + + def street_suffix(self): + """ + :example 'Avenue' + """ + return self.random_element(self.street_suffixes) + + def building_number(self): + """ + :example '791' + """ + return self.numerify(self.random_element(self.building_number_formats)) + + def city(self): + """ + :example 'Sashabury' + """ + pattern = self.random_element(self.city_formats) + return self.generator.parse(pattern) + + def street_name(self): + """ + :example 'Crist Parks' + """ + pattern = self.random_element(self.street_name_formats) + return self.generator.parse(pattern) + + def street_address(self): + """ + :example '791 Crist Parks' + """ + pattern = self.random_element(self.street_address_formats) + return self.generator.parse(pattern) + + def postcode(self): + """ + :example 86039-9874 + """ + return self.bothify(self.random_element(self.postcode_formats)).upper() + + def address(self): + """ + :example '791 Crist Parks, Sashabury, IL 86039-9874' + """ + pattern = self.random_element(self.address_formats) + return self.generator.parse(pattern) + + def country(self): + return self.random_element(self.countries) + + def country_code(self, representation=ALPHA_2): + if representation == self.ALPHA_2: + return self.random_element(self.alpha_2_country_codes) + elif representation == self.ALPHA_3: + return self.random_element(self.alpha_3_country_codes) + else: + raise ValueError("`representation` must be one of `alpha-2` or `alpha-3`.") diff --git a/testbed/joke2k__faker/faker/providers/address/cs_CZ/__init__.py b/testbed/joke2k__faker/faker/providers/address/cs_CZ/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e96f044c1618be51214ff537864ab409cbd8191 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/cs_CZ/__init__.py @@ -0,0 +1,762 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + street_name_formats = ('{{street_name}}', ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) + + building_number_formats = ('###', '##', '#', '#/#') + + street_suffixes_long = ('náměstí', ) + street_suffixes_short = ('nám.', ) + + postcode_formats = ('### ##', ) + + cities = ( + 'Abertamy', 'Adamov', 'Andělská Hora', 'Bakov nad Jizerou', 'Bavorov', + 'Bechyně', 'Benešov nad Ploučnicí', 'Benátky nad Jizerou', + 'Bezdružice', 'Bečov nad Teplou', 'Blatná', 'Blovice', 'Blšany', + 'Bochov', 'Bohušovice nad Ohří', 'Bojkovice', 'Bor', 'Borohrádek', + 'Borovany', 'Boží Dar', 'Brandýs nad Orlicí', 'Brno', 'Broumov', + 'Brtnice', 'Brumov-Bylnice', 'Brušperk', 'Budišov nad Budišovkou', + 'Budyně nad Ohří', 'Bučovice', 'Buštěhrad', 'Bystré', 'Bystřice', + 'Bystřice nad Pernštejnem', 'Bystřice pod Hostýnem', 'Bzenec', + 'Bílovec', 'Bělá nad Radbuzou', 'Bělá pod Bezdězem', 'Březnice', + 'Březová', 'Březová nad Svitavou', 'Břidličná', 'Chabařovice', + 'Chlumec', 'Chlumec nad Cidlinou', 'Choceň', 'Chomutov', 'Chotěboř', + 'Chrast', 'Chrastava', 'Chropyně', 'Chvaletice', 'Chyše', 'Chýnov', + 'Chřibská', 'Cvikov', 'Dačice', 'Dašice', 'Desná', 'Deštná', + 'Dobrovice', 'Dobruška', 'Dobřany', 'Dobřichovice', 'Dobříš', 'Doksy', + 'Dolní Benešov', 'Dolní Bousov', 'Dolní Kounice', 'Dolní Poustevna', + 'Dubá', 'Dubí', 'Dubňany', 'Duchcov', 'Děčín', 'Františkovy Lázně', + 'Fryšták', 'Frýdek-Místek', 'Frýdlant', 'Frýdlant nad Ostravicí', + 'Fulnek', 'Golčův Jeníkov', 'Habartov', 'Habry', 'Hanušovice', + 'Harrachov', 'Hartmanice', 'Havířov', 'Hejnice', 'Heřmanův Městec', + 'Hlinsko', 'Hluboká nad Vltavou', 'Hluk', 'Hodkovice nad Mohelkou', + 'Holice', 'Holýšov', 'Hora Svaté Kateřiny', 'Horažďovice', + 'Horní Benešov', 'Horní Blatná', 'Horní Bříza', 'Horní Cerekev', + 'Horní Jelení', 'Horní Jiřetín', 'Horní Planá', 'Horní Slavkov', + 'Horšovský Týn', 'Hostinné', 'Hostivice', 'Hostomice', 'Hostouň', + 'Hořice', 'Hořovice', 'Hoštka', 'Hradec Králové', + 'Hradec nad Moravicí', 'Hranice (okres Cheb)', 'Hrob', + 'Hrochův Týnec', 'Hronov', 'Hrotovice', 'Hroznětín', + 'Hrušovany nad Jevišovkou', 'Hrádek', 'Hrádek nad Nisou', 'Hulín', + 'Husinec', 'Hustopeče', 'Ivanovice na Hané', 'Ivančice', + 'Jablonec nad Jizerou', 'Jablonec nad Nisou', 'Jablonné nad Orlicí', + 'Jablonné v Podještědí', 'Jablunkov', 'Janov', 'Janovice nad Úhlavou', + 'Janské Lázně', 'Jaroměřice nad Rokytnou', 'Javorník', 'Jemnice', + 'Jesenice (okres Rakovník)', 'Jevišovice', 'Jevíčko', 'Jihlava', + 'Jilemnice', 'Jistebnice', 'Jiříkov', 'Jáchymov', 'Jílové', + 'Jílové u Prahy', 'Kamenice nad Lipou', 'Kamenický Šenov', 'Kaplice', + 'Kardašova Řečice', 'Karlovy Vary', 'Karolinka', 'Karviná', + 'Kasejovice', 'Kaznějov', 'Kašperské Hory', 'Kdyně', 'Kelč', 'Kladno', + 'Kladruby', 'Klecany', 'Klimkovice', 'Klobouky u Brna', 'Kojetín', + 'Konice', 'Kopidlno', 'Koryčany', 'Kosmonosy', 'Kostelec na Hané', + 'Kostelec nad Labem', 'Kostelec nad Orlicí', + 'Kostelec nad Černými lesy', 'Kouřim', 'Košťany', 'Kožlany', + 'Kralovice', 'Kraslice', 'Kravaře', 'Kryry', 'Králíky', 'Králův Dvůr', + 'Krásno', 'Krásná Hora nad Vltavou', 'Krásná Lípa', 'Krásné Údolí', + 'Kunovice', 'Kunštát', 'Kynšperk nad Ohří', 'Lanžhot', + 'Ledeč nad Sázavou', 'Ledvice', 'Letohrad', 'Letovice', 'Liberec', + 'Libochovice', 'Libušín', 'Libáň', 'Libčice nad Vltavou', 'Liběchov', + 'Lipník nad Bečvou', 'Litovel', 'Lišov', 'Loket', 'Lom', + 'Lomnice nad Lužnicí', 'Lomnice nad Popelkou', 'Loučná pod Klínovcem', + 'Lovosice', 'Loštice', 'Luby', 'Luhačovice', 'Lučany nad Nisou', + 'Luže', 'Lysá nad Labem', 'Lázně Bohdaneč', 'Lázně Bělohrad', + 'Lázně Kynžvart', 'Manětín', 'Mašťov', 'Meziboří', 'Meziměstí', + 'Mikulov', 'Mikulášovice', 'Miletín', 'Milevsko', 'Milovice', 'Mimoň', + 'Miroslav', 'Mirotice', 'Mirovice', 'Mirošov', 'Mladá Boleslav', + 'Mladá Vožice', 'Mnichovice', 'Mnichovo Hradiště', 'Mníšek pod Brdy', + 'Modřice', 'Mohelnice', 'Moravské Budějovice', 'Moravský Beroun', + 'Moravský Krumlov', 'Morkovice-Slížany', 'Most', 'Mýto', + 'Městec Králové', 'Město Albrechtice', 'Město Touškov', 'Měčín', + 'Mšeno', 'Nalžovské Hory', 'Napajedla', 'Nasavrky', 'Nechanice', + 'Nejdek', 'Nepomuk', 'Netolice', 'Neveklov', 'Nová Bystřice', + 'Nová Paka', 'Nová Role', 'Nová Včelnice', 'Nové Hrady', + 'Nové Město nad Metují', 'Nové Město pod Smrkem', 'Nové Sedlo', + 'Nové Strašecí', 'Nový Bydžov', 'Nový Knín', 'Náměšť nad Oslavou', + 'Nýrsko', 'Nýřany', 'Němčice nad Hanou', 'Odolena Voda', 'Odry', + 'Olešnice', 'Olomouc', 'Oloví', 'Opava', 'Opočno', 'Osek', 'Osečná', + 'Oslavany', 'Ostrava', 'Pacov', 'Pardubice', 'Paskov', + 'Pec pod Sněžkou', 'Petřvald', 'Pečky', 'Pilníkov', 'Planá', + 'Planá nad Lužnicí', 'Plasy', 'Plesná', 'Plumlov', 'Plzeň', 'Plánice', + 'Poběžovice', 'Podbořany', 'Podivín', 'Pohořelice', + 'Police nad Metují', 'Polička', 'Polná', 'Postoloprty', 'Potštát', + 'Počátky', 'Praha', 'Proseč', 'Prostějov', 'Protivín', 'Pyšely', + 'Přebuz', 'Přelouč', 'Přerov', 'Přeštice', 'Přibyslav', 'Přimda', + 'Příbor', 'Rabí', 'Radnice', 'Rajhrad', 'Ralsko', 'Raspenava', + 'Rejštejn', 'Rokytnice nad Jizerou', 'Rokytnice v Orlických horách', + 'Ronov nad Doubravou', 'Rosice', 'Rotava', 'Rousínov', + 'Rovensko pod Troskami', 'Roztoky', 'Rožmberk nad Vltavou', + 'Rožmitál pod Třemšínem', 'Rožďalovice', 'Rtyně v Podkrkonoší', + 'Rudná', 'Rudolfov', 'Rychnov u Jablonce nad Nisou', 'Rychvald', + 'Rájec-Jestřebí', 'Rýmařov', 'Sadská', 'Sedlec-Prčice', 'Sedlice', + 'Sedlčany', 'Semily', 'Sezemice', 'Sezimovo Ústí', 'Seč', 'Skalná', + 'Skuteč', 'Slatiňany', 'Slavičín', 'Slavkov u Brna', 'Slavonice', + 'Slušovice', 'Smečno', 'Smiřice', 'Smržovka', 'Sobotka', 'Soběslav', + 'Solnice', 'Spálené Poříčí', 'Staré Město (okres Uherské Hradiště)', + 'Staré Město (okres Šumperk)', 'Starý Plzenec', 'Staňkov', 'Stochov', + 'Stod', 'Strmilov', 'Stráž nad Nežárkou', 'Stráž pod Ralskem', + 'Strážnice', 'Strážov', 'Studénka', 'Stárkov', 'Stříbro', + 'Suchdol nad Lužnicí', 'Svoboda nad Úpou', 'Svratka', + 'Světlá nad Sázavou', 'Sázava', 'Tanvald', 'Telč', 'Teplice', + 'Teplice nad Metují', 'Teplá', 'Terezín', 'Tišnov', 'Toužim', + 'Tovačov', 'Trhové Sviny', 'Trhový Štěpánov', 'Trmice', + 'Týn nad Vltavou', 'Týnec nad Labem', 'Týnec nad Sázavou', + 'Týniště nad Orlicí', 'Třebechovice pod Orebem', 'Třebenice', 'Třeboň', + 'Třemošnice', 'Třemošná', 'Třešť', 'Uherský Ostroh', + 'Uhlířské Janovice', 'Unhošť', 'Valašské Klobouky', 'Valtice', + 'Vamberk', 'Vejprty', 'Velešín', 'Velká Bystřice', 'Velká Bíteš', + 'Velké Bílovice', 'Velké Hamry', 'Velké Opatovice', 'Velké Pavlovice', + 'Velký Šenov', 'Veltrusy', 'Velvary', 'Verneřice', + 'Veselí nad Lužnicí', 'Vidnava', 'Vimperk', 'Vizovice', + 'Vlachovo Březí', 'Vodňany', 'Volary', 'Volyně', 'Votice', 'Vracov', + 'Vratimov', 'Vrbno pod Pradědem', 'Vroutek', 'Vysoké Veselí', + 'Vysoké nad Jizerou', 'Vyšší Brod', 'Vítkov', 'Výsluní', 'Všeruby', + 'Zbiroh', 'Zbýšov', 'Zdice', 'Zlaté Hory', 'Zliv', 'Zlín', + 'Zruč nad Sázavou', 'Zubří', 'Zákupy', 'Zásmuky', 'Újezd u Brna', + 'Úpice', 'Úsov', 'Ústí nad Labem', 'Úterý', 'Úvaly', 'Úštěk', + 'Černovice', 'Černošice', 'Černošín', 'Červená Řečice', + 'Červený Kostelec', 'Česká Kamenice', 'Česká Skalice', + 'České Budějovice', 'České Velenice', 'Český Brod', 'Český Dub', + 'Řevnice', 'Šenov', 'Šlapanice', 'Šluknov', 'Špindlerův Mlýn', + 'Štramberk', 'Štíty', 'Štětí', 'Švihov', 'Žacléř', 'Žamberk', 'Žandov', + 'Ždánice', 'Ždírec nad Doubravou', 'Žebrák', 'Železnice', + 'Železná Ruda', 'Železný Brod', 'Židlochovice', 'Žirovnice', 'Žlutice', + 'Žulová') + + streets = ( + 'Horní Stromky', + 'Vizovická', + 'K Brusce', + 'Mírová', + 'Rašínská', + 'Boušova', + 'Pobřežní', + 'Dolnobřežanská', + 'Černá', + 'Šůrova', + 'Červenkova', + 'Nad Mostem', + 'Libuňská', + 'Chotovická', + 'Petříkova', + 'Pod Vodárenskou Věží', + 'Na Fišerce', + 'Ke Březině', + 'Za Lázeňkou', + 'Nad Šafránkou', + 'Na Laurové', + 'Nám. Republiky', + 'Vlašimská', + 'Nad Rohatci', + 'Tylišovská', + 'Nábřeží Kapitána Jaroše', + 'Lešovská', + 'U Podjezdu', + 'Průškova', + 'Estonská', + 'Máslova', + 'K Otočce', + 'Jižní', + 'Švecova', + 'Mongolská', + 'Kalská', + 'Nad Rokytkou', + 'Malešovská', + 'Plzeňská', + 'V Hájkách', + 'Úpská', + 'Ambrožova', + 'Pikovická', + 'Neužilova', + 'Na Staré Vinici', + 'Vstupní', + 'Nýdecká', + 'U Společenské Zahrady', + 'Ostrovského', + 'Bazovského', + 'Lešenská', + 'Na Štamberku', + 'Na Svahu', + 'Výhledské Nám.', + 'K Lipám', + 'Za Stadionem', + 'Opletalova', + 'Nábřeží Ludvíka Svobody', + 'Komenského Nám.', + 'Křimická', + 'Domkovská', + 'Pyšelská', + 'Štychova', + 'Horákova', + 'Nad Zavážkou', + 'K Prelátům', + 'Vašátkova', + 'Benákova', + 'Náměstí Prezidenta Masaryka', + 'Mílovská', + 'U Hostivařského Nádraží', + 'Jihovýchodní I', + 'Hostivařské Nám.', + 'Zbynická', + 'Heineho', + 'U Dobešky', + 'Doubická', + 'Ke Břvům', + 'Na Záhonech', + 'Kloboukova', + 'Kostnické Náměstí', + 'Pelclova', + 'Smotlachova', + 'Pod Spiritkou', + 'Hůlkova', + 'Matenská', + 'Do Zahrádek Ii', + 'Dobrošovská', + 'Lovčenská', + 'Jasná I', + 'Škrétova', + 'Moravanů', + 'Budapešťská', + 'Kojetická', + 'Náměstí I. P. Pavlova', + 'Bajkalská', + 'U Větrolamu', + 'Vlčická', + 'Jarešova', + 'Sámova', + 'Kotrčová', + 'Musílkova', + 'Ingrišova', + 'U Nových Domů I', + 'Dělostřelecká', + 'Ke Hrázi', + 'Mochovská', + 'Rýmařovská', + 'Dolní Chaloupky', + 'Za Arielem', + 'U Rajské Zahrady', + 'K Šedivce', + 'Březová', + 'Doubravínova', + 'Mládkova', + 'Tachovské Náměstí', + 'Lehárova', + 'Severní X', + 'V Tehovičkách', + 'Bermanova', + 'Grammova', + 'Spojovací', + 'Verdunská', + 'Závrchy', + 'Čerpadlová', + 'Vítězná', + 'Nad Plynovodem', + 'U Smíchovského Hřbitova', + 'Nedvědovo Náměstí', + 'Bachova', + 'U Dálnice', + 'Všejanská', + 'Maňákova', + 'Rokytnická', + 'Loděnická', + 'U Pumpy', + 'Michnova', + 'Záblatská', + 'Poslední', + 'Hněvkovského', + 'Za Křížem', + 'Nad Návsí', + 'Jablonecká', + 'Súdánská', + 'Mazancova', + 'Pod Čertovou Skalou', + 'Weilova', + 'Čajkovského', + 'Nad Zátiším', + 'Moldavská', + 'Juarézova', + 'Žižkova', + 'Pod Lochkovem', + 'Nad Vernerákem', + 'Žherská', + 'Prusíkova', + 'Výtoňská', + 'Na Srážku', + 'Šachovská', + 'Nučická', + 'Novákovo Náměstí', + 'Sitteho', + 'U Vápenice', + 'Na Kuthence', + 'Čelakovského Sady', + 'V Závitu', + 'Na Vartě', + 'Oválová', + 'Machovická', + 'Nad Olšinami', + 'Vajgarská', + 'Kulhavého', + 'Kodaňská', + 'Kralupská', + 'Lednická', + 'Pod Velkým Hájem', + 'Hvězdonická', + 'Na Kozinci', + 'Semická', + 'K Dálnici', + 'Trytova', + 'Vyhlídkova', + 'Pohnertova', + 'U Nového Dvora', + 'K Vodě', + 'Nad Libří', + 'K Matěji', + 'V Kotcích', + 'Kohoutových', + 'Na Cikánce', + 'Chládkova', + 'Slatiňanská', + 'Pod Kostelem', + 'Na Spojce', + 'Na Zahrádkách', + 'Nad Obcí', + 'K Přehradám', + 'Na Náspu', + 'V Nížinách', + 'Josefa Houdka', + 'Na Pěšině', + 'Hnězdenská', + 'Za Statky', + 'Kremnická', + 'Čestmírova', + 'U Rakovky', + 'Kodicilova', + 'K Lučinám', + 'Nouzov', + 'Krátký Lán', + 'Anny Drabíkové', + 'Kadaňská', + 'Stroupežnického', + 'Jírova', + 'U Dětského Hřiště', + 'Žofie Podlipské', + 'Nad Šancemi', + 'Lošáková', + 'Roblínská', + 'Mezi Sklady', + 'Na Pomezí', + 'U Mlýnského Rybníka', + 'Makedonská', + 'K Dýmači', + 'V Zátiší', + 'Pohořelec', + 'Jiřinková', + 'U Nové Dálnice', + 'Čuprova', + 'Vraňanská', + 'Severovýchodní Vi', + 'Petřínská', + 'K Hořavce', + 'Sádovská', + 'Pod Průsekem', + 'Konžská', + 'Dřítenská', + 'Pirinská', + 'U Hřiště', + 'Kukelská', + 'Moravanská', + 'Koclířova', + 'Žilinská', + 'Ve Žlíbku', + 'Veronské Nám.', + 'U Větrníku', + 'Svojsíkova', + 'Izraelská', + 'Staňkovka', + 'Na Viničních Horách', + 'Čankovská', + 'Na Špitálce', + 'Valdovská', + 'Rudoltická', + 'Ke Strašnické', + 'Paťanka', + 'Panuškova', + 'Pankrácké Nám.', + 'Budčická', + 'Šermířská', + 'Medlovská', + 'K Vidouli', + 'Horní Chaloupky', + 'V Americe', + 'Dejvická', + 'Klášterecká', + 'Šárovo Kolo', + 'Mladoboleslavská', + 'Palackého', + 'Lumiérů', + 'Ivančická', + 'Za Valem', + 'Na Břevnovské Pláni', + 'Tichonická', + 'Náměstí Hrdinů', + 'Mistřínská', + 'Křížkovského', + 'Tanvaldská', + 'V Padolině', + 'Před Skalkami Ii', + 'Na Křivce', + 'Nad Zámečkem', + 'Nad Krocínkou', + 'Podlešínská', + 'Nad Popelkou', + 'Oderská', + 'Jeruzalémská', + 'Smolenská', + 'Lebeděvova', + 'Libichovská', + 'Na Šafránce', + 'Průjezdná', + 'Záluské', + 'Branišovská', + 'Spinozova', + 'K Betáni', + 'Machuldova', + 'Podohradská', + 'Cerhenická', + 'V Brůdku', + 'U Vlachovky', + 'Pod Letištěm', + 'Vlastislavova', + 'Klecanská', + 'Žinkovská', + 'Maltézské Náměstí', + 'Boršov', + 'Mukařovského', + 'Josefa Šimůnka', + 'Suchdolská', + 'Opočínská', + 'Heydukova', + 'Vršovka', + 'Thurnova', + 'Mezilesní', + 'Za Pivovarem', + 'Uljanovská', + 'Panenská', + 'Sladovnická', + 'Plynární', + 'Kozácká', + 'Vlasákova', + 'Javornická', + 'Ševčíkova', + 'Podle Náhonu', + 'Doubravická', + 'Františka Černého', + 'Chotětovská', + 'K Háječku', + 'Pod Výšinkou', + 'U Šesté Baterie', + 'Drahanská', + 'Augustova', + 'U Balabenky', + 'Boční I', + 'Jirčanská', + 'Na Šubě', + 'Brixiho', + 'Klímova', + 'Kazín', + 'Fügnerovo Náměstí', + 'Na Příčné Mezi', + 'Plánická', + 'Africká', + 'Vratislavova', + 'Olympijská', + 'Na Bojišti', + 'K Nádrži', + 'Vokrojova', + 'Bořetínská', + 'Kováříkova', + 'Lánovská', + 'U Staré Pošty', + 'Na Poustkách', + 'V Poli', + 'Meziškolská', + 'Pajerova', + 'Habartovská', + 'Mlékárenská', + 'Dělnická', + 'U Štěpu', + 'Družná', + 'Klouzková', + 'Před Rybníkem', + 'Nad Košinkou', + 'Spolupráce', + 'V Humenci', + 'Adélčina', + 'Březanova', + 'Pod Kesnerkou', + 'Kosmonoská', + 'Do Dubin', + 'Nad Lávkou', + 'Mezi Lysinami', + 'Na Topolce', + 'Snopkova', + 'Severní Viii', + 'Okrová', + 'Třebihošťská', + 'Mádrova', + 'Na Lázeňce', + 'Slivenecká', + 'Nám. Barikád', + 'Nad Strouhou', + 'Jindřicha Plachty', + 'Pod Srázem', + 'U Waltrovky', + 'Bratří Čapků', + 'Onšovecká', + 'Machnova', + 'Kostková', + 'Rožmberská', + 'Zapských', + 'Přípřežní', + 'Výravská', + 'Podléšková', + 'Štěchovická', + 'Poleradská', + 'Jilmová', + 'Hostýnská') + + states = ( + 'Hlavní město Praha', + 'Středočeský kraj', + 'Jihočeský kraj', + 'Plzeňský kraj', + 'Karlovarský kraj', + 'Ústecký kraj', + 'Liberecký kraj', + 'Královéhradecký kraj', + 'Pardubický kraj', + 'Kraj Vysočina', + 'Jihomoravský kraj', + 'Olomoucký kraj', + 'Moravskoslezský kraj', + 'Zlínský kraj', + ) + + countries = ( + 'Afghánistán', + 'Albánie', + 'Alžírsko', + 'Andorra', + 'Angola', + 'Antigua a Barbuda', + 'Argentina', + 'Arménie', + 'Austrálie', + 'Bahamy', + 'Bahrajn', + 'Bangladéš', + 'Barbados', + 'Belgie', + 'Belize', + 'Benin', + 'Bhútán', + 'Bolívie', + 'Bosna a Hercegovina', + 'Botswana', + 'Brazílie', + 'Brunej', + 'Bulharsko', + 'Burkina Faso', + 'Burundi', + 'Bělorusko', + 'Chile', + 'Chorvatsko', + 'Cookovy ostrovy', + 'Demokratická republika Kongo', + 'Dominika', + 'Dominikánská republika', + 'Dánsko', + 'Džibutsko', + 'Egypt', + 'Ekvádor', + 'Eritrea', + 'Estonsko', + 'Etiopie', + 'Federativní státy Mikronésie', + 'Fidži', + 'Filipíny', + 'Finsko', + 'Francie', + 'Gabon', + 'Gambie', + 'Ghana', + 'Gruzie', + 'Guatemala', + 'Guinea', + 'Guinea-Bissau', + 'Guyana', + 'Haiti', + 'Honduras', + 'Indie', + 'Irsko', + 'Irák', + 'Island', + 'Itálie', + 'Izrael', + 'Jamajka', + 'Japonsko', + 'Jemen', + 'Jihoafrická republika', + 'Jižní Súdán', + 'Jordánsko', + 'Kambodža', + 'Kamerun', + 'Kanada', + 'Kapverdy', + 'Katar', + 'Kazachstán', + 'Keňa', + 'Kiribati', + 'Kolumbie', + 'Kostarika', + 'Kuba', + 'Kypr', + 'Kyrgyzstán', + 'Laos', + 'Lesotho', + 'Libanon', + 'Libye', + 'Lichtenštejnsko', + 'Litva', + 'Lotyšsko', + 'Lucembursko', + 'Madagaskar', + 'Makedonie', + 'Malajsie', + 'Malawi', + 'Maledivy', + 'Mali', + 'Malta', + 'Maroko', + 'Marshallovy ostrovy', + 'Mauricius', + 'Mauritánie', + 'Maďarsko', + 'Mexiko', + 'Moldavsko', + 'Monako', + 'Mongolsko', + 'Mosambik', + 'Myanmar', + 'Namibie', + 'Nauru', + 'Nepál', + 'Niger', + 'Nigérie', + 'Nikaragua', + 'Niue', + 'Nizozemsko', + 'Norsko', + 'Nový Zéland', + 'Německo', + 'Omán', + 'Palau', + 'Panama', + 'Papua-Nová Guinea', + 'Paraguay', + 'Peru', + 'Pobřeží slonoviny', + 'Polsko', + 'Portugalsko', + 'Pákistán', + 'Rakousko', + 'Republika Kongo', + 'Rovníková Guinea', + 'Rumunsko', + 'Rusko', + 'Rwanda', + 'Salvador', + 'Samoa', + 'San Marino', + 'Saúdská Arábie', + 'Senegal', + 'Severní Korea', + 'Seychely', + 'Sierra Leone', + 'Singapur', + 'Slovensko', + 'Slovinsko', + 'Somálsko', + 'Spojené arabské emiráty', + 'Spojené království', + 'Spojené státy americké', + 'Srbsko', + 'Středoafrická republika', + 'Surinam', + 'Svatá Lucie', + 'Svatý Kryštof a Nevis', + 'Svatý Tomáš a Princův ostrov', + 'Svatý Vincenc a Grenadiny', + 'Svazijsko', + 'Súdán', + 'Sýrie', + 'Tanzanie', + 'Thajsko', + 'Togo', + 'Tonga', + 'Trinidad a Tobago', + 'Tunisko', + 'Turecko', + 'Turkmenistán', + 'Tuvalu', + 'Tádžikistán', + 'Uganda', + 'Ukrajina', + 'Uruguay', + 'Uzbekistán', + 'Vanuatu', + 'Vatikán', + 'Venezuela', + 'Vietnam', + 'Východní Timor', + 'Zambie', + 'Zimbabwe', + 'Ázerbájdžán', + 'Írán', + 'Čad', + 'Černá Hora', + 'Česko', + 'Čína', + 'Řecko', + 'Šalamounovy ostrovy', + 'Španělsko', + 'Srí Lanka', + 'Švédsko', + 'Švýcarsko') + + def street_suffix_short(self): + return self.random_element(self.street_suffixes_short) + + def street_suffix_long(self): + return self.random_element(self.street_suffixes_long) + + def city_name(self): + return self.random_element(self.cities) + + def street_name(self): + return self.random_element(self.streets) + + def state(self): + return self.random_element(self.states) + + def postcode(self): + return self.bothify(self.random_element(self.postcode_formats)) + + def city_with_postcode(self): + return self.postcode() + " " + self.random_element(self.cities) diff --git a/testbed/joke2k__faker/faker/providers/address/de/__init__.py b/testbed/joke2k__faker/faker/providers/address/de/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c80abf45272660e448ffe5456bfedcf4ac3531f --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/de/__init__.py @@ -0,0 +1,63 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + countries = ( + 'Afghanistan', 'Alandinseln', 'Albanien', 'Algerien', + 'Amerikanisch-Ozeanien', 'Amerikanisch-Samoa', + 'Amerikanische Jungferninseln', 'Andorra', 'Angola', 'Anguilla', + 'Antarktis', 'Antigua und Barbuda', 'Argentinien', 'Armenien', 'Aruba', + 'Aserbaidschan', 'Australien', 'Bahamas', 'Bahrain', 'Bangladesch', + 'Barbados', 'Belarus', 'Belgien', 'Belize', 'Benin', 'Bermuda', + 'Bhutan', 'Bolivien', 'Bosnien und Herzegowina', 'Botsuana', + 'Bouvetinsel', 'Brasilien', 'Britische Jungferninseln', + 'Britisches Territorium im Indischen Ozean', 'Brunei Darussalam', + 'Bulgarien', 'Burkina Faso', 'Burundi', 'Chile', 'China', 'Cookinseln', + 'Costa Rica', 'Côte d’Ivoire', 'Demokratische Republik Kongo', + 'Demokratische Volksrepublik Korea', 'Deutschland', 'Dominica', + 'Dominikanische Republik', 'Dschibuti', 'Dänemark', 'Ecuador', + 'El Salvador', 'Eritrea', 'Estland', 'Falklandinseln', 'Fidschi', + 'Finnland', 'Frankreich', 'Französisch-Guayana', + 'Französisch-Polynesien', 'Färöer', 'Gabun', 'Gambia', 'Georgien', + 'Ghana', 'Gibraltar', 'Grenada', 'Griechenland', 'Grönland', + 'Guadeloupe', 'Guam', 'Guatemala', 'Guernsey', 'Guinea', + 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard- und McDonald-Inseln', + 'Honduras', 'Indien', 'Indonesien', 'Irak', 'Iran', 'Irland', 'Island', + 'Isle of Man', 'Israel', 'Italien', 'Jamaika', 'Japan', 'Jemen', + 'Jersey', 'Jordanien', 'Kaimaninseln', 'Kambodscha', 'Kamerun', + 'Kanada', 'Kap Verde', 'Kasachstan', 'Katar', 'Kenia', 'Kirgisistan', + 'Kiribati', 'Kokosinseln', 'Kolumbien', 'Komoren', 'Kongo', 'Kroatien', + 'Kuba', 'Kuwait', 'Laos', 'Lesotho', 'Lettland', 'Libanon', 'Liberia', + 'Libyen', 'Liechtenstein', 'Litauen', 'Luxemburg', 'Madagaskar', + 'Malawi', 'Malaysia', 'Malediven', 'Mali', 'Malta', 'Marokko', + 'Marshallinseln', 'Martinique', 'Mauretanien', 'Mauritius', 'Mayotte', + 'Mazedonien', 'Mexiko', 'Mikronesien', 'Monaco', 'Mongolei', + 'Montenegro', 'Montserrat', 'Mosambik', 'Myanmar', 'Namibia', 'Nauru', + 'Nepal', 'Neukaledonien', 'Neuseeland', 'Nicaragua', 'Niederlande', + 'Niederländische Antillen', 'Niger', 'Nigeria', 'Niue', 'Norfolkinsel', + 'Norwegen', 'Nördliche Marianen', 'Oman', 'Osttimor', 'Pakistan', + 'Palau', 'Palästinensische Gebiete', 'Panama', 'Papua-Neuguinea', + 'Paraguay', 'Peru', 'Philippinen', 'Pitcairn', 'Polen', 'Portugal', + 'Puerto Rico', 'Republik Korea', 'Republik Moldau', 'Ruanda', + 'Rumänien', 'Russische Föderation', 'Réunion', 'Salomonen', 'Sambia', + 'Samoa', 'San Marino', 'Saudi-Arabien', 'Schweden', 'Schweiz', + 'Senegal', 'Serbien', 'Serbien und Montenegro', 'Seychellen', + 'Sierra Leone', 'Simbabwe', 'Singapur', 'Slowakei', 'Slowenien', + 'Somalia', 'Sonderverwaltungszone Hongkong', + 'Sonderverwaltungszone Macao', 'Spanien', 'Sri Lanka', + 'St. Barthélemy', 'St. Helena', 'St. Kitts und Nevis', 'St. Lucia', + 'St. Martin', 'St. Pierre und Miquelon', + 'St. Vincent und die Grenadinen', 'Sudan', 'Suriname', + 'Svalbard und Jan Mayen', 'Swasiland', 'Syrien', + 'São Tomé und Príncipe', 'Südafrika', + 'Südgeorgien und die Südlichen Sandwichinseln', 'Tadschikistan', + 'Taiwan', 'Tansania', 'Thailand', 'Togo', 'Tokelau', 'Tonga', + 'Trinidad und Tobago', 'Tschad', 'Tschechische Republik', 'Tunesien', + 'Turkmenistan', 'Turks- und Caicosinseln', 'Tuvalu', 'Türkei', + 'Uganda', 'Ukraine', 'Ungarn', 'Uruguay', 'Usbekistan', 'Vanuatu', + 'Vatikanstadt', 'Venezuela', 'Vereinigte Arabische Emirate', + 'Vereinigte Staaten', 'Vereinigtes Königreich', 'Vietnam', + 'Wallis und Futuna', 'Weihnachtsinsel', 'Westsahara', + 'Zentralafrikanische Republik', 'Zypern', 'Ägypten', + 'Äquatorialguinea', 'Äthiopien', 'Äußeres Ozeanien', 'Österreich', + ) diff --git a/testbed/joke2k__faker/faker/providers/address/de_AT/__init__.py b/testbed/joke2k__faker/faker/providers/address/de_AT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1dcb9d9473b86a3e1f31f30c3a0b87e6ce78f8 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/de_AT/__init__.py @@ -0,0 +1,87 @@ +from ..de import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + city_with_postcode_formats = ('{{postcode}} {{city}}', ) + + street_name_formats = ( + '{{first_name}}-{{last_name}}-{{street_suffix_long}}', + '{{last_name}}{{street_suffix_short}}', + ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) + + building_number_formats = ('###', '##', '#', '#/#') + + street_suffixes_long = ( + 'Gasse', 'Platz', 'Ring', 'Straße', 'Weg', + ) + street_suffixes_short = ( + 'gasse', 'platz', 'ring', 'straße', 'str.', 'weg', + ) + + # https://en.wikipedia.org/wiki/List_of_postal_codes_in_Austria + postcode_formats = ( + '1###', '2###', '3###', '4###', '5###', '6###', '7###', '8###', '9###', + ) + + # https://en.wikipedia.org/wiki/List_of_cities_and_towns_in_Austria + cities = ( + 'Allentsteig', 'Altheim', 'Althofen', 'Amstetten', 'Ansfelden', 'Attnang-Puchheim', + 'Bad Aussee', 'Bad Hall', 'Bad Ischl', 'Bad Leonfelden', 'Bad Radkersburg', + 'Bad Sankt Leonhard im Lavanttal', 'Bad Vöslau', 'Baden', 'Bärnbach', 'Berndorf', + 'Bischofshofen', 'Bleiburg', 'Bludenz', 'Braunau am Inn', 'Bregenz', + 'Bruck an der Leitha', 'Bruck an der Mur', 'Deutsch-Wagram', 'Deutschlandsberg', + 'Dornbirn', 'Drosendorf-Zissersdorf 1', 'Dürnstein', 'Ebenfurth', 'Ebreichsdorf', + 'Eferding', 'Eggenburg', 'Eisenerz', 'Eisenstadt', 'Enns', 'Fehring', 'Feldbach', + 'Feldkirch', 'Feldkirchen', 'Ferlach', 'Fischamend', 'Frauenkirchen', 'Freistadt', + 'Friedberg', 'Friesach', 'Frohnleiten', 'Fürstenfeld', 'Gallneukirchen', 'Gänserndorf', + 'Geras', 'Gerasdorf bei Wien', 'Gföhl', 'Gleisdorf', 'Gloggnitz', 'Gmünd', + 'Gmünd in Kärnten', 'Gmunden', 'Graz', 'Grein', 'Grieskirchen', 'Groß-Enzersdorf', + 'Groß-Gerungs', 'Groß-Siegharts', 'Güssing', 'Haag', 'Hainburg an der Donau', 'Hainfeld', + 'Hall in Tirol', 'Hallein', 'Hardegg', 'Hartberg', 'Heidenreichstein', 'Herzogenburg', + 'Imst', 'Innsbruck', 'Jennersdorf', 'Judenburg', 'Kapfenberg', 'Kindberg', 'Klagenfurt', + 'Klosterneuburg', 'Knittelfeld', 'Köflach', 'Korneuburg', 'Krems an der Donau', 'Kufstein', + 'Laa an der Thaya', 'Laakirchen', 'Landeck', 'Langenlois', 'Leibnitz', 'Leoben', 'Lienz', + 'Liezen', 'Lilienfeld', 'Linz', 'Litschau', 'Maissau', 'Mank', 'Mannersdorf am Leithagebirge', + 'Marchegg', 'Marchtrenk', 'Mariazell', 'Mattersburg', 'Mattighofen', 'Mautern an der Donau', + 'Melk', 'Mistelbach an der Zaya', 'Mödling', 'Murau', 'Mureck', 'Mürzzuschlag', 'Neulengbach', + 'Neumarkt am Wallersee', 'Neunkirchen', 'Neusiedl am See', 'Oberndorf bei Salzburg', + 'Oberpullendorf', 'Oberwart', 'Oberwälz', 'Perg', 'Peuerbach', 'Pinkafeld', 'Pöchlarn', + 'Poysdorf', 'Pregarten', 'Pulkau', 'Purbach am Neusiedler See', 'Purkersdorf', + 'Raabs an der Thaya', 'Radenthein', 'Radstadt', 'Rattenberg', 'Retz', 'Ried im Innkreis', + 'Rohrbach in Oberösterreich', 'Rottenmann', 'Rust', 'Saalfelden am Steinernen Meer', + 'Salzburg', 'Sankt Andrä im Lavanttal', 'Sankt Johann im Pongau', 'Sankt Pölten', + 'Sankt Valentin', 'Sankt Veit an der Glan', 'Schärding', 'Scheibbs', 'Schladming', + 'Schrattenthal', 'Schrems', 'Schwanenstadt', 'Schwaz', 'Schwechat', 'Spittal an der Drau', + 'Stadtschlaining', 'Steyr', 'Steyregg', 'Stockerau', 'Straßburg', 'Ternitz', 'Traiskirchen', + 'Traismauer', 'Traun', 'Trieben', 'Trofaiach', 'Tulln an der Donau', 'Villach', 'Vils', + 'Vöcklabruck', 'Voitsberg', 'Völkermarkt', 'Waidhofen an der Thaya', 'Waidhofen an der Ybbs', + 'Weitra', 'Weiz', 'Wels', 'Wien', 'Wiener Neustadt', 'Wieselburg', 'Wilhelmsburg', 'Wolfsberg', + 'Wolkersdorf', 'Wörgl', 'Ybbs an der Donau', 'Zell am See', 'Zeltweg', 'Zistersdorf', 'Zwettl', + ) + + # https://en.wikipedia.org/wiki/States_of_Austria + states = ( + 'Wien', 'Steiermark', 'Burgenland', 'Tirol', 'Niederösterreich', + 'Oberösterreich', 'Salzburg', 'Kärnten', 'Vorarlberg', + ) + + def street_suffix_short(self): + return self.random_element(self.street_suffixes_short) + + def street_suffix_long(self): + return self.random_element(self.street_suffixes_long) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) + + def city_with_postcode(self): + pattern = self.random_element(self.city_with_postcode_formats) + return self.generator.parse(pattern) diff --git a/testbed/joke2k__faker/faker/providers/address/de_DE/__init__.py b/testbed/joke2k__faker/faker/providers/address/de_DE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f70d5638a21d8d8a7a7c39e0bb58ebc35f92aca5 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/de_DE/__init__.py @@ -0,0 +1,130 @@ +from ..de import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + city_with_postcode_formats = ('{{postcode}} {{city}}', ) + + street_name_formats = ( + '{{first_name}}-{{last_name}}-{{street_suffix_long}}', + '{{last_name}}{{street_suffix_short}}', + ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) + + building_number_formats = ('###', '##', '#', '#/#') + + street_suffixes_long = ( + 'Gasse', 'Platz', 'Ring', 'Straße', 'Weg', 'Allee', + ) + street_suffixes_short = ( + 'gasse', 'platz', 'ring', 'straße', 'str.', 'weg', 'allee', + ) + + postcode_formats = ('#####', ) + + cities = ( + 'Aachen', 'Ahaus', 'Altentreptow', 'Altötting', 'Amberg', 'Angermünde', + 'Anklam', 'Ansbach', 'Apolda', 'Arnstadt', 'Artern', 'Aschaffenburg', + 'Aue', 'Auerbach', 'Augsburg', 'Aurich', 'Backnang', 'Bad Brückenau', + 'Bad Freienwalde', 'Bad Kissingen', 'Bad Kreuznach', 'Bad Langensalza', + 'Bad Liebenwerda', 'Bad Mergentheim', 'Badalzungen', 'Badibling', + 'Badoberan', 'Bamberg', 'Bautzen', 'Bayreuth', 'Beeskow', 'Beilngries', + 'Belzig', 'Berchtesgaden', 'Bergzabern', 'Berlin', 'Bernburg', + 'Bersenbrück', 'Biedenkopf', 'Bischofswerda', 'Bitterfeld', 'Bogen', + 'Borken', 'Borna', 'Brand', 'Brandenburg', 'Bremen', 'Bremervörde', + 'Brilon', 'Bruchsal', 'Burg', 'Burgdorf', 'Burglengenfeld', + 'Böblingen', 'Büsingenm Hochrhein', 'Bützow', 'Calau', 'Calw', 'Celle', + 'Chemnitz', 'Cloppenburg', 'Coburg', 'Cottbus', 'Crailsheim', + 'Cuxhaven', 'Dachau', 'Darmstadt', 'Deggendorf', 'Delitzsch', 'Demmin', + 'Dessau', 'Dieburg', 'Diepholz', 'Dinkelsbühl', 'Dinslaken', + 'Donaueschingen', 'Dresden', 'Duderstadt', 'Döbeln', 'Düren', + 'Ebermannstadt', 'Ebern', 'Ebersberg', 'Eberswalde', 'Eckernförde', + 'Eggenfelden', 'Eichstätt', 'Eichstätt', 'Eilenburg', 'Einbeck', + 'Eisenach', 'Eisenberg', 'Eisenhüttenstadt', 'Eisleben', 'Emmendingen', + 'Erbisdorf', 'Erding', 'Erfurt', 'Erkelenz', 'Euskirchen', 'Eutin', + 'Fallingbostel', 'Feuchtwangen', 'Finsterwalde', 'Flöha', 'Forchheim', + 'Forst', 'Freising', 'Freital', 'Freudenstadt', 'Fulda', + 'Fürstenfeldbruck', 'Fürstenwalde', 'Füssen', 'Gadebusch', + 'Gardelegen', 'Garmisch-Partenkirchen', 'Geithain', 'Geldern', + 'Gelnhausen', 'Genthin', 'Gera', 'Germersheim', 'Gerolzhofen', + 'Gießen', 'Gifhorn', 'Goslar', 'Gotha', 'Grafenau', 'Gransee', + 'Greifswald', 'Greiz', 'Grevenbroich', 'Grevesmühlen', + 'Griesbach Rottal', 'Grimma', 'Grimmen', 'Groß-Gerau', 'Großenhain', + 'Gräfenhainichen', 'Guben', 'Gunzenhausen', 'Göppingen', 'Görlitz', + 'Göttingen', 'Günzburg', 'Güstrow', 'Gütersloh', 'Hagenow', + 'Hainichen', 'Halberstadt', 'Haldensleben', 'Hamburg', 'Hammelburg', + 'Hannover', 'Hannoversch Münden', 'Hansestadttralsund', 'Havelberg', + 'Hechingen', 'Heiligenstadt', 'Heinsberg', 'Helmstedt', 'Herford', + 'Hersbruck', 'Herzberg', 'Hettstedt', 'Hildburghausen', 'Hildesheim', + 'Hofgeismar', 'Hohenmölsen', 'Hohenstein-Ernstthal', 'Holzminden', + 'Hoyerswerda', 'Husum', 'Höxter', 'Hünfeld', 'Illertissen', 'Ilmenau', + 'Ingolstadt', 'Iserlohn', 'Jena', 'Jessen', 'Jülich', 'Jüterbog', + 'Kaiserslautern', 'Kamenz', 'Karlsruhe', 'Kassel', 'Kehl', 'Kelheim', + 'Kemnath', 'Kitzingen', 'Kleve', 'Klötze', 'Koblenz', 'Konstanz', + 'Kronach', 'Kulmbach', 'Kusel', 'Kyritz', 'Königs Wusterhausen', + 'Kötzting', 'Leipziger Land', 'Lemgo', 'Lichtenfels', 'Lippstadt', + 'Lobenstein', 'Luckau', 'Luckenwalde', 'Ludwigsburg', 'Ludwigslust', + 'Lörrach', 'Lübben', 'Lübeck', 'Lübz', 'Lüdenscheid', 'Lüdinghausen', + 'Lüneburg', 'Magdeburg', 'Main-Höchst', 'Mainburg', 'Malchin', + 'Mallersdorf', 'Marienberg', 'Marktheidenfeld', 'Mayen', 'Meiningen', + 'Meißen', 'Melle', 'Mellrichstadt', 'Melsungen', 'Meppen', 'Merseburg', + 'Mettmann', 'Miesbach', 'Miltenberg', 'Mittweida', 'Moers', 'Monschau', + 'Mühldorfm Inn', 'Mühlhausen', 'München', 'Nabburg', 'Naila', 'Nauen', + 'Neu-Ulm', 'Neubrandenburg', 'Neunburg vorm Wald', 'Neuruppin', + 'Neuss', 'Neustadtm Rübenberge', 'Neustadtner Waldnaab', 'Neustrelitz', + 'Niesky', 'Norden', 'Nordhausen', 'Northeim', 'Nördlingen', + 'Nürtingen', 'Oberviechtach', 'Ochsenfurt', 'Olpe', 'Oranienburg', + 'Oschatz', 'Osterburg', 'Osterodem Harz', 'Paderborn', 'Parchim', + 'Parsberg', 'Pasewalk', 'Passau', 'Pegnitz', 'Peine', 'Perleberg', + 'Pfaffenhofenner Ilm', 'Pinneberg', 'Pirmasens', 'Plauen', 'Potsdam', + 'Prenzlau', 'Pritzwalk', 'Pößneck', 'Quedlinburg', 'Querfurt', + 'Rastatt', 'Rathenow', 'Ravensburg', 'Recklinghausen', 'Regen', + 'Regensburg', 'Rehau', 'Reutlingen', 'Ribnitz-Damgarten', 'Riesa', + 'Rochlitz', 'Rockenhausen', 'Roding', 'Rosenheim', 'Rostock', 'Roth', + 'Rothenburg oberauber', 'Rottweil', 'Rudolstadt', 'Saarbrücken', + 'Saarlouis', 'Sangerhausen', 'Sankt Goar', 'Sankt Goarshausen', + 'Saulgau', 'Scheinfeld', 'Schleiz', 'Schlüchtern', 'Schmölln', + 'Schongau', 'Schrobenhausen', 'Schwabmünchen', 'Schwandorf', + 'Schwarzenberg', 'Schweinfurt', 'Schwerin', 'Schwäbisch Gmünd', + 'Schwäbisch Hall', 'Sebnitz', 'Seelow', 'Senftenberg', 'Siegen', + 'Sigmaringen', 'Soest', 'Soltau', 'Soltau', 'Sondershausen', + 'Sonneberg', 'Spremberg', 'Stade', 'Stade', 'Stadtroda', + 'Stadtsteinach', 'Staffelstein', 'Starnberg', 'Staßfurt', 'Steinfurt', + 'Stendal', 'Sternberg', 'Stollberg', 'Strasburg', 'Strausberg', + 'Stuttgart', 'Suhl', 'Sulzbach-Rosenberg', 'Säckingen', 'Sömmerda', + 'Tecklenburg', 'Teterow', 'Tirschenreuth', 'Torgau', 'Tuttlingen', + 'Tübingen', 'Ueckermünde', 'Uelzen', 'Uffenheim', 'Vechta', + 'Viechtach', 'Viersen', 'Vilsbiburg', 'Vohenstrauß', 'Waldmünchen', + 'Wanzleben', 'Waren', 'Warendorf', 'Weimar', 'Weißenfels', + 'Weißwasser', 'Werdau', 'Wernigerode', 'Wertingen', 'Wesel', 'Wetzlar', + 'Wiedenbrück', 'Wismar', 'Wittenberg', 'Wittmund', 'Wittstock', + 'Witzenhausen', 'Wolfach', 'Wolfenbüttel', 'Wolfratshausen', 'Wolgast', + 'Wolmirstedt', 'Worbis', 'Wunsiedel', 'Wurzen', 'Zerbst', 'Zeulenroda', + 'Zossen', 'Zschopau', + ) + + states = ( + 'Baden-Württemberg', 'Bayern', 'Berlin', 'Brandenburg', 'Bremen', + 'Hamburg', 'Hessen', 'Mecklenburg-Vorpommern', 'Niedersachsen', + 'Nordrhein-Westfalen', 'Rheinland-Pfalz', 'Saarland', 'Sachsen', + 'Sachsen-Anhalt', 'Schleswig-Holstein', 'Thüringen', + ) + + def street_suffix_short(self): + return self.random_element(self.street_suffixes_short) + + def street_suffix_long(self): + return self.random_element(self.street_suffixes_long) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) + + def city_with_postcode(self): + pattern = self.random_element(self.city_with_postcode_formats) + return self.generator.parse(pattern) diff --git a/testbed/joke2k__faker/faker/providers/address/el_GR/__init__.py b/testbed/joke2k__faker/faker/providers/address/el_GR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87f5d738cffc3fd1863dba24ce9909d19ab8bec3 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/el_GR/__init__.py @@ -0,0 +1,4718 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + building_number_formats = ( + '###', + '##', + '##', + '##', + '#', + '#', + '##-##', + '###-###', + ) + + street_prefixes_short = ( + 'Πλ.', + 'Πάρ.', + 'Λεωφ.', + ) + + street_prefixes_long = ( + 'Πλατεία', + 'Πάροδος', + 'Λεωφόρος', + ) + + street_name_formats = ( + '{{street_prefix}} {{street}}', + '{{street}}', + '{{street}}', + '{{street}}', + '{{last_name_female}}', + ) + + street_address_formats = ( + '{{street_name}} {{building_number}}', + ) + + postcode_formats = ( + '### ##', + '#####', + '#####', + 'ΤΚ ### ##', + 'ΤΚ #####', + ) + + address_formats = ( + "{{street_address}},\n{{postcode}} {{city}}", + ) + + line_address_formats = ( + "{{street_address}}, {{postcode}} {{city}}", + ) + + def line_address(self): + pattern = self.random_element(self.line_address_formats) + return self.generator.parse(pattern) + + def street_prefix(self): + return self.random_element( + self.street_prefixes_short + + self.street_prefixes_long) + + def street_prefix_short(self): + return self.random_element(self.street_prefixes_short) + + def street_prefix_long(self): + return self.random_element(self.street_prefixes_long) + + def street(self): + return self.random_element(self.localities) + + def city(self): + return self.random_element(self.cities) + + def region(self): + return self.random_element(self.regions) + + # Ονόματα πρωτευουσών νομών + cities = ( + 'Άμφισσα', + 'Άρτα', + 'Έδεσσα', + 'Αγ. Νικόλαος', + 'Αθήνα', + 'Αλεξανδρούπολη', + 'Αργοστόλι', + 'Βέροια', + 'Βόλος', + 'Γρεβενά', + 'Δράμα', + 'Ερμούπολη', + 'Ζάκυνθος', + 'Ηγουμενίτσα', + 'Ηράκλειο', + 'Θεσσαλονίκη', + 'Ιωάννινα', + 'Κέρκυρα', + 'Καβάλα', + 'Καλαμάτα', + 'Καρδίτσα', + 'Καρπενήσι', + 'Καστοριά', + 'Κατερίνη', + 'Κιλκίς', + 'Κοζάνη', + 'Κομοτηνή', + 'Κόρινθος', + 'Λάρισα', + 'Λαμία', + 'Λευκάδα', + 'Λιβαδιά', + 'Μεσολόγγι', + 'Μυτιλήνη', + 'Ναύπλιο', + 'Ξάνθη', + 'Πάτρα', + 'Πολύγυρος', + 'Πρέβεζα', + 'Πύργος', + 'Ρέθυμνο', + 'Ρόδος', + 'Σάμος', + 'Σέρρες', + 'Σπάρτη', + 'Τρίκαλα', + 'Τρίπολη', + 'Φλώρινα', + 'Χίος', + 'Χαλκίδα', + 'Χανιά', + ) + + # Ονόματα νομών + regions = ( + 'Αιτωλία & Ακαρνανία', 'Αργολίδα', 'Αρκαδία', 'Άρτα', 'Αττική', 'Αχαΐα', + 'Βοιωτία', 'Γρεβενά', 'Δράμα', 'Δωδεκάνησσος', 'Έβρος', 'Ευρυτανία', + 'Εύβοια', 'Ζάκυνθος', 'Ηλεία', 'Ημαθία', 'Ηράκλειο', 'Θεσπρωτία', + 'Θεσσαλονίκη', 'Ιωάννινα', 'Κέρκυρα', 'Καβάλα', 'Καρδίτσα', 'Καστοριά', + 'Κεφαλληνία', 'Κιλκίς', 'Κοζάνη', 'Κορινθία', 'Κυκλάδες', 'Λάρισσα', + 'Λέσβος', 'Λακωνία', 'Λασσίθι', 'Λευκάδα', 'Μαγνησία', 'Μεσσηνία', + 'Ξάνθη', 'Πέλλα', 'Πιερία', 'Πρέβεζα', 'Ρέθυμνο', 'Ροδόπη', 'Σάμος', + 'Σέρρες', 'Τρίκαλα', 'Φθιώτιδα', 'Φλώρινα', 'Φωκίδα', 'Χίος', + 'Χαλκιδική', 'Χανιά', + ) + + # Ονόματα χωρών + countries = ( + 'Άγιος Βαρθολομαίος', 'Άγιος Βικέντιος και Γρεναδίνες', 'Άγιος Μαρίνος', + 'Άγιος Μαρτίνος', 'Άγιος Μαρτίνος (Γαλλικό Κομμάτι)', 'Άγιος Πέτρος και Μικελόν', + 'Άγιος Χριστόφορος και Νέβις', 'Αίγυπτος', 'Αγία Ελένη, Ασενσιόν και Τριστάν ντα Κούνια', + 'Αγία Λουκία', 'Αζερμπαϊτζάν', 'Αιθιοπία', 'Ακτή Ελεφαντοστού', 'Αλβανία', + 'Αλγερία', 'Αμερικανικές Παρθένοι Νήσοι', 'Αμερικανική Σαμόα', 'Ανατολικό Τιμόρ', + 'Ανγκουίλα', 'Ανγκόλα', 'Ανδόρα', 'Αντίγκουα και Μπαρμπούντα', 'Ανταρκτική', + 'Απομακρυσμένες Νησίδες των Ηνωμένων Πολιτειών', 'Αραβική Δημοκρατία της Λιβύης', + 'Αργεντινή', 'Αρμενία', 'Αρούμπα', 'Αυστρία', 'Αυστραλία', 'Αφγανιστάν', 'Αϊτή', + 'Βέλγιο', 'Βανουάτου', 'Βατικανό', 'Βενεζουέλα', 'Βερμούδες', 'Βιετνάμ', 'Βολιβία', + 'Βοσνία-Ερζεγοβίνη', 'Βουλγαρία', 'Βραζιλία', 'Βρετανικές Παρθένοι Νήσοι', + 'Βρετανικό Έδαφος Ινδικού Ωκεανού', 'Βόρειες Μαριάνες Νήσοι', 'Γαλλία', + 'Γαλλικά Νότια και Ανταρκτικά Εδάφη', 'Γαλλική Γουιάνα', 'Γαλλική Πολυνησία', + 'Γερμανία', 'Γεωργία', 'Γιβραλτάρ', 'Γκάμπια', 'Γκάνα', 'Γκέρνσεϊ', 'Γκαμπόν', + 'Γκουάμ', 'Γουάλις και Φουτούνα', 'Γουαδελούπη', 'Γουατεμάλα', 'Γουιάνα', + 'Γουινέα', 'Γουινέα-Μπισσάου', 'Γρενάδα', 'Γροιλανδία', 'Δανία', 'Δημοκρατία της Κορέας', + 'Δομινίκα', 'Δομινικανή Δημοκρατία', 'Δυτική Σαχάρα', 'Ελ Σαλβαδόρ', 'Ελβετία', + 'Ελλάδα', 'Ερυθραία', 'Εσθονία', 'Ζάμπια', 'Ζιμπάμπουε', 'Ηνωμένα Αραβικά Εμιράτα', + 'Ηνωμένες Πολιτείες Αμερικής', 'Ηνωμένο Βασίλειο', 'Ιαπωνία', 'Ινδία', 'Ινδονησία', + 'Ιορδανία', 'Ιράκ', 'Ιράν', 'Ιρλανδία', 'Ισημερινή Γουινέα', 'Ισημερινός', 'Ισλανδία', + 'Ισπανία', 'Ισραήλ', 'Ιταλία', 'Κένυα', 'Κίνα', 'Καζακστάν', 'Καμερούν', 'Καμπότζη', + 'Καναδάς', 'Κατάρ', 'Κεντροαφρικανική Δημοκρατία', 'Κιργιστάν', 'Κιριμπάτι', + 'Κολομβία', 'Κομόρες', 'Κονγκό', 'Κουβέιτ', 'Κουρακάο', 'Κούβα', 'Κροατία', + 'Κόστα Ρίκα', 'Κύπρος', 'Λίβανος', 'Λαοκρατική Δημοκρατία της Κορέας', + 'Λαϊκή Δημοκρατία του Κονγκό', 'Λαϊκή Δημοκρατία του Λάος', 'Λεσότο', + 'Λετονία', 'Λευκορωσία', 'Λιβερία', 'Λιθουανία', 'Λιχτενστάϊν', 'Λουξεμβούργο', + 'Μάλι', 'Μάλτα', 'Μαγιότ', 'Μαδαγασκάρη', 'Μακάο', 'Μαλάουι', 'Μαλαισία', + 'Μαλδίβες', 'Μαρτινίκη', 'Μαρόκο', 'Μαυρίκιος', 'Μαυριτανία', 'Μαυροβούνιο', + 'Μεξικό', 'Μιανμάρ', 'Μικρονησία', 'Μογγολία', 'Μοζαμβίκη', 'Μολδαβία', + 'Μονακό', 'Μονσεράτ', 'Μπαγκλαντές', 'Μπαρμπάντος', 'Μπαχάμες', 'Μπαχρέιν', + 'Μπελίζ', 'Μπενίν', 'Μποτσουάνα', 'Μπουρκίνα Φάσο', 'Μπουρουντί', 'Μπουτάν', + 'Μπρουνέι', 'Νέα Ζηλανδία', 'Νέα Καληδονία', 'Νήσοι Κουκ', 'Νήσοι Κόκος', + 'Νήσοι Μάρσαλ', 'Νήσοι Πίτκαιρν', 'Νήσοι Σολομώντα', 'Νήσοι Φώκλαντ', + 'Νήσοι Χερντ και Μακντόναλντ', 'Νήσοι Ώλαντ', 'Νήσος Μαν', 'Νήσος Μπουβέ', + 'Νήσος των Χριστουγέννων', 'Νίγηρας', 'Ναμίμπια', 'Ναουρού', 'Νεπάλ', + 'Νησί Νόρφολκ', 'Νησιά Καϋμάν', 'Νησιά Τερκς και Κάικος', 'Νησιά Φερόες', + 'Νιγηρία', 'Νικαράγουα', 'Νιούε', 'Νορβηγία', 'Νότιος Αφρική', + 'Νότιος Γεωργία και οι Νότιοι Σάντουιτς Νήσοι', 'Ολλανδία', 'Ολλανδικές Αντίλλες', + 'Ομάν', 'Ονδούρα', 'Ουγγαρία', 'Ουγκάντα', 'Ουζμπεκιστάν', 'Ουκρανία', 'Ουρουγουάη', + 'Π.Γ.Δ. Μακεδονίας', 'Πακιστάν', 'Παλάου', 'Παλαιστίνη', 'Παναμάς', + 'Παπούα Νέα Γουινέα', 'Παραγουάη', 'Περού', 'Πολωνία', 'Πορτογαλία', + 'Πουέρτο Ρίκο', 'Πράσινο Ακρωτήρι', 'Ρεϊνιόν', 'Ρουάντα', 'Ρουμανία', + 'Ρωσία', 'Σάο Τομέ και Πρίνσιπε', 'Σαμόα', 'Σαουδική Αραβία', + 'Σβάλμπαρντ και Γιαν Μαγιέν', 'Σενεγάλη', 'Σερβία', 'Σεϋχέλλες', + 'Σιέρα Λεόνε', 'Σιγκαπούρη', 'Σλοβακία', 'Σλοβενία', 'Σομαλία', + 'Σουαζιλάνδη', 'Σουδάν', 'Σουηδία', 'Σουρινάμ', 'Σρι Λάνκα', 'Συρία', + 'Τανζανία', 'Τατζικιστάν', 'Ταϊβάν', 'Ταϊλάνδη', 'Τζέρσεϊ', 'Τζαμάικα', + 'Τζιμπουτί', 'Τοκελάου', 'Τουβαλού', 'Τουρκία', 'Τουρκμενιστάν', + 'Τρινιντάντ και Τομπάγκο', 'Τσαντ', 'Τσεχία', 'Τυνησία', 'Τόγκο', + 'Τόνγκα', 'Υεμένη', 'Φίτζι', 'Φιλιππίνες', 'Φινλανδία', 'Χιλή', 'Χονγκ Κονγκ', + ) + + # Επίσημα τοπικά διαμερίσματα. + # Χρησιμοποιούνται ως ονόματα δρόμων (λόγω ανάγκης για γενική κλίση). + # Η λίστα είναι από το ΥΠ.ΕΣ. (μετά από επεξεργασία και μορφοποίηση) + localities = ( + 'Άγρα', + 'Άγρας', + 'Άδελε', + 'Άκρης', + 'Άλλης Μεριάς', + 'Άλσους', + 'Άμμου', + 'Άμπλιανης', + 'Άνδρου', + 'Άργους', + 'Άργους Ορεστικού', + 'Άρζου', + 'Άρλας', + 'Άρμπουνα', + 'Άρνης', + 'Άσκρης', + 'Άσου', + 'Άσπρου', + 'Άσπρων Σπιτιών', + 'Άσσου', + 'Άστρους', + 'Άτταλης', + 'Άφρας', + 'Έλους', + 'Έμπωνα', + 'Έρφων', + 'Ήπιον', + 'Ήρας', + 'Ίδας', + 'Ίμπρου', + 'Ίσαρη', + 'Αΐμονα', + 'Αβάτου', + 'Αβίας', + 'Αβαρίκου', + 'Αβγαριάς', + 'Αβγού', + 'Αβδέλλας', + 'Αβδήρων', + 'Αβδού', + 'Αβρακόντε', + 'Αβραμιού', + 'Αβραμυλιάς', + 'Αβόρανης', + 'Αβόρου', + 'Αγάπης', + 'Αγία Βαρβάρα', + 'Αγία Κυριακή', + 'Αγία Παρασκευή', + 'Αγίας Άννας', + 'Αγίας Άννης', + 'Αγίας Αναστασίας', + 'Αγίας Βαρβάρας', + 'Αγίας Βλαχέρνης', + 'Αγίας Γαλήνης', + 'Αγίας Ειρήνης', + 'Αγίας Ελένης', + 'Αγίας Ευθυμίας', + 'Αγίας Ευφημίας', + 'Αγίας Θέκλης', + 'Αγίας Κυριακής', + 'Αγίας Μαρίνης', + 'Αγίας Μαύρας', + 'Αγίας Παρασκευής', + 'Αγίας Ρουμέλης', + 'Αγίας Σοφίας', + 'Αγίας Σωτήρας', + 'Αγίου', + 'Αγίου Αδριανού', + 'Αγίου Αθανασίου', + 'Αγίου Ακακίου', + 'Αγίου Ανδρέου', + 'Αγίου Αντωνίου', + 'Αγίου Αρσενίου', + 'Αγίου Αχιλλείου', + 'Αγίου Βαρθολομαίου', + 'Αγίου Βασιλείου', + 'Αγίου Βασιλείου Κυνουρίας', + 'Αγίου Βασιλείου Μαντινείας', + 'Αγίου Βησσαρίου', + 'Αγίου Βλασίου', + 'Αγίου Γερμανού', + 'Αγίου Γεωργίου', + 'Αγίου Γεωργίου Δομοκού', + 'Αγίου Γεωργίου Λαρίσης', + 'Αγίου Γεωργίου Λασιθίου', + 'Αγίου Γεωργίου Νηλείας', + 'Αγίου Γεωργίου Σητείας', + 'Αγίου Γεωργίου Συκούση', + 'Αγίου Γεωργίου Φαρσάλων', + 'Αγίου Γεωργίου Φερών', + 'Αγίου Δημητρίου', + 'Αγίου Δημητρίου Μονεμβασίας', + 'Αγίου Δημητρίου Πηλίου', + 'Αγίου Ευστρατίου', + 'Αγίου Ηλία', + 'Αγίου Ηλία Πηνηίων', + 'Αγίου Ηλία Πύργου', + 'Αγίου Θεοδώρου', + 'Αγίου Θωμά', + 'Αγίου Ισιδώρου', + 'Αγίου Ιωάννη', + 'Αγίου Ιωάννου', + 'Αγίου Ιωάννου Αγίου Βασιλείου', + 'Αγίου Ιωάννου Αμαρίου', + 'Αγίου Ιωάννου Αρχαίας Ηραίας', + 'Αγίου Ιωάννου Επιδαύρου Λιμήρας', + 'Αγίου Ιωάννου Μυλοποτάμου', + 'Αγίου Ιωάννου Ρέντη', + 'Αγίου Κηρύκου', + 'Αγίου Κοσμά', + 'Αγίου Κυρίλλου', + 'Αγίου Κωνσταντίνου', + 'Αγίου Λαυρεντίου', + 'Αγίου Λουκά', + 'Αγίου Μάρκου', + 'Αγίου Ματθαίου', + 'Αγίου Μηνά', + 'Αγίου Νικήτα', + 'Αγίου Νικολάου', + 'Αγίου Νικολάου Βοιών', + 'Αγίου Νικολάου Βονίτσης και Ξηρομέρου', + 'Αγίου Νικολάου Κράλης', + 'Αγίου Νικολάου Μονεμβασίας', + 'Αγίου Νικολάου Σπάτων', + 'Αγίου Ονουφρίου', + 'Αγίου Πέτρου', + 'Αγίου Παντελεήμονα', + 'Αγίου Παύλου', + 'Αγίου Πολυκάρπου', + 'Αγίου Προδρόμου', + 'Αγίου Προκοπίου', + 'Αγίου Σεραφείμ', + 'Αγίου Στεφάνου', + 'Αγίου Σύλλα', + 'Αγίου Σώστου', + 'Αγίου Φλώρου', + 'Αγίου Χαραλάμπους', + 'Αγίου Χριστοφόρου', + 'Αγίων Αναργύρων', + 'Αγίων Αποστόλων', + 'Αγίων Δέκα', + 'Αγίων Δούλων', + 'Αγίων Θεοδώρων', + 'Αγίων Πάντων', + 'Αγίων Παρασκιών', + 'Αγαθονησίου', + 'Αγαθουπόλεως', + 'Αγαλά', + 'Αγαλιανής', + 'Αγαλιανού', + 'Αγγίστης', + 'Αγγελιανών', + 'Αγγελοκάστρου', + 'Αγγελοχωρίου', + 'Αγγελώνας', + 'Αγδινών', + 'Αγιάς', + 'Αγιάσου', + 'Αγιοβλασιτίκων', + 'Αγιονερίου', + 'Αγιονορίου', + 'Αγιοπηγής', + 'Αγιοφύλλου', + 'Αγιοχωρίου', + 'Αγιοχώριον', + 'Αγιωργιτίκων', + 'Αγκίστρου', + 'Αγκαθιάς', + 'Αγκαιριάς', + 'Αγκαρυώνων', + 'Αγκιστρίου', + 'Αγκουσελιανών', + 'Αγνάντης', + 'Αγνάντων', + 'Αγναντερής', + 'Αγναντερού', + 'Αγναντιάς', + 'Αγοράς', + 'Αγράφων', + 'Αγρίλου', + 'Αγραμπέλων', + 'Αγραπιδεών', + 'Αγραπιδιάς', + 'Αγραπιδοχωρίου', + 'Αγραφών', + 'Αγρελιάς', + 'Αγριάνων', + 'Αγριάς', + 'Αγριακόνας', + 'Αγριανής', + 'Αγριδίου', + 'Αγριλιάς Μεσσήνης', + 'Αγριλιάς Τριφυλίας', + 'Αγριλοβούνου', + 'Αγρινίου', + 'Αγριοβοτάνου', + 'Αγροσυκέας', + 'Αγρού', + 'Αγχιάλου', + 'Αγόριανης', + 'Αδάμ', + 'Αδένδρου', + 'Αδαμίου', + 'Αδελφικού', + 'Αδριανής', + 'Αερινού', + 'Αετολόφου', + 'Αετομηλίτσης', + 'Αετοπέτρας', + 'Αετοπέτρας Δωδώνης', + 'Αετοπέτρας Κονίτσης', + 'Αετορράχη', + 'Αετορράχης', + 'Αετού', + 'Αζώρου', + 'Αηδονίων', + 'Αηδονιάς', + 'Αηδονοχωρίου', + 'Αθαμανίας', + 'Αθαμανίου', + 'Αθανίου', + 'Αθανασίου Διάκου', + 'Αθηναίου', + 'Αθηναίων', + 'Αθικίων', + 'Αθύρων', + 'Αιανής', + 'Αιαντείου', + 'Αιγάλεω', + 'Αιγάνης', + 'Αιγίνης', + 'Αιγίου', + 'Αιγείρας', + 'Αιγείρου', + 'Αιγιάλης', + 'Αιγινίου', + 'Αιγιών', + 'Αιγών', + 'Αιθαίας', + 'Αισύμης', + 'Αιτωλικού', + 'Ακοντίου', + 'Ακουμίων', + 'Ακράτας', + 'Ακρίτα', + 'Ακρίτας', + 'Ακρίων', + 'Ακραιφνίου', + 'Ακρασίου', + 'Ακρινής', + 'Ακριτοχωρίου', + 'Ακρολίμνης', + 'Ακροποτάμου', + 'Ακροποταμιάς', + 'Ακρωτηρίου', + 'Ακρών', + 'Ακταίου', + 'Ακόβου', + 'Αλέας', + 'Αλίκων', + 'Αλίμου', + 'Αλαγνίου', + 'Αλαγονίας', + 'Αλαλκομενών', + 'Αλατόπετρας', + 'Αλειμματάδων', + 'Αλεξάνδρου', + 'Αλεξανδρείας', + 'Αλεξανδρουπόλεως', + 'Αλεποχωρίου', + 'Αλεποχωρίου Μπότσαρη', + 'Αλεπούς', + 'Αλεστίων', + 'Αλεσταίνης', + 'Αλευράδας', + 'Αλευρούς', + 'Αληθινής', + 'Αλιάρτου', + 'Αλιβερίου', + 'Αλικάμπου', + 'Αλικανά', + 'Αλικαρνασσού', + 'Αλικιανού', + 'Αλισσού', + 'Αλιστράτης', + 'Αλιφείρας', + 'Αλμυροποτάμου', + 'Αλμυρού', + 'Αλοίδων', + 'Αλοννήσου', + 'Αλποχωρίου', + 'Αλτομιρών', + 'Αλυφαντών', + 'Αλφάς', + 'Αλφειούσης', + 'Αλωνίων', + 'Αλωνακίων', + 'Αλωνισταίνης', + 'Αλώνων', + 'Αλώρου', + 'Αμάδων', + 'Αμαλιαπόλεως', + 'Αμαξάδων', + 'Αμαράντου', + 'Αμαράντων', + 'Αμαρίου', + 'Αμαριανού', + 'Αμαρουσίου', + 'Αμαρύνθου', + 'Αμβρακίας', + 'Αμβροσίας', + 'Αμελάντων', + 'Αμιρά', + 'Αμισιανών', + 'Αμμολόχου', + 'Αμμοτόπου', + 'Αμμουδάρας', + 'Αμμουδιάς', + 'Αμμουλιανής', + 'Αμμοχωρίου', + 'Αμνάτου', + 'Αμορίου', + 'Αμοργιανών', + 'Αμοργού', + 'Αμουρίου', + 'Αμπέλου', + 'Αμπέλων', + 'Αμπελίων', + 'Αμπελακίου', + 'Αμπελακίων', + 'Αμπελακιωτίσσης', + 'Αμπελείας', + 'Αμπελειών', + 'Αμπελιάς', + 'Αμπελικού', + 'Αμπελιώνας', + 'Αμπελοκάμπου', + 'Αμπελοκήπων', + 'Αμπελοφύτου', + 'Αμπελοχωρίου', + 'Αμπελούζου', + 'Αμυγδαλέας', + 'Αμυγδαλής', + 'Αμυγδαλεών', + 'Αμυγδαλιάς', + 'Αμυγδαλοκεφαλίου', + 'Αμυκλών', + 'Αμυνταίου', + 'Αμφία', + 'Αμφίσσης', + 'Αμφείας', + 'Αμφιθέας', + 'Αμφικλείας', + 'Αμφιλοχίας', + 'Αμφιπόλεως', + 'Ανάβατου', + 'Ανάβρας', + 'Ανάφης', + 'Ανέζης', + 'Αναβρυτής', + 'Αναβρυτού', + 'Αναβρυτών', + 'Αναβύσσου', + 'Αναγεννήσεως', + 'Ανακασιάς', + 'Αναλήψεως', + 'Αναργύρων', + 'Αναρράχης', + 'Αναστάσεως', + 'Αναστασίας', + 'Ανατολής', + 'Ανατολικής', + 'Ανατολικής Φραγκίστας', + 'Ανατολικού', + 'Αναφωνητρίας', + 'Ανδανίας', + 'Ανδρίτσης', + 'Ανδραβίδας', + 'Ανδριτσαίνης', + 'Ανδρούσης', + 'Ανδρωνιάνων', + 'Ανεμοδουρίου', + 'Ανεμομύλου', + 'Ανεμορράχης', + 'Ανεμοχωρίου', + 'Ανεμότιας', + 'Ανηλίου', + 'Ανθήλης', + 'Ανθής', + 'Ανθείας', + 'Ανθηρού', + 'Ανθοτόπου', + 'Ανθοφύτου', + 'Ανθοχωρίου', + 'Ανθοχωρίου Δωδώνης', + 'Ανθοχωρίου Μετσόβου', + 'Ανθοχώριον', + 'Ανθούσης', + 'Ανθρακίτη', + 'Ανιάδας', + 'Ανοίξεως', + 'Ανοιξιάτικου', + 'Αντίσσης', + 'Ανταρτικού', + 'Αντιγονείας', + 'Αντικαλάμου', + 'Αντικυθήρων', + 'Αντικύρας', + 'Αντιμαχείας', + 'Αντιπάρου', + 'Αντιπάτων Ερίσου', + 'Αντιπερνών', + 'Αντιρρίου', + 'Αντισκαρίου', + 'Αντιφιλίππων', + 'Αντρωνίου', + 'Ανυφίου', + 'Ανωγής', + 'Ανωγείου', + 'Ανωγείων', + 'Ανωπόλεως', + 'Ανύδρου', + 'Ανώσκελης', + 'Αξιοκάστρου', + 'Αξιουπόλεως', + 'Αξιοχωρίου', + 'Αξού', + 'Απεράθου', + 'Απερίου', + 'Απεσωκαρίου', + 'Απιδέα', + 'Απιδέας', + 'Απιδίων', + 'Απλαδιανών', + 'Αποδούλου', + 'Αποικίων', + 'Απολακκιάς', + 'Απολλωνίας', + 'Απολπαίνης', + 'Αποστολιά', + 'Αποστόλων', + 'Απροβάτου', + 'Απτέρων', + 'Απόλλωνα', + 'Αράξου', + 'Αράχου', + 'Αρήνης', + 'Αρίας', + 'Αρίσβη', + 'Αρίσβης', + 'Αρίστης', + 'Αραβησσού', + 'Αραχαμιτών', + 'Αραχναίου', + 'Αραχοβιτίκων', + 'Αραχόβης', + 'Αρβανίτη', + 'Αργέννου', + 'Αργίλου', + 'Αργαλαστής', + 'Αργασίου', + 'Αργιθέας', + 'Αργινίων', + 'Αργολικού', + 'Αργοστολίου', + 'Αργυράδων', + 'Αργυράς', + 'Αργυρίου', + 'Αργυρίων', + 'Αργυροπουλείου', + 'Αργυροτόπου', + 'Αργυρουπόλεως', + 'Αργυροχωρίου', + 'Αργυρού', + 'Αργυρού Πηγαδίου', + 'Αργυρούπολης', + 'Αργυρούπολις', + 'Αρδάκτου', + 'Αρδάσσης', + 'Αρδαμερίου', + 'Αρδανίου', + 'Αρδείας', + 'Αρδόσεως', + 'Αρεθούσης', + 'Αρεοπόλεως', + 'Αρετής', + 'Αριδαίας', + 'Αριοχωρίου', + 'Αριστοδημείου', + 'Αριστομένους', + 'Αρκάσας', + 'Αρκίτσας', + 'Αρκαδάδων', + 'Αρκαδικού', + 'Αρκαλοχωρίου', + 'Αρκεσίνης', + 'Αρκοχωρίου', + 'Αρμάτων', + 'Αρμένων', + 'Αρματολικού', + 'Αρμενάδων', + 'Αρμενίου', + 'Αρμενιών', + 'Αρμενοχωρίου', + 'Αρμολίων', + 'Αρνά', + 'Αρνίθας', + 'Αρνίσσης', + 'Αρναίας', + 'Αροανίας', + 'Αρραβωνίτσης', + 'Αρριανά', + 'Αρσενίου', + 'Αρσινόης', + 'Αρτάκης', + 'Αρτέμιδας', + 'Αρταίων', + 'Αρτεμισίας', + 'Αρτεμισίου', + 'Αρτεσιανού', + 'Αρτικίου', + 'Αρτοπούλας', + 'Αρτοτίνας', + 'Αρφαρών', + 'Αρχαίας Ήλιδας', + 'Αρχαίας Ελεύθερνας', + 'Αρχαίας Επιδαύρου', + 'Αρχαίας Κορίνθου', + 'Αρχαίας Μεσσήνης', + 'Αρχαίας Νεμέας', + 'Αρχαίας Ολυμπίας', + 'Αρχαίας Πίσας', + 'Αρχαίας Φενεού', + 'Αρχαίων Κλεωνών', + 'Αρχαγγέλου', + 'Αρχανίου', + 'Αρχανών', + 'Αρχιλόχου', + 'Αρχιπόλεως', + 'Αρχοντικά', + 'Αρχοντικής', + 'Αρχοντικού', + 'Αρχοντοχωρίου', + 'Αρωγή', + 'Αρωνά', + 'Αρωνίου', + 'Αρωνιαδίκων', + 'Ασέας', + 'Ασή Γωνιάς', + 'Ασίνης', + 'Ασβεστάδων', + 'Ασβεστίου', + 'Ασβεστοπέτρας', + 'Ασβεστοχωρίου', + 'Ασημένιου', + 'Ασημίου', + 'Ασημοχωρίου', + 'Ασιτών', + 'Ασκληπιείου', + 'Ασκού', + 'Ασκύφου', + 'Ασκών', + 'Ασμηνίου', + 'Ασπραγγέλων', + 'Ασπριάς', + 'Ασπροβάλτας', + 'Ασπρογείων', + 'Ασπρογερακάτων', + 'Ασπροκάμπου', + 'Ασπροκκλησίου', + 'Ασπροκκλησιάς', + 'Ασπρονερίου', + 'Ασπροπουλιάς', + 'Ασπροπύργου', + 'Ασπροχωρίου', + 'Ασπρούλας', + 'Ασσήρου', + 'Αστακού', + 'Αστερίου', + 'Αστρά', + 'Αστράκων', + 'Αστρίτσης', + 'Αστριτσίου', + 'Αστροχωρίου', + 'Αστυπαλαίας', + 'Αστυρακίου', + 'Ασφάκας', + 'Ασφένδου', + 'Ασφενδιού', + 'Ασωμάτου', + 'Ασωμάτων', + 'Ασωπίας', + 'Ασωπού', + 'Ασώματα', + 'Αταλάντης', + 'Ατραπού', + 'Ατσικής', + 'Ατσιποπούλου', + 'Ατσιχόλου', + 'Αυγής', + 'Αυγείου', + 'Αυγενικής', + 'Αυγερινού', + 'Αυγώνυμων', + 'Αυλής', + 'Αυλακίου', + 'Αυλιωτών', + 'Αυλοτόπου', + 'Αυλωναρίου', + 'Αυλών', + 'Αφάντου', + 'Αφετών', + 'Αφιδνών', + 'Αφισίου', + 'Αφράτου', + 'Αφράτων', + 'Αφρατίου', + 'Αφροξυλιάς', + 'Αφύτου', + 'Αχαΐας', + 'Αχαρνών', + 'Αχαϊκού', + 'Αχεντριά', + 'Αχερουσίας', + 'Αχιλλείου', + 'Αχινού', + 'Αχλάδας', + 'Αχλαδέ', + 'Αχλαδέας', + 'Αχλαδίου', + 'Αχλαδίων', + 'Αχλαδερής', + 'Αχλαδεών', + 'Αχλαδινής', + 'Αχλαδοκάμπου', + 'Αχλαδοκάστρου', + 'Αχλαδοχωρίου', + 'Αχυρών', + 'Αψάλου', + 'Αϊδινίου', + 'Αϊτανίων', + 'Αύρας', + 'Βάβδου', + 'Βάγγου', + 'Βάθειας', + 'Βάθης', + 'Βάλτας', + 'Βάλτου', + 'Βάμου', + 'Βάρδας', + 'Βάρης', + 'Βάρνακα', + 'Βάρους', + 'Βάστα', + 'Βάτου', + 'Βάχλιας', + 'Βάχου', + 'Βέλου', + 'Βέλους', + 'Βέργας', + 'Βέργης', + 'Βέροιας', + 'Βέσσης', + 'Βήσσανης', + 'Βίβλου', + 'Βίγλας', + 'Βίνιανης', + 'Βίτολης', + 'Βίτσης', + 'Βαβιλών', + 'Βαβουρίου', + 'Βαγίων', + 'Βαγενιτίου', + 'Βαγιονιάς', + 'Βαθέως', + 'Βαθείας', + 'Βαθυκοίλου', + 'Βαθυλάκκου', + 'Βαθυπέδου', + 'Βαθυτόπου', + 'Βαλανίδας', + 'Βαλανείου', + 'Βαλανιδιάς', + 'Βαλανιδοράχης', + 'Βαλανιδούσσας', + 'Βαλαώρας', + 'Βαλεριάνου', + 'Βαλιμής', + 'Βαλιμιτίκων', + 'Βαλκάνου', + 'Βαλσαμονέρου', + 'Βαλτερού', + 'Βαλτεσινίκου', + 'Βαλτετσίου', + 'Βαλτινού', + 'Βαλτονέρων', + 'Βαλτοτοπίου', + 'Βαλτοχωρίου', + 'Βαλύρας', + 'Βαμβακιάς', + 'Βαμβακοπούλου', + 'Βαμβακοφύτου', + 'Βαμβακούς', + 'Βαμβακούσσης', + 'Βανάδας', + 'Βανάτου', + 'Βαπτιστού', + 'Βαρβάρας', + 'Βαρβίτσης', + 'Βαρβασαίνης', + 'Βαργιάδων', + 'Βαργιάνης', + 'Βαρδάτων', + 'Βαρδαλής', + 'Βαρετάδας', + 'Βαρθολομιού', + 'Βαρικού', + 'Βαρλαάμ', + 'Βαρνάβα', + 'Βαρυπατάδων', + 'Βαρύπετρου', + 'Βασαρά', + 'Βασιλή', + 'Βασιλακίου', + 'Βασιλατίκων', + 'Βασιλειών', + 'Βασιλεωνοίκου', + 'Βασιλικής', + 'Βασιλικιάδων', + 'Βασιλικού', + 'Βασιλικών', + 'Βασιλικών Ανωγείων', + 'Βασιλιτσίου', + 'Βασιλοπούλου', + 'Βασιλουδίου', + 'Βατίου', + 'Βατατάδων', + 'Βατερού', + 'Βατολάκκου', + 'Βατοχωρίου', + 'Βατούσσης', + 'Βατσουνιάς', + 'Βαυκερής', + 'Βαφέ', + 'Βαφιοχωρίου', + 'Βαχού', + 'Βεγόρων', + 'Βελάς', + 'Βελίκας', + 'Βελίνης', + 'Βελανιδίου', + 'Βελανιδίων', + 'Βελανιδιάς', + 'Βελβίνας', + 'Βελβεντού', + 'Βελεντζικού', + 'Βελεσιωτών', + 'Βελεστίνου', + 'Βελημαχίου', + 'Βελιγοστής', + 'Βελιμαχίου', + 'Βελιτσών', + 'Βελιών', + 'Βελονάδων', + 'Βελωτών', + 'Βενίου', + 'Βενεράτου', + 'Βερίνου', + 'Βερβένων', + 'Βερβεράτου', + 'Βεργίνης', + 'Βερδικούσσης', + 'Βερενίκης', + 'Βερμίου', + 'Βερτίσκου', + 'Βεύης', + 'Βιάννου', + 'Βιδιακίου', + 'Βιζαρίου', + 'Βικίου', + 'Βιλίων', + 'Βιλανδρέδου', + 'Βιλιβίνης', + 'Βιρού', + 'Βισταγής', + 'Βιτάλων', + 'Βιταλάδων', + 'Βιταλίου', + 'Βλάση', + 'Βλάστης', + 'Βλάτους', + 'Βλασίας', + 'Βλασίου', + 'Βλαχάβας', + 'Βλαχάτων Εικοσιμίας', + 'Βλαχέρνης', + 'Βλαχατάνου', + 'Βλαχερωνιτίσσης', + 'Βλαχιάς', + 'Βλαχιώτη', + 'Βλαχογιαννίου', + 'Βλαχοκερασέας', + 'Βλαχομάνδρας', + 'Βλαχοπούλου', + 'Βλησιδιάς', + 'Βλιζιανών', + 'Βλοχού', + 'Βλυχού', + 'Βοβούσης', + 'Βογατσικού', + 'Βοθιανών', + 'Βολιμών', + 'Βολισσού', + 'Βομβοκούς', + 'Βορδονίας', + 'Βορεινού', + 'Βοριζίων', + 'Βοσκοχωρίου', + 'Βοτονοσίου', + 'Βουβοποτάμου', + 'Βουβών', + 'Βουγιάτου', + 'Βουζίου', + 'Βουκολιών', + 'Βουλγάρω', + 'Βουλιάστης', + 'Βουλιαγμένης', + 'Βουλισμένης', + 'Βουνάργου', + 'Βουναίνων', + 'Βουναρίων', + 'Βουνιατάδων', + 'Βουνιχώρας', + 'Βουνοπλαγιάς', + 'Βουνού', + 'Βουρβούλου', + 'Βουρβούρων', + 'Βουργαρελίου', + 'Βουρκωτής', + 'Βουρλιωτών', + 'Βουρνικά', + 'Βουτά', + 'Βουταίνης', + 'Βουτιάνων', + 'Βουτσίμου', + 'Βουτσαρά', + 'Βουτύρου', + 'Βουτών', + 'Βουχωρίνας', + 'Βοχαϊκού', + 'Βούλας', + 'Βούλπης', + 'Βούνων', + 'Βούρμπιανης', + 'Βούτση', + 'Βράχας', + 'Βράχου', + 'Βρίας', + 'Βρίνας', + 'Βρίσας', + 'Βραΐλας', + 'Βραγγιανών', + 'Βραγιά', + 'Βραγκιανών', + 'Βραδέτου', + 'Βρασνών', + 'Βραστάμων', + 'Βραχασίου', + 'Βραχατίου', + 'Βραχιάς', + 'Βραχναιίκων', + 'Βρεσθένων', + 'Βρεστού', + 'Βριλησσίων', + 'Βρομόβρυσης', + 'Βροντάδου', + 'Βροντής', + 'Βρονταμά', + 'Βροντερού', + 'Βροντισμένης', + 'Βροντούς', + 'Βροσίνας', + 'Βρουβιανών', + 'Βρουστίου', + 'Βρουχά', + 'Βροχίτσης', + 'Βρούτση', + 'Βρυναίνης', + 'Βρυοτόπου', + 'Βρυσέλλας', + 'Βρυσακίου', + 'Βρυσικών', + 'Βρυσιών', + 'Βρυσουλών', + 'Βρυσοχωρίου', + 'Βρυσούλας', + 'Βρυσών', + 'Βρυσών Αποκορρώνου', + 'Βρυσών Κυδωνίας', + 'Βρυτών', + 'Βρύσης', + 'Βυζίτσης', + 'Βυζικίου', + 'Βυθού', + 'Βυρωνείας', + 'Βυσσινέας', + 'Βυτίνης', + 'Βυτιναιίκων', + 'Βωλάδας', + 'Βωλεώνων', + 'Βόλβης', + 'Βόλου', + 'Βόνης', + 'Βόνιτσας', + 'Βύσσης', + 'Βώρων', + 'Γάβρου', + 'Γέρακα', + 'Γέργερης', + 'Γέρμα', + 'Γέρμας', + 'Γέροντα', + 'Γαΐου', + 'Γαβαλά', + 'Γαβαλοχωρίου', + 'Γαβαλούς', + 'Γαβρακίων', + 'Γαβριάς', + 'Γαβρισιών', + 'Γαβρολίμνης', + 'Γαζίου', + 'Γαζώρου', + 'Γαλάνης', + 'Γαλάρου', + 'Γαλήνης', + 'Γαλίφας', + 'Γαλανάδου', + 'Γαλαναίϊκα', + 'Γαλανόβρυσης', + 'Γαλαξιδίου', + 'Γαλαρινού', + 'Γαλατά', + 'Γαλατάδων', + 'Γαλατίστης', + 'Γαλατακίου', + 'Γαλατείας', + 'Γαλατινής', + 'Γαλατσάδων', + 'Γαλατσίου', + 'Γαλατσώνας', + 'Γαλησσά', + 'Γαληψού', + 'Γαλιάς', + 'Γαλλικού', + 'Γαναδιού', + 'Γανοχώρας', + 'Γαράζου', + 'Γαρέας', + 'Γαρίπας', + 'Γαργαλιάνων', + 'Γαρδελάδων', + 'Γαρδικίου', + 'Γαρδικίου Σούλι', + 'Γαρεφείου', + 'Γαρούνας', + 'Γαστουρίου', + 'Γαστούνης', + 'Γαυρίου', + 'Γαϊτανίου', + 'Γαύδου', + 'Γδοχίων', + 'Γελάνθης', + 'Γελινιατίκων', + 'Γενεσίου', + 'Γενισέας', + 'Γενναδίου', + 'Γερακίου', + 'Γερακαρίου', + 'Γερακαρούς', + 'Γερακιούς', + 'Γερακλίου', + 'Γερανίου', + 'Γερανίων', + 'Γεροπλατάνου', + 'Γεφυρίων', + 'Γεφυρουδίου', + 'Γεφύρας', + 'Γεωργάνων', + 'Γεωργανάδων', + 'Γεωργιανής', + 'Γεωργιανών', + 'Γεωργικού', + 'Γεωργιουπόλεως', + 'Γεωργιτσίου', + 'Γιάλτρων', + 'Γιάννουλης', + 'Γιαννάδων', + 'Γιανναίων', + 'Γιαννακοχωρίου', + 'Γιαννιτσίου', + 'Γιαννιτσοχωρίου', + 'Γιαννιτσούς', + 'Γιαννιτσών', + 'Γιαννοπούλων', + 'Γιαννωτών', + 'Γιμαρίου', + 'Γιουργάνιστας', + 'Γιρομερίου', + 'Γκαγκαλών', + 'Γκανέϊκα', + 'Γκοριτσάς', + 'Γκούρας', + 'Γκρίκας', + 'Γκραίκα', + 'Γκριμπόβου', + 'Γλάστρας', + 'Γλίνου', + 'Γλαφυρών', + 'Γλαύκης', + 'Γλινάδου', + 'Γλυκής', + 'Γλυκομηλέας', + 'Γλυκορριζίου', + 'Γλυκόβρυσης', + 'Γλυκών Νερών', + 'Γλυφάδα', + 'Γλυφάδας', + 'Γλύφας', + 'Γλώσσης', + 'Γολάς', + 'Γοματίου', + 'Γονίμου', + 'Γονούσσης', + 'Γοράνων', + 'Γοργοβιτών', + 'Γοργογυρίου', + 'Γοργομύλου', + 'Γοργοποτάμου', + 'Γοργόπη', + 'Γορτυνίας', + 'Γουβών', + 'Γουλεδιανών', + 'Γουλεμίου', + 'Γουλών', + 'Γουμένισσας', + 'Γουμέρου', + 'Γουριάς', + 'Γουριωτίσσης', + 'Γράμου', + 'Γρίβας', + 'Γραίκα', + 'Γραβιάς', + 'Γραβούνης', + 'Γραικικού', + 'Γραικοχωρίου', + 'Γραικού', + 'Γραμβουσής', + 'Γραμμένης', + 'Γραμμένης Οξυάς', + 'Γραμμένου', + 'Γραμματικού', + 'Γραμματικούς', + 'Γραμμενίτσης', + 'Γραμμούσης', + 'Γραμπιάς', + 'Γρανίτου', + 'Γρανίτσης', + 'Γρανιτσαιίκων', + 'Γρανιτσοπούλας', + 'Γρατίνη', + 'Γρεβενιτίου', + 'Γρεβενών', + 'Γρηγορίας', + 'Γρηγορίου', + 'Γρηγόρη', + 'Γριζάνου', + 'Γριζάτων', + 'Γριμπόβου', + 'Γρύλλου', + 'Γυθείου', + 'Γυμνοτόπου', + 'Γυμνού', + 'Γυναικοκάστρου', + 'Γυρίου', + 'Γωνιάς', + 'Γωνιών Μαλεβιζίου', + 'Γόμφων', + 'Γόννων', + 'Δάρα', + 'Δάφνης', + 'Δάφνου', + 'Δένδρου', + 'Δένδρων Τυρνάβου', + 'Δένδρων Φαρσάλων', + 'Δέσης', + 'Δήμητρας', + 'Δίβρης', + 'Δίου', + 'Δαδιάς', + 'Δαιμονίας', + 'Δαλαμανάρας', + 'Δαμάστας', + 'Δαμαβόλου', + 'Δαμακινίου', + 'Δαμανίων', + 'Δαμασίου', + 'Δαμασκηνιάς', + 'Δαματρίας', + 'Δαμουλιανάτων', + 'Δανακού', + 'Δαράτσου', + 'Δαρμένη', + 'Δασκίου', + 'Δασολόφου', + 'Δασοχωρίου', + 'Δασυλλίου', + 'Δασωτού', + 'Δαυγάτων', + 'Δαυλείας', + 'Δαφίων', + 'Δαφνέ', + 'Δαφνίου', + 'Δαφνιά', + 'Δαφνιωτίσσης', + 'Δαφνοσπηλιάς', + 'Δαφνουδίου', + 'Δαφνοφύτου', + 'Δαφνούλας', + 'Δαφνούσσης', + 'Δαφνωτής', + 'Δαφνών', + 'Δειλινά', + 'Δελβινακίου', + 'Δελβινακοπούλου', + 'Δελερίων', + 'Δελιανών', + 'Δελφίνου', + 'Δελφών', + 'Δεματίου', + 'Δεμεστίχων', + 'Δενδροχωρίου', + 'Δερβενίου', + 'Δερβιζιάνων', + 'Δερματίου', + 'Δεσινού', + 'Δεσκάτης', + 'Δεσποτικού', + 'Δεσφίνης', + 'Δεσύλλα', + 'Δημαίνης', + 'Δημαρίου', + 'Δημητρητσίου', + 'Δημητροπούλου', + 'Δημητσάνης', + 'Διάβας', + 'Διάσελλου', + 'Διαβατού', + 'Διαβατών', + 'Διαβολιτσίου', + 'Διακοπίου', + 'Διακοπτού', + 'Διαλεκτού', + 'Διασέλλου', + 'Διασέλλων', + 'Διασελλακίου', + 'Διβαράτων', + 'Διγελιωτίκων', + 'Διδυμοτείχου', + 'Διδύμας', + 'Διδύμων', + 'Διευχών', + 'Δικάστρου', + 'Δικαίων', + 'Δικορύφου', + 'Διλινάτων', + 'Διλόφου', + 'Διλόφου Λαρίσης', + 'Διλόφου Φαρσάλων', + 'Διμηνίου', + 'Διμηνιού', + 'Διμοκορίου', + 'Διμυλιάς', + 'Διοδίων', + 'Διομηδείας', + 'Διονυσίου', + 'Διονύσου', + 'Διπλατάνου', + 'Διποτάμου', + 'Διποταμιάς', + 'Δισπηλίου', + 'Διστράτου', + 'Διστόμου', + 'Διχειμάρρου', + 'Διχομοιρίου', + 'Διχωρίου', + 'Δοβλά', + 'Δοκιμίου', + 'Δοκός', + 'Δολίχης', + 'Δολιανών', + 'Δολού', + 'Δολών', + 'Δομίρου', + 'Δομβραίνης', + 'Δομενίκου', + 'Δομιανών', + 'Δομνίστης', + 'Δομοκού', + 'Δονούσης', + 'Δοξάτου', + 'Δοξαρά', + 'Δοξαρού', + 'Δορίσκου', + 'Δορβιτσιάς', + 'Δοτσικού', + 'Δουκάδων', + 'Δουκαναιίκων', + 'Δουλίου', + 'Δουμενών', + 'Δουμπιών', + 'Δουναίικων', + 'Δούκα', + 'Δράμας', + 'Δρίμιτσας', + 'Δραΐνας', + 'Δραβήσκου', + 'Δραγάνου', + 'Δραγασιάς', + 'Δραγοψάς', + 'Δραγωγίου', + 'Δρακαίων', + 'Δρακείας', + 'Δρακοβουνίου', + 'Δρακόνας', + 'Δρακότρυπας', + 'Δραμεσιών', + 'Δραπανιά', + 'Δραπετσώνας', + 'Δρεπάνου', + 'Δριμίσκου', + 'Δροσάτου', + 'Δροσίνη', + 'Δροσερού', + 'Δροσιά', + 'Δροσιάς', + 'Δροσινή', + 'Δροσοπηγής', + 'Δροσοχωρίου', + 'Δρυάλου', + 'Δρυμάδων', + 'Δρυμαίας', + 'Δρυμού', + 'Δρυοβούνου', + 'Δρυοφύτου', + 'Δρυόπης', + 'Δρύμη', + 'Δυρραχίου', + 'Δυσβάτου', + 'Δυτικής Φραγκίστας', + 'Δυτικού', + 'Δωδώνης', + 'Δωματίων', + 'Δωρίου', + 'Δωρικού', + 'Δωροθέας', + 'Δόλιανης', + 'Δόξης', + 'Δόριζα', + 'Δύο Βουνών', + 'Δύο Χωρίων', + 'Δύστου', + 'Εβροπούλων', + 'Εγγαρών', + 'Εγκλουβής', + 'Εδέσσης', + 'Εθιάς', + 'Εθνικού', + 'Ειδομένης', + 'Ειρηνικού', + 'Εκάλης', + 'Εκκάρας', + 'Εκκλησιών', + 'Εκκλησοχωρίου', + 'Εκκλησούλας', + 'Ελάτας', + 'Ελάτειας', + 'Ελάτης', + 'Ελάτου', + 'Ελάφου', + 'Ελίκας', + 'Ελίκης', + 'Ελαίας', + 'Ελαιοφύτου', + 'Ελαιοχωρίου', + 'Ελαιοχωρίων', + 'Ελαταριάς', + 'Ελατείας', + 'Ελατοχωρίου', + 'Ελατούς', + 'Ελατόβρυσης', + 'Ελαφονήσου', + 'Ελαφοχωρίου', + 'Ελαφότοπου', + 'Ελενών', + 'Ελεούσης', + 'Ελευθέρνης', + 'Ελευθέρου', + 'Ελευθερίου', + 'Ελευθερίου-Κορδελιού', + 'Ελευθεριανής', + 'Ελευθερουπόλεως', + 'Ελευθεροχωρίου', + 'Ελευθερών', + 'Ελικίστρας', + 'Ελληνίτσης', + 'Ελληνικού', + 'Ελληνικών', + 'Ελληνοεκκλησίας', + 'Ελληνοκάστρου', + 'Ελληνοπύργου', + 'Ελληνοχωρίου', + 'Ελλοπίας', + 'Ελούντας', + 'Εμμανουήλ Παππά', + 'Εμπάρου', + 'Εμπεσού', + 'Εμπορίου', + 'Εμπορείου', + 'Εμπορειού', + 'Εμπροσνέρου', + 'Ενορίας', + 'Εξάρχου', + 'Εξαλόφου', + 'Εξαμιλίων', + 'Εξανθείας', + 'Εξαπλατάνου', + 'Εξοχή', + 'Εξοχής', + 'Εξοχικού', + 'Εξωγής', + 'Εξωχωρίου', + 'Επάνω Βαθείας', + 'Επανομής', + 'Επανωχωρίου', + 'Επιβατών', + 'Επιδαύρου', + 'Επινιανών', + 'Επισκέψεως', + 'Επισκοπής', + 'Επισκοπής Γωνιάς', + 'Επισκοπής Νάουσας', + 'Επισκοπικού', + 'Επιταλίου', + 'Επταλόφου', + 'Επταμύλων', + 'Επταχωρίου', + 'Ερασμίου', + 'Ερατεινής', + 'Ερατεινού', + 'Ερατύρας', + 'Ερεικούσσης', + 'Ερεσού', + 'Ερετρίας', + 'Ερινεού', + 'Ερμακιάς', + 'Ερμητσίου', + 'Ερμιόνης', + 'Ερμουπόλεως', + 'Ερυθραίας', + 'Ερυθρών', + 'Ερυμανθείας', + 'Εσοχή', + 'Εσωβάλτων', + 'Εσωχωρίων', + 'Ευάνδρου', + 'Ευαγγελισμού', + 'Ευαγγελισμού Λαρίσης', + 'Ευαγγελιστρίας', + 'Ευγήρου', + 'Ευδήλου', + 'Ευζώνων', + 'Ευηνοχωρίου', + 'Ευκαρπίας', + 'Ευλάλου', + 'Ευμοίρου', + 'Ευξεινουπόλεως', + 'Ευπαλίου', + 'Ευρωπού', + 'Ευρωστίνης Ροζενών', + 'Ευόσμου', + 'Εφέσου', + 'Εφύρας', + 'Εχίνου', + 'Εύας', + 'Ζάκα', + 'Ζάκρου', + 'Ζάρκου', + 'Ζήριας', + 'Ζίρου', + 'Ζίτσης', + 'Ζίχνης', + 'Ζαγκλιβερίου', + 'Ζαγοράς', + 'Ζακυνθίων', + 'Ζαλόγγου', + 'Ζαππείου', + 'Ζαράκων', + 'Ζαρκαδιάς', + 'Ζαρού', + 'Ζαρούχλης', + 'Ζατούνης', + 'Ζαχάρως', + 'Ζαχλωριτίκων', + 'Ζαχλωρούς', + 'Ζαϊμίου', + 'Ζελίου', + 'Ζεμενού', + 'Ζενίων', + 'Ζερβοχωρίου', + 'Ζερμπισίων', + 'Ζευγαρακίου', + 'Ζευγολατείου', + 'Ζευγολατιού', + 'Ζεφυρίου', + 'Ζηλευτής', + 'Ζηλευτού', + 'Ζιγοβιστίου', + 'Ζουνακίου', + 'Ζουριδίου', + 'Ζούζουλης', + 'Ζυγού', + 'Ζυμπραγού', + 'Ζυφιά', + 'Ζωής', + 'Ζωγράφου', + 'Ζωνιανών', + 'Ζωοδόχου', + 'Ζωοδόχου Πηγής', + 'Ζωριάνου', + 'Ζωτικού', + 'Ζωφόρων', + 'Ζόλων', + 'Ζώνης', + 'Ηγουμενίτσης', + 'Ηλέκτρας', + 'Ηλιοκάλης', + 'Ηλιοκάστρου', + 'Ηλιοκώμης', + 'Ηλιορράχης', + 'Ηλιοχωρίου', + 'Ηλιούπολης', + 'Ηλιόλουστο', + 'Ημεροβιγλίου', + 'Ηραίου', + 'Ηρακλίτσης', + 'Ηρακλείας', + 'Ηρακλείου', + 'Θάνα', + 'Θάνους', + 'Θάσου', + 'Θέας', + 'Θέρμης', + 'Θέρμου', + 'Θήρας', + 'Θίσβης', + 'Θαλαμών', + 'Θαλερού', + 'Θαρουνίων', + 'Θαυμακού', + 'Θεισόας', + 'Θεμέλου', + 'Θεοδοσίων', + 'Θεοδωρακίου', + 'Θεοδωρακείου', + 'Θεοδωριάνων', + 'Θεοδώρας', + 'Θεοκτίστου', + 'Θεολόγου', + 'Θεοπέτρας', + 'Θερίσου', + 'Θεραπειό', + 'Θεριακησίου', + 'Θεριανού', + 'Θερινού', + 'Θερμησίας', + 'Θερμοπυλών', + 'Θερμών', + 'Θεσπιών', + 'Θεσπρωτικού', + 'Θεσσαλονίκης', + 'Θηβαίων', + 'Θηναίας', + 'Θηρασίας', + 'Θηριοπέτρας', + 'Θολαρίων', + 'Θολοποταμίου', + 'Θολού', + 'Θουρίας', + 'Θουρίου', + 'Θούριο Θουρίου', + 'Θρακομακεδόνων', + 'Θραψανού', + 'Θραψιμίου', + 'Θροφαρίου', + 'Θρυλορίου', + 'Θρόνου', + 'Θυμιανών', + 'Θυρίου', + 'Θωκνίας', + 'Ιάσιον', + 'Ιάσμου', + 'Ιαλυσού', + 'Ιβήρων', + 'Ιεραπέτρας', + 'Ιερισσού', + 'Ιερομνήμης', + 'Ιεροπηγής', + 'Ιητών', + 'Ιθάκης', + 'Ιθώμης', + 'Ικλαίνης', + 'Ιλίου', + 'Ιμέρου', + 'Ιμέρων', + 'Ινάχου', + 'Ινίου', + 'Ιππείου', + 'Ιρίων', + 'Ισαακίου', + 'Ισθμίας', + 'Ιστιαίας', + 'Ιστρίου', + 'Ισώματος Καρυών', + 'Ιτέα', + 'Ιτέας', + 'Ιωαννίνων', + 'Ιωαννιτών', + 'Ιωνίας', + 'Κάινας', + 'Κάλφα', + 'Κάμπου', + 'Κάμπων', + 'Κάπης', + 'Κάρπης', + 'Κάσου', + 'Κάσπακα', + 'Κάστρου', + 'Κάψα', + 'Κέδρου', + 'Κέδρων', + 'Κέλλης', + 'Κέντρου', + 'Κέχρου', + 'Κήπων', + 'Κίνυρα', + 'Κίου', + 'Κίρκης', + 'Κίρρας', + 'Καβάλας', + 'Καβάλου', + 'Καβάσιλα', + 'Καβαλλαρίου', + 'Καβαλλουρίου', + 'Καβασίλων', + 'Καββαδάδων', + 'Καβησού', + 'Καβουσίου', + 'Καβύλης', + 'Καγκαδίου', + 'Καδίου', + 'Καθενών', + 'Καθολικού', + 'Καινουργίου', + 'Καινούργιου Χωρίου', + 'Καισάρειας', + 'Καισαρίου', + 'Καισαριανής', + 'Κακαλετρίου', + 'Κακοβάτου', + 'Κακοδικίου', + 'Κακολάκκου', + 'Κακοπέτρου', + 'Κακοπλευρίου', + 'Κακοταρίου', + 'Κακουραίικων', + 'Καλάθου', + 'Καλάμου', + 'Καλάνδρας', + 'Καλάνου', + 'Καλής', + 'Καλής Βρύσης', + 'Καλής Κώμης', + 'Καλαβάρδα', + 'Καλαβρούζης', + 'Καλαβρύτων', + 'Καλαθενών', + 'Καλαμάτας', + 'Καλαμίου', + 'Καλαμακίου', + 'Καλαμαρά', + 'Καλαμαριάς', + 'Καλαμαύκας', + 'Καλαμιά', + 'Καλαμιάς', + 'Καλαμιτσίου', + 'Καλαμιτσίου Αλεξάνδρου', + 'Καλαμιτσίου Αμυγδαλίου', + 'Καλαμπάκας', + 'Καλαμπακίου', + 'Καλαμωτής', + 'Καλαμωτού', + 'Καλανίστρας', + 'Καλανδαρές', + 'Καλαποδίου', + 'Καλαρρυτών', + 'Καλαφατιώνων', + 'Καλεντίνης', + 'Καλεντζίου', + 'Καλεσιών', + 'Καλεσμένου', + 'Καλημεριάνων', + 'Καληράχης', + 'Καλιανών', + 'Καλιδόνης', + 'Καλιπάδου', + 'Καλιτσαίνης', + 'Καλλίου', + 'Καλλίστη', + 'Καλλίστης', + 'Καλλεργιανών', + 'Καλλιανίου', + 'Καλλιανού', + 'Καλλιδρόμου', + 'Καλλιθέας', + 'Καλλιθέας Σουλίου', + 'Καλλιθέας Φαρσάλων', + 'Καλλιθέας Φιλιατών', + 'Καλλιθήρου', + 'Καλλικράτειας', + 'Καλλικώμου', + 'Καλλιμασιάς', + 'Καλλινίκης', + 'Καλλιπεύκης', + 'Καλλιπόλεως', + 'Καλλιράχης', + 'Καλλιρρόης', + 'Καλλιφωνίου', + 'Καλλιφύτου', + 'Καλλιόπης', + 'Καλλονής', + 'Καλλυντήριον', + 'Καλοβάτου', + 'Καλογέρου', + 'Καλογήρων', + 'Καλογερεσίου', + 'Καλογερικού', + 'Καλογερόρραχης', + 'Καλογριανής', + 'Καλογριανών', + 'Καλοκάστρου', + 'Καλομοίρας', + 'Καλονερίου', + 'Καλονύκτου', + 'Καλοσκοπής', + 'Καλουδίου', + 'Καλουδιανών', + 'Καλουσίου', + 'Καλουτά', + 'Καλοχίου', + 'Καλοχωρίου', + 'Καλοχωρίου-Παντειχίου', + 'Καλού Αγρού', + 'Καλού Νερού', + 'Καλού Χωρίου', + 'Καλπακίου', + 'Καλτεζών', + 'Καλυβίων', + 'Καλυβίων Θορικού', + 'Καλυβίων Μυρτουντίων', + 'Καλυβίων Σοχάς', + 'Καλυβακίων', + 'Καλυβών', + 'Καλυδονίας', + 'Καλυθιών', + 'Καλυμνίων', + 'Καλύβου', + 'Καλών Δένδρων', + 'Καλών Νερών', + 'Καμάρας', + 'Καμάρων', + 'Καμένης', + 'Καμένων Βούρλων', + 'Καμήλας', + 'Καμαρίνας', + 'Καμαρίου', + 'Καμαρίτσης', + 'Καμαρίων', + 'Καμαριώτου', + 'Καμαρούλας', + 'Καμαρωτού', + 'Καμαρών', + 'Καματερού', + 'Καμενίτσης', + 'Καμενιάνων', + 'Καμηλαρίου', + 'Καμινίων', + 'Καμινακίου', + 'Καμιναράτων', + 'Καμισιανών', + 'Καμπάνη', + 'Καμπής', + 'Καμπανού', + 'Καμπιών', + 'Καμποχωρίου', + 'Κανακάδων', + 'Καναλίου', + 'Καναλίων', + 'Καναλλακίου', + 'Κανδάλου', + 'Κανδάνου', + 'Κανδήλας', + 'Καπανδριτίου', + 'Καπαρελλίου', + 'Καπελέτου', + 'Καπεσόβου', + 'Καπλανίου', + 'Καπνοφύτου', + 'Καπνοχωρίου', + 'Καππά', + 'Καππαδοκικού', + 'Καππαριάς', + 'Καράνου', + 'Καράτουλα', + 'Καράτουλα Κυνουρίας', + 'Καράτουλα Μεγαπόλεως', + 'Καρέας', + 'Καρές', + 'Καρίτσης', + 'Καρίτσης Δολόπων', + 'Καρίτσης Καρπενησίου', + 'Καραβά', + 'Καραβάδου', + 'Καραβομύλου', + 'Καραβοστάμου', + 'Καραιίκων', + 'Καρατζά', + 'Καραϊσκάκη', + 'Καρβάλης', + 'Καρβασαρά', + 'Καρβελά', + 'Καρβελίου', + 'Καρβουνάδων', + 'Καρβουναρίου', + 'Καρδίας', + 'Καρδίτσης', + 'Καρδαμά', + 'Καρδαμαίνης', + 'Καρδαμύλης', + 'Καρδαμύλων', + 'Καρδαρά', + 'Καρδαριτσίου', + 'Καρδιάς', + 'Καρδιακαυτίου', + 'Καρδιανής', + 'Καρδιτσομαγούλας', + 'Καριανής', + 'Καρινών', + 'Καριταίνης', + 'Καριωτίου', + 'Καριωτών', + 'Καρκιναγρίου', + 'Καρλοβασίων', + 'Καρνασίου', + 'Καρνεζαίικων', + 'Καροπλεσίου', + 'Καρουζανών', + 'Καρουσάδων', + 'Καρουτών', + 'Καρπάθου', + 'Καρπασίου', + 'Καρπενησίου', + 'Καρπερής', + 'Καρπερού', + 'Καρποφόρων', + 'Καρποχωρίου', + 'Καρτεράδου', + 'Καρτερίου', + 'Καρτερολίου', + 'Καρτερών', + 'Καρυάς', + 'Καρυδίου', + 'Καρυδίου Μιραμπέλλου', + 'Καρυδίτσας', + 'Καρυδιάς', + 'Καρυοβουνίου', + 'Καρυουπόλεως', + 'Καρυοφύτου', + 'Καρυοχωρίου', + 'Καρυωτίσσης', + 'Καρυών', + 'Καρωτής', + 'Καρύστου', + 'Καρών Αποκορρώνου', + 'Καρών Κισσάμου', + 'Κασάνου', + 'Κασσανδρείας', + 'Κασσανδρηνού', + 'Κασσιόπης', + 'Καστάνιανης', + 'Καστέλλας', + 'Καστέλλου', + 'Κασταμονίτσης', + 'Καστανέας', + 'Καστανέας Επιδαύρου Λιμηράς', + 'Καστανίτσης', + 'Καστανίων', + 'Καστανερής', + 'Καστανεών', + 'Καστανιάς', + 'Καστανιωτίσσης', + 'Καστανοφύτου', + 'Καστανοχωρίου', + 'Καστανούλας', + 'Καστανούσσης', + 'Καστανώνος Ζαγορίου', + 'Καστελλάνων Γύρου', + 'Καστελλάνων Μέσης', + 'Καστελλίου', + 'Καστελλίου Φουρνής', + 'Καστελλίων', + 'Καστελλιανών', + 'Καστορίας', + 'Καστορείου', + 'Καστού', + 'Καστρίου', + 'Καστρίτσης', + 'Καστρίων', + 'Καστρακίου', + 'Καστριτσίου', + 'Καστριωτίσσης', + 'Κατάκαλης', + 'Καταβόθρας', + 'Κατακαλίου', + 'Κατακοίλου', + 'Κατακόλου', + 'Καταλάκκου', + 'Καταλαγαρίου', + 'Καταλωνίων', + 'Καταμάχης', + 'Καταπόλων', + 'Καταρράκτου', + 'Κατασταρίου', + 'Καταφυγίου', + 'Καταφυλλίου', + 'Καταφύτου', + 'Καταχά', + 'Κατερίνης', + 'Κατοχής', + 'Κατούνας', + 'Κατούνης', + 'Κατσίμπαλη', + 'Κατσαρού', + 'Κατσαρωνίου', + 'Κατσιδωνίου', + 'Κατσικά', + 'Κατταβίας', + 'Κατωγής', + 'Κατωμερίου', + 'Κατωχωρίου', + 'Καυκάσου', + 'Καυκωνίας', + 'Καψάλων', + 'Καψοράχης', + 'Κελεφά', + 'Κεντρικής', + 'Κεντρικού', + 'Κεντροχωρίου', + 'Κεράμου', + 'Κεράς', + 'Κερίου', + 'Κεραμέ', + 'Κεραμίου', + 'Κεραμίτσης', + 'Κεραματών', + 'Κεραμείας', + 'Κεραμείων', + 'Κεραμειών', + 'Κεραμιδίου', + 'Κεραμιδιάς', + 'Κεραμουτσίου', + 'Κεραμωτής', + 'Κερασέα', + 'Κερασέας', + 'Κερασίτσης', + 'Κερασίων', + 'Κερασεών', + 'Κερασιάς', + 'Κερασοχωρίου', + 'Κεραστάρη', + 'Κερασόβου', + 'Κερατέας', + 'Κερατσινίου', + 'Κερδυλίων', + 'Κερκίνης', + 'Κερκυραίων', + 'Κερπινής', + 'Κερτέζης', + 'Κερυνείας', + 'Κεσσάνης', + 'Κεστρίνης', + 'Κεφάλου', + 'Κεφαλά', + 'Κεφαλίου', + 'Κεφαλαρίου', + 'Κεφαλινού', + 'Κεφαλοβρυσίου', + 'Κεφαλοβρύσου', + 'Κεφαλοχωρίου', + 'Κεφαλόβρυσης', + 'Κεχρινιάς', + 'Κεχριών', + 'Κεχροκάμπου', + 'Κηκίδιον', + 'Κηπίων', + 'Κηπουρείου', + 'Κηρίνθου', + 'Κηφισιάς', + 'Κιβερίου', + 'Κιβωτού', + 'Κιζάριον', + 'Κιλελέρ', + 'Κιλκίς', + 'Κιμμερίων', + 'Κιμώλου', + 'Κινιδάρου', + 'Κιονίου', + 'Κιρκιζατών', + 'Κισσάμου', + 'Κισσού', + 'Κλένιας', + 'Κλήματος Ευπαλίου', + 'Κλαδά', + 'Κλαδέου', + 'Κλαδορράχης', + 'Κλαυσίου', + 'Κλείτου', + 'Κλειδίου', + 'Κλειδωνιάς', + 'Κλεινού', + 'Κλεινών', + 'Κλειούς', + 'Κλεισορρευμάτων', + 'Κλεισούρας', + 'Κλεισωρείας', + 'Κλειτορίας', + 'Κλειτσού', + 'Κλεπάς', + 'Κληματακίου', + 'Κληματιάς', + 'Κλημεντίου', + 'Κλινδιάς', + 'Κλοκοτού', + 'Κλωνίου', + 'Κνίδης', + 'Κοίλων', + 'Κοίτας', + 'Κοζάνης', + 'Κοθρέα', + 'Κοιλαδίου', + 'Κοιλιωμένου', + 'Κοιμήσεως', + 'Κοινής', + 'Κοκκάλας', + 'Κοκκίνου', + 'Κοκκίνου Χωρίου', + 'Κοκκαρίου', + 'Κοκκινίου', + 'Κοκκινιάς', + 'Κοκκινογείου', + 'Κοκκινογείων', + 'Κοκκινολιθαρίου', + 'Κοκκινομηλέας', + 'Κοκκινοπηλού', + 'Κοκκινορράχης', + 'Κοκκινοχωρίου', + 'Κοκκινόβρυσης', + 'Κοκκορά', + 'Κοκκωνίου', + 'Κοκκωτών', + 'Κολινδρού', + 'Κολιρίου', + 'Κολλινών', + 'Κολοκυθιάς', + 'Κολυμβαρίου', + 'Κολχικής', + 'Κολχικού', + 'Κομάνου', + 'Κομάρων', + 'Κομίτου', + 'Κομηλίου', + 'Κομιτάτων', + 'Κομμένου', + 'Κομνίνης', + 'Κομνηνάδων', + 'Κομνηνών', + 'Κομοτηνής', + 'Κομπηγαδίου', + 'Κομπιτσίου', + 'Κομποτάδων', + 'Κομποτίου', + 'Κομπωτής', + 'Κονίσκης', + 'Κονίτσης', + 'Κονακίων', + 'Κονιάκου', + 'Κονιδίτσης', + 'Κονισκού', + 'Κονιστρών', + 'Κονοπίνας', + 'Κονταιίκων', + 'Κοντακαιίκων', + 'Κονταραίνης', + 'Κονταριωτίσσης', + 'Κοντιά', + 'Κοντοβαζαίνης', + 'Κοντοβουνίου', + 'Κοντογενάδας', + 'Κοντοδεσποτίου', + 'Κοντολιανίκων', + 'Κοντομαρίου', + 'Κοντοπουλίου', + 'Κοντοπούλων', + 'Κοξαρές', + 'Κοπάνης', + 'Κοπανακίου', + 'Κοπανού', + 'Κορίνθου', + 'Κορίτιανης', + 'Κορακιάνας', + 'Κορακοβουνίου', + 'Κορακοχωρίου', + 'Κορησού', + 'Κορησσίας', + 'Κορθίου', + 'Κορινού', + 'Κορμίστης', + 'Κορνοφωλεάς', + 'Κορνού', + 'Κοροίβου', + 'Κορομηλέας', + 'Κορυδαλλού', + 'Κορυσχάδων', + 'Κορυφής', + 'Κορυφασίου', + 'Κορυφούλας', + 'Κορυφών', + 'Κορφιωτίσσης', + 'Κορφοβουνίου', + 'Κορφών', + 'Κορωνείας', + 'Κορωνησίας', + 'Κορωνούδας', + 'Κορώνας', + 'Κορώνης', + 'Κορώνου', + 'Κοσκίνων', + 'Κοσκινά', + 'Κοσκινού', + 'Κοσμά', + 'Κοσμαδαίων', + 'Κοσματίου', + 'Κοσμηράς', + 'Κοτρωνίου', + 'Κοτσανοπούλου', + 'Κοτσικιάς', + 'Κοτύλης', + 'Κουβαλάτων', + 'Κουβαρά', + 'Κουβουκλίων', + 'Κουδουνίου', + 'Κουδουνίων', + 'Κουκκουλίου', + 'Κουκκουλίων', + 'Κουκκουνάρας', + 'Κουκλεσίου', + 'Κουκλιών', + 'Κουκουλιών', + 'Κουκουναράς', + 'Κουλεντίων', + 'Κουλούρας', + 'Κουμαιίκων', + 'Κουμαραδαίων', + 'Κουμαριάς', + 'Κουμαριτσίου', + 'Κουμπουριανών', + 'Κουνάβων', + 'Κουνινάς', + 'Κουνουπίτσης', + 'Κουνουπιάς', + 'Κουνουπιδιανών', + 'Κουπακίου', + 'Κουπιών', + 'Κουρέντων', + 'Κουραμάδων', + 'Κουρεμαδίου', + 'Κουρκουλών', + 'Κουρνά', + 'Κουρουκλάτων', + 'Κουρουνίου', + 'Κουρουνίων', + 'Κουρουνιού', + 'Κουρουτών', + 'Κουρτακίου', + 'Κουρτεσίου', + 'Κουσέ', + 'Κουσπάδων', + 'Κουτίφαρη', + 'Κουταλά', + 'Κουτρούφων', + 'Κουτσίου', + 'Κουτσελιού', + 'Κουτσοποδίου', + 'Κουτσοχέρας', + 'Κουτσοχέρου', + 'Κουτσού', + 'Κουφαλίων', + 'Κουφοβούνου', + 'Κουφονησίων', + 'Κουφοπούλου', + 'Κουφού', + 'Κοχύλου', + 'Κούβελα', + 'Κούκκου', + 'Κούμανη', + 'Κούμαρη', + 'Κούμων', + 'Κούνου', + 'Κούταλης', + 'Κούτελης', + 'Κούφης', + 'Κράψης', + 'Κρήμνης', + 'Κρήνης', + 'Κρήνης Αιγιαλείας', + 'Κρήνης Πατρών', + 'Κρίνου', + 'Κραθίου', + 'Κρανέας', + 'Κρανιδίου', + 'Κρανιδίων', + 'Κρανούλας', + 'Κρασίου', + 'Κρατερού', + 'Κρεμαστής', + 'Κρεμαστού', + 'Κρεμμυδίων', + 'Κρεστένων', + 'Κρηνίδων', + 'Κρηνίτσης', + 'Κρηνών', + 'Κρηστώνης', + 'Κρητηνίας', + 'Κριατσίου', + 'Κριεζών', + 'Κριθαρακίων', + 'Κριθιάς', + 'Κρικέλλου', + 'Κριμηνίου', + 'Κρινοφύτων', + 'Κριτσάς', + 'Κροκίου', + 'Κροκεών', + 'Κροκυλείου', + 'Κρούστα', + 'Κρυονέρου', + 'Κρυονερίου', + 'Κρυονερίου Ηλείας', + 'Κρυονερίου Ολυμπίας', + 'Κρυονερίτη', + 'Κρυονερίων', + 'Κρυοπηγής', + 'Κρυσταλλοπηγής', + 'Κρυσταλλόβρυσης', + 'Κρυφοβού', + 'Κρυόβρυση', + 'Κρυόβρυσης', + 'Κρυών', + 'Κρωβύλης', + 'Κρωπίας', + 'Κρόκου', + 'Κρύας', + 'Κρύας Βρύσης', + 'Κτένιον', + 'Κτικάδου', + 'Κτιμένης', + 'Κτισμάτων', + 'Κτιστάδων', + 'Κυανής', + 'Κυδωνέας', + 'Κυδωνιών', + 'Κυθήρων', + 'Κυλλήνης', + 'Κυμίνων', + 'Κυνηγού', + 'Κυνοπιαστών', + 'Κυπαρίσσου', + 'Κυπαρισσίας', + 'Κυπαρισσίου', + 'Κυπαρισσίων', + 'Κυρά Βγένας', + 'Κυρίων', + 'Κυρακαλής', + 'Κυριάννας', + 'Κυριακής', + 'Κυριακίου', + 'Κυριακοχωρίου', + 'Κυρτώνης', + 'Κυψέλης', + 'Κυψέλης Μεθάνων', + 'Κυψελοχωρίου', + 'Κω', + 'Κωνσταντίας', + 'Κωνσταντίνων', + 'Κωνσταντινάτου', + 'Κωστάνιανης', + 'Κωστακιών', + 'Κωσταλέξη', + 'Κωσταραζίου', + 'Κωτιλίου', + 'Κωφών', + 'Κόκκινων Λουριών', + 'Κόκλα', + 'Κόμπων', + 'Κόντσικας', + 'Κόξαρης', + 'Κόρφου', + 'Κόσμιον', + 'Κότρωνα', + 'Κύθνου', + 'Κύμης', + 'Κώμης', + 'Κώστου', + 'Κώτα', + 'Λάβδα', + 'Λάβδανης', + 'Λάγιου', + 'Λάγκας', + 'Λάδης', + 'Λάκκας', + 'Λάκκων', + 'Λάλα', + 'Λάλουκα', + 'Λάμπου Μύλων', + 'Λάρδου', + 'Λάστης', + 'Λάστρου', + 'Λάτα', + 'Λέκας', + 'Λέρου', + 'Λίμνης', + 'Λίνδου', + 'Λίππας', + 'Λίστας', + 'Λαΐστης', + 'Λαέρμων', + 'Λαβάρων', + 'Λαγίας', + 'Λαγανά', + 'Λαγκάδας', + 'Λαγκαδά', + 'Λαγκαδίων', + 'Λαγκαδαιίκων', + 'Λαγκαδακίων', + 'Λαγκαδικίων', + 'Λαγοβουνίου', + 'Λαγολίου', + 'Λαγορράχης', + 'Λαγού', + 'Λαγυνών', + 'Λαγωπόδου', + 'Λαδά', + 'Λαδικούς', + 'Λαδοχωρίου', + 'Λαζαράτων', + 'Λαζαρίνας', + 'Λαιίκων', + 'Λαιμού', + 'Λακήθρας', + 'Λακκοπέτρας', + 'Λακκωμάτων', + 'Λακκωνίων', + 'Λακώνων', + 'Λαλιώτου', + 'Λαμιέων', + 'Λαμπαίνης', + 'Λαμπείας', + 'Λαμπερού', + 'Λαμπινής', + 'Λαμπινούς', + 'Λαμπιρίου', + 'Λαμπιωτών', + 'Λαμποκάμπου', + 'Λαμπρόν', + 'Λαμψάκου', + 'Λαμύρων', + 'Λανθίου', + 'Λαντζουνάτου', + 'Λαπαναγών', + 'Λαρίσης', + 'Λαρανίου', + 'Λαρύμνης', + 'Λασταιίκων', + 'Λατζοΐου', + 'Λατσίδας', + 'Λαυκίου', + 'Λαυρεωτικής', + 'Λαφιώνας', + 'Λαφυστίου', + 'Λαχίου', + 'Λαχανά', + 'Λαχανάδας', + 'Λαχανιάς', + 'Λαψίστης', + 'Λαύκας', + 'Λαύκου', + 'Λεήμονα', + 'Λεβαίας', + 'Λεβαδέων', + 'Λεβεντοχωρίου', + 'Λεβιδίου', + 'Λειανοκλαδίου', + 'Λειψυδρίου', + 'Λειψών', + 'Λεκάνης', + 'Λεοντίου', + 'Λεοντίτου', + 'Λεονταρίου', + 'Λεπενούς', + 'Λεπετύμνου', + 'Λεπιανών', + 'Λεπούρων', + 'Λεπρέου', + 'Λεπτινίου', + 'Λεπτοκαρυάς', + 'Λεπτοκαρυάς Ζαγορίου', + 'Λεπτοκαρυών', + 'Λεπτοπόδων', + 'Λεσινίου', + 'Λευκάρων', + 'Λευκίμμης', + 'Λευκαδίων', + 'Λευκαδιτίου', + 'Λευκακίων', + 'Λευκασίου', + 'Λευκογείων', + 'Λευκοθέας', + 'Λευκοπηγής', + 'Λευκοτόπου', + 'Λευκοχωρίου', + 'Λευκοχώρας', + 'Λευκού', + 'Λευκόβρυσης', + 'Λευκών', + 'Λεχαίου', + 'Λεχαινών', + 'Λεχουρίου', + 'Λεχωνίων', + 'Λεχόβου', + 'Λεωνιδίου', + 'Λεύκας', + 'Λεύκης', + 'Λεύκτρων', + 'Λημερίου', + 'Ληνός', + 'Ληξουρίου', + 'Λητής', + 'Λιανοβεργίου', + 'Λιαπάδων', + 'Λιας', + 'Λιβαδίου', + 'Λιβαδίων', + 'Λιβαδακίου', + 'Λιβαδαρίου', + 'Λιβαδερού', + 'Λιβαδιάς', + 'Λιβαδοχωρίου', + 'Λιβανατών', + 'Λιβαρτζίου', + 'Λιβερών', + 'Λιγκιάδων', + 'Λιγορτύνου', + 'Λιγοψάς', + 'Λιδωρικίου', + 'Λιθίνου', + 'Λιθίου', + 'Λιθακιάς', + 'Λιθιάς', + 'Λιθινών', + 'Λιθοβουνίων', + 'Λιθοτόπου', + 'Λιθοχωρίου', + 'Λικνάδων', + 'Λιλαίας', + 'Λιλιανού', + 'Λιμένος Χερσονήσου', + 'Λιμίνης', + 'Λιμεναρίων', + 'Λιμνίτσης', + 'Λιμνιών', + 'Λιμνοτόπου', + 'Λιμνοχωρίου', + 'Λιμνών', + 'Λιναριάς', + 'Λινισταίνης', + 'Λιοδώρας', + 'Λιοπράσου', + 'Λιοσίων', + 'Λιπαρού', + 'Λιποχωρίου', + 'Λιρών', + 'Λισβορίου', + 'Λιτοσέλου', + 'Λιτοχώρου', + 'Λογγάδων', + 'Λογγάς', + 'Λογγάστρας', + 'Λογγιτσίου', + 'Λογγού', + 'Λογκανίκου', + 'Λογοθετιανίκων', + 'Λοξάδας', + 'Λουκά', + 'Λουκισίων', + 'Λουκομίου', + 'Λουρδάτων', + 'Λουρών', + 'Λουσακιών', + 'Λουσικών', + 'Λουσών', + 'Λουτουφίου', + 'Λουτρακίου', + 'Λουτρακίου Περαχώρας', + 'Λουτροπηγής', + 'Λουτροπόλεως Θερμής', + 'Λουτροπόλεως Μεθάνων', + 'Λουτροτόπου', + 'Λουτρού', + 'Λουτρού Λαρίσης', + 'Λουτρών', + 'Λουτρών Αιδηψού', + 'Λουτρών Ηραίας', + 'Λουτρών Υπάτης', + 'Λουτσίου', + 'Λουτσών', + 'Λοφίσκου', + 'Λοφαρίου', + 'Λοχριάς', + 'Λούβρης', + 'Λούβρου', + 'Λούμα', + 'Λούρου', + 'Λούτσας', + 'Λούτσης', + 'Λούχας', + 'Λυγαριάς', + 'Λυγερέα', + 'Λυγερής', + 'Λυγιά', + 'Λυγιάς', + 'Λυδίας', + 'Λυκίσσης', + 'Λυκαίου', + 'Λυκοβρύσεως', + 'Λυκοποριάς', + 'Λυκοσούρας', + 'Λυκοστόμου', + 'Λυκοτράφου', + 'Λυκουδίου', + 'Λυκουρίας', + 'Λυκοχίων', + 'Λυκούρεση', + 'Λυκόγιαννης', + 'Λυπουδεσίου', + 'Λυρκείας', + 'Λυσιμαχείας', + 'Λυσσαρέας', + 'Λυττού', + 'Λυχνού', + 'Λόγγου', + 'Λόφου', + 'Λόφων', + 'Λύγγου', + 'Λύκειον', + 'Λύρας', + 'Λύχνων', + 'Μάγειρα', + 'Μάζης', + 'Μάζιας', + 'Μάκρης', + 'Μάλεμε', + 'Μάλης', + 'Μάλθης', + 'Μάλτας', + 'Μάναρη', + 'Μάνδρας', + 'Μάνεση', + 'Μάνης', + 'Μάννα', + 'Μάννας', + 'Μάραθα', + 'Μάρθας', + 'Μάρκου', + 'Μάστρου', + 'Μάχου', + 'Μέγα Κάμπου', + 'Μέγα Πιστόν', + 'Μέρους', + 'Μέρωνα', + 'Μέσα Διδύμας', + 'Μέσα Λακκωνίων', + 'Μέσα Λασιθίου', + 'Μέσα Μουλιανών', + 'Μέση', + 'Μέσης', + 'Μέσης Συνοικίας Τρικάλων', + 'Μέσου Γερακαρίου', + 'Μήλου', + 'Μίλα', + 'Μίνας', + 'Μίνθης', + 'Μίστρου', + 'Μαγαζιών', + 'Μαγαρικαρίου', + 'Μαγγάνων', + 'Μαγγανίτου', + 'Μαγγανιακού', + 'Μαγικού', + 'Μαγνησίας', + 'Μαγουλάδων', + 'Μαγουλίτσης', + 'Μαγουλιάνων', + 'Μαγούλας', + 'Μαδένης', + 'Μαδύτου', + 'Μαζίου', + 'Μαζαράκι', + 'Μαζαρακίου', + 'Μαζαρακιάς', + 'Μαθίας', + 'Μαθιάς', + 'Μαθρακίου', + 'Μαινάλου', + 'Μακίστου', + 'Μακράδων', + 'Μακρίνου', + 'Μακρίσης', + 'Μακρακώμης', + 'Μακρινής', + 'Μακρινίτσης', + 'Μακρινούς', + 'Μακρισίων', + 'Μακρολιβάδου', + 'Μακροταντάλου', + 'Μακροχωρίου', + 'Μακρυγιάλου', + 'Μακρυκάπας', + 'Μακρυλιάς', + 'Μακρυπλαγίου', + 'Μακρυρράχης', + 'Μακρυσίου', + 'Μακρυχωρίου', + 'Μακρυωτίκων', + 'Μακυνείας', + 'Μαλάξας', + 'Μαλίων', + 'Μαλαθύρου', + 'Μαλακάσης', + 'Μαλακίων', + 'Μαλακασίου', + 'Μαλαμάτων', + 'Μαλανδρίνου', + 'Μαλαντρενίου', + 'Μαλγάρων', + 'Μαλεσίνης', + 'Μαλεσιάδας', + 'Μαλετιάνων', + 'Μαλλωτών', + 'Μαλουνίου', + 'Μαλυκρείου', + 'Μαλών', + 'Μαμουλάδας', + 'Μαμουσιάς', + 'Μαναγούλης', + 'Μανασσή', + 'Μανδάλου', + 'Μανδηλίου', + 'Μανδρακίου', + 'Μανδρινής', + 'Μανδρών', + 'Μανεσίου Καλαβρύτων', + 'Μανεσίου Πατρών', + 'Μανθυρέας', + 'Μανιάκων', + 'Μανιακίου', + 'Μανικίων', + 'Μανολατών', + 'Μανολιάσης', + 'Μανολιοπούλου', + 'Μανταμάδου', + 'Μαντασιάς', + 'Μαντείου', + 'Μαντζαρίου', + 'Μαντινείας', + 'Μαντουδίου', + 'Μαράθου', + 'Μαρίνης', + 'Μαρίου', + 'Μαραθέας', + 'Μαραθιά', + 'Μαραθιάς', + 'Μαραθοκάμπου', + 'Μαραθοπόλεως', + 'Μαραθούσσης', + 'Μαραντοχωρίου', + 'Μαρασίων', + 'Μαργαριτίου', + 'Μαργαριτών', + 'Μαργελίου', + 'Μαριολάτας', + 'Μαριού', + 'Μαριτσών', + 'Μαριών', + 'Μαρκινιάδας', + 'Μαρκοπούλου', + 'Μαρκοπούλου Μεσογαίας', + 'Μαρκοπούλου Ωρωπού', + 'Μαρμάρου', + 'Μαρμάρων', + 'Μαρμακέτου', + 'Μαρμαρά', + 'Μαρμαρίνης', + 'Μαρμαρίου', + 'Μαρουλά', + 'Μαρπήσσης', + 'Μαρτίνου', + 'Μαρωνίας', + 'Μαρωνείας', + 'Μασάρων', + 'Μασχολουρίου', + 'Ματίου', + 'Ματαράγκας', + 'Ματεσίου', + 'Ματονερίου', + 'Ματσουκίου', + 'Μαυράτων', + 'Μαυρίλου', + 'Μαυραναίων', + 'Μαυρατζαίων', + 'Μαυραχάδων', + 'Μαυρελίου', + 'Μαυρικίου', + 'Μαυριών', + 'Μαυροβάτου', + 'Μαυροβουνίου', + 'Μαυρογιάννη', + 'Μαυροδενδρίου', + 'Μαυροθαλάσσης', + 'Μαυροκάμπου', + 'Μαυροκκλησίου', + 'Μαυρολεύκης', + 'Μαυρολιθαρίου', + 'Μαυρολόφου', + 'Μαυρομμάτας', + 'Μαυρομματίου', + 'Μαυρομματίου Παμίσου', + 'Μαυρονερίου', + 'Μαυρονόρους', + 'Μαυροπηγής', + 'Μαυροπούλου', + 'Μαυρουδίου', + 'Μαυροχωρίου', + 'Μαυρούδας', + 'Μαχαιρά', + 'Μαχαιράδου', + 'Μαχαιρών', + 'Μεγάλης Βρύσης', + 'Μεγάλης Γότιστας', + 'Μεγάλης Δοξιπάρας', + 'Μεγάλης Κάψης', + 'Μεγάλης Κερασέας', + 'Μεγάλης Παναγίας', + 'Μεγάλης Στέρνας', + 'Μεγάλης Χώρας', + 'Μεγάλου Βάλτου', + 'Μεγάλου Γαρδικίου', + 'Μεγάλου Δουκάτου', + 'Μεγάλου Ελευθεροχωρίου', + 'Μεγάλου Ευυδρίου', + 'Μεγάλου Κεφαλοβρύσου', + 'Μεγάλου Μοναστηρίου', + 'Μεγάλου Περιστερίου', + 'Μεγάλου Σειρηνίου', + 'Μεγάλου Χωρίου', + 'Μεγάλων Καλυβίων', + 'Μεγάρου', + 'Μεγάρχης', + 'Μεγίστης', + 'Μεγαλοβρύσου', + 'Μεγαλοκάμπου', + 'Μεγαλοπόλεως', + 'Μεγαλοχωρίου', + 'Μεγαλόχαρης', + 'Μεγαπλατάνου', + 'Μεγαρέων', + 'Μεθώνης', + 'Μελά', + 'Μελάμπων', + 'Μελάνων', + 'Μελέτη', + 'Μελίας', + 'Μελίκης', + 'Μελίσσα', + 'Μελίσσης', + 'Μελίτης', + 'Μελανθίου', + 'Μελανιού', + 'Μελενικιτσίου', + 'Μελεσών', + 'Μελιάς', + 'Μελιανών', + 'Μελιβοίας', + 'Μελιγαλά', + 'Μελιγγών', + 'Μελιγούς', + 'Μελιδονίου', + 'Μελισσίου', + 'Μελισσίων', + 'Μελισσοκομείου', + 'Μελισσοπέτρας', + 'Μελισσοτόπου', + 'Μελισσουργακίου', + 'Μελισσουργού', + 'Μελισσουργών', + 'Μελισσοχωρίου', + 'Μελισσόπετρας', + 'Μελιτίνης', + 'Μελιταίας', + 'Μελπείας', + 'Μενδενίτσης', + 'Μενεμένης', + 'Μενετών', + 'Μενιδίου', + 'Μεξιατών', + 'Μεράς', + 'Μεριάς', + 'Μερκάδας', + 'Μερκοβουνίου', + 'Μερόπης', + 'Μεσαίας Κάψης', + 'Μεσαίου', + 'Μεσαγρού', + 'Μεσαναγρού', + 'Μεσαρίστης', + 'Μεσαριάς', + 'Μεσαριάς Άνδρου', + 'Μεσελέρων', + 'Μεσενικόλα', + 'Μεσημβρίας', + 'Μεσημερίου', + 'Μεσιάς', + 'Μεσιανής', + 'Μεσιανού', + 'Μεσινού', + 'Μεσκλών', + 'Μεσοβουνίου', + 'Μεσοβουνίων', + 'Μεσοβούνου', + 'Μεσογείου', + 'Μεσοκάμπου', + 'Μεσοκώμης', + 'Μεσολακκιάς', + 'Μεσολογγίου', + 'Μεσολουρίου', + 'Μεσολόγγου', + 'Μεσονησίου', + 'Μεσοποτάμου', + 'Μεσοποταμιάς', + 'Μεσοπύργου', + 'Μεσορράχης', + 'Μεσορρουγίου', + 'Μεσορόπης', + 'Μεσοτόπου', + 'Μεσοχωρίου', + 'Μεσοχωρίου Υπάτης', + 'Μεσοχωρίων', + 'Μεσοχώρας', + 'Μεσσήνης', + 'Μεστών', + 'Μετάλλων', + 'Μεταγκιτσίου', + 'Μεταμορφώσεως', + 'Μεταμόρφωσης', + 'Μεταξά', + 'Μεταξάδας', + 'Μεταξάδων', + 'Μεταξάτων', + 'Μεταξοχωρίου', + 'Μετοχίου', + 'Μετοχίου Διρφύων', + 'Μετοχίου Κηρέως', + 'Μετσόβου', + 'Μετόχιο Προδρόμου', + 'Μηθύμνης', + 'Μηλέα', + 'Μηλέας', + 'Μηλίνης', + 'Μηλίτσας', + 'Μηλίτσης', + 'Μηλεών', + 'Μηλιάς', + 'Μηλιανών', + 'Μηλιωτίου', + 'Μηλοχωρίου', + 'Μητάτου', + 'Μητάτων', + 'Μητροπόλεως', + 'Μητρουσίου', + 'Μηχανιώνας', + 'Μιαμούς', + 'Μιδέας', + 'Μικράς Γότιστας', + 'Μικράς Μαντινείας', + 'Μικροβάλτου', + 'Μικροθηβών', + 'Μικροκάμπου', + 'Μικροκάστρου', + 'Μικροκλεισούρας', + 'Μικρολίμνης', + 'Μικρολιβάδου', + 'Μικρομάνης', + 'Μικρομηλέας', + 'Μικροπόλεως', + 'Μικροσπηλιάς', + 'Μικροχωρίου', + 'Μικρού Βάλτου', + 'Μικρού Βουνού', + 'Μικρού Δάσους', + 'Μικρού Δερείου', + 'Μικρού Μοναστηρίου', + 'Μικρού Περιβολακίου', + 'Μικρού Περιστερίου', + 'Μικρού Ποντιά', + 'Μικρού Σουλίου', + 'Μικρού Χωρίου', + 'Μικρόν Πιστόν', + 'Μιλάτου', + 'Μιλλιαράδων', + 'Μιντιλογλίου', + 'Μιράνων', + 'Μιραλίου', + 'Μιστεγνών', + 'Μιτοπόλεως', + 'Μιχαλιτσίου', + 'Μιχοΐου', + 'Μοίρας', + 'Μοδίου', + 'Μοιρών', + 'Μολάων', + 'Μολίστης', + 'Μολυβδοσκεπάστου', + 'Μολόχας', + 'Μονής', + 'Μοναστηρίου', + 'Μοναστηρακίου', + 'Μοναχιτίου', + 'Μονεμβασίας', + 'Μονοδενδρίου', + 'Μονοδρύου', + 'Μονοκαρυάς', + 'Μονοκκλησιάς', + 'Μονολίθου', + 'Μονολιθίου', + 'Μονοπολάτων', + 'Μονοσπίτων', + 'Μονόβρυσης', + 'Μοραΐτικων', + 'Μορονίου', + 'Μορφοβουνίου', + 'Μοσιάς', + 'Μοσχάτου', + 'Μοσχοκαρυάς', + 'Μοσχοποτάμου', + 'Μοσχοφύτου', + 'Μοσχοχωρίου', + 'Μουδανιών', + 'Μουζίλου', + 'Μουζακίου', + 'Μουζακαίων', + 'Μουζακαιίκων', + 'Μουζουρά', + 'Μουλίων', + 'Μουλιανών', + 'Μουλκίου', + 'Μουρεσίου', + 'Μουριάς', + 'Μουριατάδας', + 'Μουρικίου', + 'Μουριών', + 'Μουρνές', + 'Μουρνιών', + 'Μουσάτων', + 'Μουσθένης', + 'Μουσιωτίτσης', + 'Μουσουνίτσης', + 'Μουσούρων', + 'Μοχού', + 'Μούδρου', + 'Μούντρου', + 'Μπάφρας', + 'Μπαμπίνης', + 'Μπαμπαλιού', + 'Μπαουσιών', + 'Μπατσίου', + 'Μπελοκομίτης', + 'Μπενιτσών', + 'Μπεστιάς', + 'Μπιζανίου', + 'Μποζικά', + 'Μπολατίου', + 'Μπουλαριών', + 'Μποχάλης', + 'Μπράλου', + 'Μπόρσα', + 'Μπόρσιον', + 'Μυγδαλιάς', + 'Μυκηνών', + 'Μυκονίων', + 'Μυλοποτάμου', + 'Μυλοτόπου', + 'Μυξόρρουμα', + 'Μυρίκης', + 'Μυρίνης', + 'Μυριναίων', + 'Μυριοκεφάλων', + 'Μυριοφύτου', + 'Μυρκίνου', + 'Μυρμηγκίου', + 'Μυροδάφνης', + 'Μυροφύλλου', + 'Μυρρίνης', + 'Μυρσίνης', + 'Μυρσινοχωρίου', + 'Μυρτέας', + 'Μυρτιάς', + 'Μυρτιδίων', + 'Μυρτουντίων', + 'Μυρτοφύτου', + 'Μυρωδάτου', + 'Μυρωνίων', + 'Μυρόβρυσης', + 'Μυστρά', + 'Μυτιλήνης', + 'Μυτιληνιών', + 'Μυχού', + 'Μόριας', + 'Μόρφης', + 'Μύθων', + 'Μύκης', + 'Μύλων', + 'Μύρθιου', + 'Μύρου', + 'Μύρτου', + 'Μύρων', + 'Μύστακας', + 'Μύτικα', + 'Μώλου', + 'Ν.Κερασιάς', + 'Νάξου', + 'Νάπης', + 'Νέα Σάντα', + 'Νίκης', + 'Νίπους', + 'Νίψης', + 'Ναμάτων', + 'Ναούσης', + 'Ναρθακίου', + 'Ναρκίσσου', + 'Νασίων', + 'Ναυπάκτου', + 'Ναυπακτίας', + 'Ναυπλιέων', + 'Νεάπολης', + 'Νεαπόλεως', + 'Νεγάδων', + 'Νεγράδων', + 'Νεδούσης', + 'Νεμέας', + 'Νεμούτας', + 'Νενήτων', + 'Νενητουρίων', + 'Νεοκάστρου', + 'Νεοκαισαρείας', + 'Νεοχωρίου', + 'Νεοχωρακίου', + 'Νεοχωροπούλου', + 'Νεοχωρούδας', + 'Νεράιδας', + 'Νεράντζης', + 'Νεραντζιών', + 'Νεραϊδοχωρίου', + 'Νεριανών', + 'Νεροκούρου', + 'Νερομάννας', + 'Νερομύλου', + 'Νερομύλων', + 'Νεροτριβιάς', + 'Νεροφράκτου', + 'Νεροχωρίου', + 'Νεστάνης', + 'Νεστορίου', + 'Νευροκοπίου', + 'Νεύρα', + 'Νησίου', + 'Νησακίου', + 'Νιάτων', + 'Νιγρίτης', + 'Νιθαύρεως', + 'Νικήσιανης', + 'Νικήτης', + 'Νικαίας', + 'Νικηθιανού', + 'Νικηταί', + 'Νικηφόρου', + 'Νικιών', + 'Νικοκλείας', + 'Νικολή', + 'Νικολαιίκων', + 'Νικολιτσίου', + 'Νικομηδείας', + 'Νικομηδινού', + 'Νικοπόλεως', + 'Νικοτσάρας', + 'Νικόπολης', + 'Νιπιδιτού', + 'Νιφοραιίκων', + 'Νομής', + 'Νομίων', + 'Νομιτσή', + 'Νοστίμου', + 'Νοτίας', + 'Νοχιών', + 'Ντερέ', + 'Νυβρίτου', + 'Νυδρίου', + 'Νυμφίου', + 'Νυμφαίου', + 'Νυμφασίας', + 'Νυμφοπέτρας', + 'Νυμφών', + 'Νυφίου', + 'Ξάνθης', + 'Ξαμουδοχωρίου', + 'Ξανθάτων', + 'Ξανθοχωρίου', + 'Ξενιάκου', + 'Ξενιών', + 'Ξενοπούλου', + 'Ξεριά', + 'Ξεχασμένης', + 'Ξεχώρου', + 'Ξηροκάμπου', + 'Ξηροκαμπίου', + 'Ξηροκαριταίνης', + 'Ξηρολίμνης', + 'Ξηρολόφου', + 'Ξηρονομής', + 'Ξηροπηγάδου', + 'Ξηροποτάμου', + 'Ξηροστερνίου', + 'Ξηροχωρίου', + 'Ξινονερίου', + 'Ξινού Νερού', + 'Ξινόβρυσης', + 'Ξιφιανής', + 'Ξορυχτίου', + 'Ξυλαγανής', + 'Ξυλικών', + 'Ξυλοκάστρου', + 'Ξυλοκέρας', + 'Ξυλοκερίζης', + 'Ξυλοκερατέας', + 'Ξυλοπαροίκου', + 'Ξυλοπόλεως', + 'Οάσεως', + 'Οίας', + 'Οίτης', + 'Οβριάς', + 'Οθωνών', + 'Οινουσσών', + 'Οινοφύτων', + 'Οινοχωρίου', + 'Οινούσσας', + 'Οινόης', + 'Οιτύλου', + 'Οιχαλίας', + 'Οκτωνιάς', + 'Ολβίου', + 'Ολύμπου', + 'Ολύμπων', + 'Ολύνθου', + 'Ομαλής', + 'Ομαλών', + 'Ομβριακής', + 'Ομηρικόν', + 'Ομολίου', + 'Ομορφοκκλησιάς', + 'Ομορφοχωρίου', + 'Οξυάς', + 'Οξυλίθου', + 'Οξυνείας', + 'Ορίου', + 'Οργάνης', + 'Ορεινής', + 'Ορεινού', + 'Ορεινού Ξηροβάλτου', + 'Ορθέ', + 'Ορθοβουνίου', + 'Ορθονιών', + 'Ορθουνίου', + 'Ορμενίου', + 'Ορμυλίας', + 'Ορνές', + 'Οροπεδίου', + 'Ορφανίου', + 'Ορφανών', + 'Ορχομενού', + 'Ουρανοπόλεως', + 'Οφρυνίου', + 'Οχθίων', + 'Οχυρού', + 'Πάγου', + 'Πάγων', + 'Πάδων', + 'Πάου', + 'Πάπαρη', + 'Πάργας', + 'Πάρου', + 'Πάστρας', + 'Πάτμου', + 'Πέλεκα', + 'Πέλλης', + 'Πέντε Εκκλησιών', + 'Πέπλου', + 'Πέρα Μελάνων', + 'Πέραν Τριοβασάλου', + 'Πέρδικας', + 'Πέρκου', + 'Πέρνης', + 'Πέτα', + 'Πέτρα', + 'Πέτρας', + 'Παγκαλοχωρίου', + 'Παγκρατίου', + 'Παγκρατών', + 'Παγονερίου', + 'Παγουριών', + 'Παγώνδου', + 'Παγώντα', + 'Παιανίας', + 'Πακίων', + 'Παλαίρου', + 'Παλαίστρας', + 'Παλαιάς Γιαννιτσούς', + 'Παλαιάς Καβάλας', + 'Παλαιάς Φωκαίας', + 'Παλαικάστρου', + 'Παλαιοβαρβασαίνης', + 'Παλαιοβράχας', + 'Παλαιοκάστρου', + 'Παλαιοκήπου', + 'Παλαιοκαρυάς', + 'Παλαιοκατούνας', + 'Παλαιοκατούνου', + 'Παλαιοκερασέας', + 'Παλαιοκκλησίου', + 'Παλαιοκώμης', + 'Παλαιομανίνας', + 'Παλαιομοναστήρου', + 'Παλαιοξαρίου', + 'Παλαιοπαναγίας', + 'Παλαιοπόλεως', + 'Παλαιοπύργου', + 'Παλαιοσελλίου', + 'Παλαιοχούνης', + 'Παλαιοχωρίου', + 'Παλαιοχωρίου Δωριέων', + 'Παλαιοχωρίου Μπότσαρη', + 'Παλαιοχωρίου Σιράκου', + 'Παλαιοχωρίου Τυμφρηστού', + 'Παλαιοχωρακίου', + 'Παλαιοχώρας', + 'Παλαιού Αγιονερίου', + 'Παλαιού Ελευθεροχωρίου', + 'Παλαιού Κεραμιδίου', + 'Παλαιού Λουτρού', + 'Παλαιού Μυλοτόπου', + 'Παλαιού Σκυλλιτσίου', + 'Παλαιού Φαλήρου', + 'Παλαιφύτου', + 'Παλαιόβρυσης', + 'Παλαιόστανης', + 'Παλαιών Ρουμάτων', + 'Παλαμά', + 'Παλαμαρίου', + 'Παλαμπά', + 'Παλατίων', + 'Παλατιτσίων', + 'Παλιαμπέλων', + 'Παλιουρίου', + 'Παλιουριάς', + 'Παλιούρα', + 'Παλιούρης', + 'Παλλήνης', + 'Παλλαντίου', + 'Παλούμπας', + 'Παμφίλων', + 'Παμφίου', + 'Πανάσου', + 'Παναγίας', + 'Παναγίτσας', + 'Παναγιούδας', + 'Παναγούλας', + 'Παναιτωλίου', + 'Παναρίτη', + 'Παναριτίου', + 'Πανδρόσου', + 'Πανεθήμου', + 'Πανιπερίου', + 'Πανουργιά', + 'Παντανάσσης', + 'Πανόρμου', + 'Παπάγου', + 'Παπίγκου', + 'Παπαδιανίκων', + 'Παπαφλέσσα', + 'Παππά', + 'Παππάδου', + 'Παππάδων', + 'Παππαγιάννη', + 'Παππαγιαννάδων', + 'Παππαδάτου', + 'Παππαδατών', + 'Παππαδιανών', + 'Παππαρουσίου', + 'Παππουλίων', + 'Παραβόλας', + 'Παραδείσου', + 'Παραδεισίου', + 'Παραδεισίων', + 'Παρακαλάμου', + 'Παρακοίλων', + 'Παραλία Μέσης', + 'Παραλίας', + 'Παραλίας Πλατάνου', + 'Παραλίου Άστρους', + 'Παραλιμνίου', + 'Παραλογγών', + 'Παραμέρου', + 'Παραμυθίας', + 'Παρανεστίου', + 'Παρανύμφων', + 'Παραποτάμου', + 'Παραπουγκίου', + 'Παρασκευής', + 'Παρδαλίτσης', + 'Παρθενίου', + 'Παρορίου', + 'Παρορείου', + 'Παρπαριάς', + 'Παρτίρων', + 'Πασίου', + 'Πασαλιτών', + 'Παστίδας', + 'Πασχαλίτσης', + 'Πασχαλιάς', + 'Πατερμά', + 'Πατιοπούλου', + 'Πατουλιάς', + 'Πατρέων', + 'Πατρικάτων', + 'Πατρικίου', + 'Πατρικών', + 'Πατσιανού', + 'Πατσιδερού', + 'Πατσού', + 'Παυλιάνας', + 'Παυλοπούλου', + 'Παχείας Άμμου', + 'Παχτουρίου', + 'Παχυκαλάμου', + 'Παϊδοχωρίου', + 'Παύλιανης', + 'Παύλιας', + 'Παύλου', + 'Πεδινής', + 'Πεδινού', + 'Πεδινών', + 'Πεζούλας', + 'Πεζών', + 'Πεθελινού', + 'Πειραιώς', + 'Πελάγους', + 'Πελαγίας', + 'Πελαργού', + 'Πελασγίας', + 'Πελεκάνου', + 'Πελεκανάδας', + 'Πελετών', + 'Πελλάνας', + 'Πελλήνης', + 'Πελοπίου', + 'Πελόπης', + 'Πεμονίων', + 'Πεντέλης', + 'Πενταβρύσου', + 'Πενταγιών', + 'Πεντακόρφου', + 'Πενταλόφου', + 'Πενταμοδίου', + 'Πενταπόλεως', + 'Πεντατίου', + 'Πεντεορίων', + 'Πεντολάκκου', + 'Πεπονιάς', + 'Περάμα', + 'Περάμου', + 'Περάνθης', + 'Περάτη', + 'Περίου', + 'Περίστης', + 'Περαίας', + 'Περατάτων', + 'Περατιάς', + 'Περαχωρίου', + 'Περβολακίων', + 'Περδίκκα', + 'Περδικίου', + 'Περδικακίου', + 'Περδικονερίου', + 'Περδικόβρυσης', + 'Περθωρίου', + 'Περιβλέπτου', + 'Περιβολίου', + 'Περιβολίου Δομοκού', + 'Περιβολίων', + 'Περιβολίων Κισσάμου', + 'Περιβολίων Κυδωνίας', + 'Περιβολακίου', + 'Περιβολακίων', + 'Περιγιαλίου', + 'Περιθείας', + 'Περιθιωτίσσης', + 'Περιθωρίου', + 'Περικλείας', + 'Περιστάσεως', + 'Περιστέρας', + 'Περιστεράς', + 'Περιστερίου', + 'Περιστερώνας', + 'Περιχώρας', + 'Περουλάδων', + 'Περσαίνης', + 'Περτουλίου', + 'Πεσάδας', + 'Πεστών', + 'Πεταλείας', + 'Πεταλιδίου', + 'Πετουσίου', + 'Πετράδων', + 'Πετρίλου', + 'Πετρίνας', + 'Πετρίνου', + 'Πετρίου', + 'Πετραίας', + 'Πετραλώνων', + 'Πετρανών', + 'Πετριτής', + 'Πετριτσίου', + 'Πετριών', + 'Πετροβίτσας', + 'Πετροβούνιον', + 'Πετροκεράσων', + 'Πετροκεφάλου', + 'Πετροκεφαλίου', + 'Πετροπηγής', + 'Πετροπόρου', + 'Πετροχωρίου', + 'Πετρούπολης', + 'Πετρούσσης', + 'Πετρωτού', + 'Πετρωτών', + 'Πετρών', + 'Πετρώνας', + 'Πετσάκων', + 'Πετσαλίου', + 'Πευκοδάσους', + 'Πευκοφύτου', + 'Πευκοχωρίου', + 'Πεύκης', + 'Πεύκου', + 'Πεύκων', + 'Πηγής', + 'Πηγαδίου', + 'Πηγαδίτσης', + 'Πηγαδίων', + 'Πηγαδακίων', + 'Πηγαδησάνων', + 'Πηγαδούλια', + 'Πηγαϊδακίων', + 'Πηγών', + 'Πηδάσου', + 'Πηλίου', + 'Πιάνας', + 'Πιαλείας', + 'Πικέρνη', + 'Πικερμίου', + 'Πιλαλίστρας', + 'Πινακατών', + 'Πινακοχωρίου', + 'Πιπερίτσης', + 'Πιπεριών', + 'Πιραμάς', + 'Πισίων', + 'Πισκοκεφάλου', + 'Πισοδερίου', + 'Πιστιανών', + 'Πιτίτσης', + 'Πιτροφού', + 'Πιτσίου', + 'Πιτσιδίων', + 'Πιτσιναιίκων', + 'Πιτσιωτών', + 'Πιτσών', + 'Πλάκας', + 'Πλάνου', + 'Πλάτης', + 'Πλάτσης', + 'Πλαγίων', + 'Πλαγιά', + 'Πλαγιάς', + 'Πλαγιαρίου', + 'Πλαγιών', + 'Πλαισίου', + 'Πλαισίων Μαλακασίου', + 'Πλακάδου', + 'Πλακίδας', + 'Πλακωτής', + 'Πλανητέρου', + 'Πλατάνας', + 'Πλατάνης', + 'Πλατάνου', + 'Πλαταιών', + 'Πλατανίου', + 'Πλατανίων', + 'Πλατανακίου', + 'Πλατανακίων', + 'Πλατανιά', + 'Πλατανιάς', + 'Πλατανιστού', + 'Πλατανιωτίσσης', + 'Πλατανοτόπου', + 'Πλατανούσσης', + 'Πλατανόβρυσης', + 'Πλαταριάς', + 'Πλατιάνας', + 'Πλατρειθιά', + 'Πλατυβόλας', + 'Πλατυκάμπου', + 'Πλατυστόμου', + 'Πλατυστόμων', + 'Πλεμενιανών', + 'Πληκατίου', + 'Πλουτοχωρίου', + 'Πλωμαρίου', + 'Πλώρας', + 'Πογωνίας', + 'Ποδογοράς', + 'Ποδοχωρίου', + 'Ποιμενικού', + 'Ποκίστης', + 'Πολίχνης', + 'Πολεμαρχίου', + 'Πολιανής', + 'Πολιτικών', + 'Πολιχνίτου', + 'Πολοβίτσης', + 'Πολυάνθου', + 'Πολυανέμου', + 'Πολυγύρου', + 'Πολυδένδρου', + 'Πολυδαμείου', + 'Πολυδενδρίου', + 'Πολυδρόσου', + 'Πολυδώρου', + 'Πολυθέας', + 'Πολυκάρπης', + 'Πολυκάστρου', + 'Πολυκαρπίου', + 'Πολυκαστάνου', + 'Πολυκεράσου', + 'Πολυλάκκου', + 'Πολυλόφου', + 'Πολυμύλου', + 'Πολυνέρου', + 'Πολυνερίου', + 'Πολυπέτρου', + 'Πολυπλατάνου', + 'Πολυποτάμου', + 'Πολυρράχου', + 'Πολυρρηνίας', + 'Πολυσίτου', + 'Πολυσταφύλου', + 'Πολυστύλου', + 'Πολυφύτου', + 'Πολυχρόνου', + 'Ποντικατών', + 'Ποντινής', + 'Ποντισμένου', + 'Ποντοηρακλείας', + 'Ποντοκερασέας', + 'Ποντοκώμης', + 'Ποντολιβάδου', + 'Ποροΐων', + 'Ποροβίτσης', + 'Πορτής', + 'Πορτίτσης', + 'Πορταριάς', + 'Πορτιανού', + 'Πορτοχελίου', + 'Πορτών', + 'Ποσειδωνίας', + 'Ποτάμων', + 'Ποταμίδας', + 'Ποταμιά', + 'Ποταμιάς', + 'Ποταμιών', + 'Ποταμού', + 'Ποταμούλας Μεσολογγίου', + 'Ποταμών', + 'Ποτειδαίας', + 'Ποτιδάνειας', + 'Ποτιστικών', + 'Πουγκακίων', + 'Πουλάτων', + 'Πουλίθρων', + 'Πουλιτσίου', + 'Πουλλίτσης', + 'Πουλλακίδας', + 'Πουρίου', + 'Πουρναρίου', + 'Πουρναριάς', + 'Πουρνιάς', + 'Πούρνου', + 'Πρίνας', + 'Πρίνου', + 'Πραγγίου', + 'Πραγματευτή', + 'Πραισού', + 'Πραιτωρίου', + 'Πραιτωρίων', + 'Πραμάντων', + 'Πρασέ', + 'Πρασίνου', + 'Πρασιάς', + 'Πρασιδακίου', + 'Πρασινάδας', + 'Πρασιών', + 'Πραστού', + 'Πρεβέζης', + 'Πρινέ', + 'Πρινιά', + 'Πριολίθου', + 'Προαστίου', + 'Προβατά', + 'Προδρομίου', + 'Προδρόμου', + 'Προκοπίου', + 'Προμάχων', + 'Προμυρίου', + 'Προσβόρρου', + 'Προσηλίου', + 'Προσηλίων', + 'Προσκυνά', + 'Προσκυνητών', + 'Προσοτσάνης', + 'Προσύμνης', + 'Προυσού', + 'Προφήτη Ηλία', + 'Προφήτης Ηλίας', + 'Προφήτου', + 'Προφήτου Ηλία', + 'Προφήτου Ηλιού', + 'Προφίλιας', + 'Πρωτοκκλησίου', + 'Πρωτοχωρίου', + 'Πρωτόπαππα', + 'Πρώτης', + 'Πτέρης', + 'Πτελέας', + 'Πτελέας Πλατανιάς', + 'Πτελεού', + 'Πτελοπούλας', + 'Πτεριάς', + 'Πυθίου', + 'Πυθαγορείου', + 'Πυλίου', + 'Πυλαίας', + 'Πυλωρίου', + 'Πυλωρών', + 'Πυλών', + 'Πυξαρίου', + 'Πυράς', + 'Πυργέλλας', + 'Πυργίου', + 'Πυργαδικίων', + 'Πυργακίου', + 'Πυργετού', + 'Πυργιωτίκων', + 'Πυργούς', + 'Πυρρή', + 'Πυρρίχου', + 'Πυρσόγιαννης', + 'Πωγωνιανής', + 'Πόδου', + 'Πόμπιας', + 'Πόρου', + 'Πόρπη', + 'Πόρων', + 'Πύδνας', + 'Πύλας', + 'Πύλης', + 'Πύλου', + 'Πύργου', + 'Πύργου Διρού', + 'Πύργου Ιθώμης', + 'Πύργου Καλαμών', + 'Πύργου Καλλίστης', + 'Πύργου Κιερίου', + 'Πύργου Τριφυλίας', + 'Πύργων', + 'Πύργων Θερμής', + 'Πύρρας', + 'Ράδου', + 'Ράμιας', + 'Ράξας', + 'Ράφτη', + 'Ράχη', + 'Ράχης', + 'Ρίγανης', + 'Ρίζης', + 'Ρίζου', + 'Ρίου', + 'Ραΐκου', + 'Ραβδούχας', + 'Ραβενής', + 'Ραβενίων', + 'Ραγάδα', + 'Ραγίου', + 'Ραδοβιζίου', + 'Ραιδεστού', + 'Ραμνής', + 'Ραπτοπούλου', + 'Ραφήνας', + 'Ραφταναίων', + 'Ραχούλας', + 'Ραχτάδων', + 'Ραχωνίου', + 'Ραχών', + 'Ραχώνας', + 'Ραψάνης', + 'Ραψομμάτη', + 'Ρεγκινίου', + 'Ρεθίου', + 'Ρεθύμνης', + 'Ρειχέας', + 'Ρεντίνας', + 'Ρεπανιδίου', + 'Ρεπετίστης', + 'Ρετσίνων', + 'Ρετσιανών', + 'Ρευματιάς', + 'Ρητίνης', + 'Ριαχόβου', + 'Ριγανίου', + 'Ριγκλίων', + 'Ριζίων', + 'Ριζαρίου', + 'Ριζοβουνίου', + 'Ριζομύλου', + 'Ριζοσπηλιάς', + 'Ριζού', + 'Ριζωμάτων', + 'Ριζών', + 'Ριφίου', + 'Ριόλου', + 'Ροβίων', + 'Ροβιάτας', + 'Ροβιών', + 'Ροβολιαρίου', + 'Ρογιτίκων', + 'Ρογών', + 'Ροδίτου', + 'Ροδίτσης', + 'Ροδακίνου', + 'Ροδαυγής', + 'Ροδιάς', + 'Ροδιανής', + 'Ροδινών', + 'Ροδοβανίου', + 'Ροδοδάφνης', + 'Ροδολίβους', + 'Ροδοπόλεως', + 'Ροδοτοπίου', + 'Ροδοχωρίου', + 'Ροδωνιάς', + 'Ροδωπού', + 'Ροεινού', + 'Ρομιρίου', + 'Ροποτού', + 'Ροσκάς', + 'Ρουμελής', + 'Ρουπακίου', + 'Ρουπακιάς', + 'Ρουσσοπουλίου', + 'Ρουσσοσπιτίου', + 'Ρουστίκων', + 'Ρουτσίου', + 'Ρουφά', + 'Ρουψιάς', + 'Ρούσσας Εκκλησίας', + 'Ρούσσου', + 'Ρυακίου', + 'Ρυακίων', + 'Ρυζιών', + 'Ρυμνίου', + 'Ρυσίου', + 'Ρωμαιίκου', + 'Ρωμανού', + 'Ρωμιάς', + 'Ρόδου', + 'Ρόδων', + 'Ρόκκας', + 'Σάγκα', + 'Σάλπης', + 'Σάμης', + 'Σάντας', + 'Σάρτης', + 'Σάρχου', + 'Σέκουλα', + 'Σέμπρωνα', + 'Σέρβου', + 'Σέσκλου', + 'Σέτας', + 'Σίβα', + 'Σίβας', + 'Σίδερης', + 'Σίλης', + 'Σίμου', + 'Σίνδου', + 'Σίτσαινα', + 'Σαβαλίων', + 'Σαγαιίκων', + 'Σαγιάδας', + 'Σαγκρίου', + 'Σακτουρίων', + 'Σαλάκου', + 'Σαλμενίκου', + 'Σαλμώνης', + 'Σαλονίκης', + 'Σαμίων', + 'Σαμαρίνης', + 'Σαμικού', + 'Σαμοθράκης', + 'Σαμονίδας', + 'Σαμπά', + 'Σαντομερίου', + 'Σανών', + 'Σαπουνακαίϊκων', + 'Σαπών', + 'Σαραβαλίου', + 'Σαρακήνας', + 'Σαρακηνάδου', + 'Σαρακηνών', + 'Σαρακινίου', + 'Σαρακινίου Ηραίας', + 'Σαρανταπήχου', + 'Σαρανταπόρου', + 'Σαργιάδας', + 'Σαρδινίων', + 'Σαρδών', + 'Σαρκίνης', + 'Σασάλου', + 'Σατρών', + 'Σαϊδόνας', + 'Σαϊτουρών', + 'Σβορωνάτων', + 'Σβορώνου', + 'Σγουράδων', + 'Σγουροκεφαλίου', + 'Σεβαστής', + 'Σεβαστιανών', + 'Σεβαστού', + 'Σειρών', + 'Σελέρου', + 'Σελίνου', + 'Σελεγουδίου', + 'Σελευκείας', + 'Σεληνίων', + 'Σελιάνας', + 'Σελιανιτίκων', + 'Σελλά', + 'Σελλάδων', + 'Σελλίου', + 'Σελλίων', + 'Σελλασίας', + 'Σελλών', + 'Σενίκου', + 'Σερίφου', + 'Σερβίων', + 'Σερβιανών', + 'Σερβωτών', + 'Σεργούλας', + 'Σεριζιανών', + 'Σερνικακίου', + 'Σερρών', + 'Σημάντρου', + 'Σημάντρων', + 'Σηρικαρίου', + 'Σησαμίας', + 'Σητείας', + 'Σιάμου', + 'Σιάνων', + 'Σιατίστης', + 'Σιβίστης', + 'Σιγουνίου', + 'Σιγρίου', + 'Σιδήρων', + 'Σιδαρίου', + 'Σιδερά', + 'Σιδηράδες', + 'Σιδηροκάστρου', + 'Σιδηρονέρου', + 'Σιδηροχωρίου', + 'Σικίνου', + 'Σιλάτων', + 'Σιλίμνης', + 'Σιμίζα', + 'Σιμιάδων', + 'Σιμοπούλου', + 'Σιναράδων', + 'Σινεβρού', + 'Σινιών', + 'Σινώπης', + 'Σιριλίου', + 'Σισανίου', + 'Σιστρουνίου', + 'Σισών', + 'Σιταίνης', + 'Σιταγρών', + 'Σιταρά', + 'Σιταραλώνων', + 'Σιταριάς', + 'Σιτομένων', + 'Σιτοχωρίου', + 'Σιτοχώρου', + 'Σκάλας', + 'Σκάλας Ωρωπού', + 'Σκάλωμα', + 'Σκάφης', + 'Σκήτης', + 'Σκαδού', + 'Σκαλανίου', + 'Σκαλοχωρίου', + 'Σκαλωτής', + 'Σκαμνακίου', + 'Σκαμνελλίου', + 'Σκανδάλου', + 'Σκανδαλίου', + 'Σκαρφείας', + 'Σκαφιδακίου', + 'Σκαφιδιάς', + 'Σκαφιδωτής', + 'Σκεπαρίου', + 'Σκεπαστής', + 'Σκεπαστού', + 'Σκιάδα', + 'Σκιάθου', + 'Σκιαδά', + 'Σκιλλουντίας', + 'Σκινέ', + 'Σκινέως', + 'Σκινιά', + 'Σκιώνης', + 'Σκλήθρου', + 'Σκλίβανης', + 'Σκλίβας', + 'Σκλαβοπούλας', + 'Σκληρού', + 'Σκοπέλου', + 'Σκοπής', + 'Σκοπιάς', + 'Σκοπού', + 'Σκορτσινού', + 'Σκοτάνης', + 'Σκοτίνης', + 'Σκοτεινής', + 'Σκοτούσσης', + 'Σκουληκάδου', + 'Σκουληκαριάς', + 'Σκουλουφίων', + 'Σκουραιίκων', + 'Σκουρβούλων', + 'Σκουροχωρίου', + 'Σκουρτούς', + 'Σκουτάρεως', + 'Σκουτάρου', + 'Σκουταρίου', + 'Σκουτεράς', + 'Σκουτεσιάδας', + 'Σκούπας', + 'Σκούρα', + 'Σκούρας', + 'Σκούρτων', + 'Σκρα', + 'Σκριπερού', + 'Σκύδρας', + 'Σκύρου', + 'Σμέρνας', + 'Σμέρτου', + 'Σμίλας', + 'Σμίξης', + 'Σμαρίου', + 'Σμυρτιάς', + 'Σμύρνης', + 'Σοκαρά', + 'Σολακίου', + 'Σολομού', + 'Σοπίου', + 'Σορωνής', + 'Σουδεναιίκων', + 'Σουλίου', + 'Σουλαρίου', + 'Σουληναρίου', + 'Σουλλάρων', + 'Σουλοπούλου', + 'Σουνίου', + 'Σουρωτής', + 'Σουστιάνων', + 'Σουφλίου', + 'Σοφάδων', + 'Σοφιάδας', + 'Σοφιανών', + 'Σοφικού', + 'Σοφικό', + 'Σοχού', + 'Σούγιας', + 'Σούδας', + 'Σούλου', + 'Σούρπης', + 'Σπάθαρη', + 'Σπάρτου', + 'Σπάτων-Λούτσας', + 'Σπήλιου', + 'Σπαθάδων', + 'Σπαθαρίου', + 'Σπαθαραίων', + 'Σπανοχωρίου', + 'Σπαρτιά', + 'Σπαρτιάς', + 'Σπαρτιατών', + 'Σπαρτιών', + 'Σπαρτοχωρίου', + 'Σπαρτύλα', + 'Σπερχογείας', + 'Σπετσών', + 'Σπηλίου', + 'Σπηλαίου', + 'Σπηλαίων', + 'Σπηλιάς', + 'Σπιταλίου', + 'Σπολαίτης', + 'Σπόθων', + 'Σπόων', + 'Στάβλων', + 'Στάθη', + 'Στάνου', + 'Στέρνας', + 'Στίβου', + 'Στίλιας', + 'Στίρφακας', + 'Σταβιών', + 'Σταγίρων', + 'Σταγιατών', + 'Σταδίου', + 'Σταθά', + 'Σταθμού Αγγίστης', + 'Σταθμού Μουριών', + 'Σταλού', + 'Σταμάτας', + 'Σταματινού', + 'Σταμνάς', + 'Στανού', + 'Σταροχωρίου', + 'Στασίμου', + 'Στασιού', + 'Σταυρακίου', + 'Σταυρακίων', + 'Σταυρινήδων', + 'Σταυροδρομίου', + 'Σταυροπηγίου', + 'Σταυροσκιαδίου', + 'Σταυρουπόλεως', + 'Σταυροχωρίου', + 'Σταυρού', + 'Σταυρωμένου', + 'Σταφιδοκάμπου', + 'Στειρίου', + 'Στεμνίτσης', + 'Στενής', + 'Στενημάχου', + 'Στενιών', + 'Στενού', + 'Στενυκλάρου', + 'Στερνών', + 'Στεφάνης', + 'Στεφανίου', + 'Στεφανιάς', + 'Στεφανινών', + 'Στεφανοβικείου', + 'Στεφανοβούνου', + 'Στιμάγκας', + 'Στομίου', + 'Στουππαίων', + 'Στουρναραιίκων', + 'Στράτου', + 'Στρίγκου', + 'Στρανώμης', + 'Στρατινίστης', + 'Στρατονίκης', + 'Στρατωνίου', + 'Στρεφίου', + 'Στροβλών', + 'Στρογγυλής', + 'Στρογγυλοβουνίου', + 'Στροπώνων', + 'Στρουσίου', + 'Στροφή', + 'Στροφυλιάς', + 'Στρυμονικού', + 'Στρυμονοχωρίου', + 'Στρόμης', + 'Στρύμης', + 'Στυλάριον', + 'Στυλίων', + 'Στυμφαλίας', + 'Στόλου', + 'Στόλων', + 'Στύλιας', + 'Στύλου', + 'Στύρων', + 'Στύψης', + 'Συβότων', + 'Συγκρέλλου', + 'Συκά Υπάτης', + 'Συκέας', + 'Συκής', + 'Συκαμίνου', + 'Συκαμινέας', + 'Συκεών', + 'Συκιάδας', + 'Συκολόγου', + 'Συκορράχης', + 'Συκουρίου', + 'Συλιβαινιώτικων', + 'Συμβολής', + 'Συνδένδρου', + 'Συνετίου', + 'Συνοικίας Τρικάλων', + 'Συρράκου', + 'Συρρίζου', + 'Σφάκας', + 'Σφακερών', + 'Σφακοπηγαδίου', + 'Σφελινού', + 'Σφενδαμίου', + 'Σφηκιάς', + 'Σφηνωτού', + 'Σχίνων', + 'Σχηματαρίου', + 'Σχινοκαψάλων', + 'Σχινοχωρίου', + 'Σχοινούσσης', + 'Σχολαρίου', + 'Σωκρακίου', + 'Σωληναρίου', + 'Σωσάνδρας', + 'Σωστίου', + 'Σωτήρας', + 'Σωταίνης', + 'Σωτηρίου', + 'Σωτηρίτσης', + 'Σωτηριανίκων', + 'Σύβρου', + 'Σύμης', + 'Σύρνας', + 'Σύρου', + 'Σώστης', + 'Τέμενης', + 'Τήνου', + 'Ταγαράδων', + 'Τακτικουπόλεως', + 'Ταλάντων', + 'Τανάγρας', + 'Ταξιάρχου', + 'Ταξιαρχών', + 'Ταρσινών', + 'Ταρσού', + 'Ταυρωνίτου', + 'Ταύρου', + 'Τειχίου', + 'Τεμενίων', + 'Τεμπών', + 'Τενέδου', + 'Τεριαχίου', + 'Τερπνής', + 'Τερπύλλου', + 'Τερψιθέας', + 'Τερόβου', + 'Τετρακώμου', + 'Τετραλόφου', + 'Τεφελίου', + 'Τζίβα', + 'Τζερμιάδου', + 'Τζιτζιφέ', + 'Τιθορέας', + 'Τιθρωνίου', + 'Τιτάνης', + 'Τοιχίου', + 'Τολού', + 'Τοξοτών', + 'Τοπολίων', + 'Τοπολιάνων', + 'Τουλιάτων', + 'Τουρκολέκα', + 'Τουρλάδας', + 'Τουρλωτής', + 'Τούμπας', + 'Τρίκαστρον', + 'Τρίτους', + 'Τραγάνας', + 'Τραγίλου', + 'Τραγακίου', + 'Τραγανού', + 'Τρανοβάλτου', + 'Τραπέζης', + 'Τραπεζίτσης', + 'Τραπεζαντής', + 'Τραχήλας', + 'Τραχειάς', + 'Τραχηλίου', + 'Τρεχλού', + 'Τριανδρίας', + 'Τριαντάρου', + 'Τριανταφυλλέας', + 'Τριανταφυλλιάς', + 'Τριβούνου', + 'Τριγλίας', + 'Τριγωνικού', + 'Τριδένδρου', + 'Τριζονίων', + 'Τρικάλων', + 'Τρικερίου', + 'Τρικκαίων', + 'Τρικλίνου', + 'Τρικοκκιάς', + 'Τρικορύφου', + 'Τρικόρφου', + 'Τρικώμου', + 'Τριλόφου', + 'Τριοβασάλου', + 'Τριποτάμου', + 'Τριποταμιάς', + 'Τριπόλεως', + 'Τριπύλας', + 'Τριστένου', + 'Τριταίας', + 'Τριφυλλίου', + 'Τριχωνίου', + 'Τριόδου', + 'Τροβάτου', + 'Τροπαίων', + 'Τροπαιούχου', + 'Τρυπητής', + 'Τρυπών', + 'Τρωιανάτων', + 'Τρύγονα', + 'Τρύπης', + 'Τρύφου', + 'Τσάκονης', + 'Τσάκων', + 'Τσαγγαρίου', + 'Τσαγκαράδας', + 'Τσαγκαροπούλου', + 'Τσαμαντά', + 'Τσαπουρνιάς', + 'Τσαριτσάνης', + 'Τσελεπάκου', + 'Τσεπελόβου', + 'Τσερίων', + 'Τσικαλαριών', + 'Τσικκαλιών', + 'Τσιμανδρίων', + 'Τσιπιανών', + 'Τσιταλίων', + 'Τσοτυλίου', + 'Τσουκαλάδων', + 'Τσουκαλαιίκων', + 'Τσούκκας', + 'Τυλίσου', + 'Τυμπακίου', + 'Τυμφρηστού', + 'Τυρνάβου', + 'Τυρολόης', + 'Τυρού', + 'Τυχερού', + 'Τόρνου', + 'Υαμείας', + 'Υδρούσσης', + 'Υμηττού', + 'Υπάτης', + 'Υπάτου', + 'Υπερείας', + 'Υστερνίων', + 'Υψηλάντου', + 'Υψηλής Ράχης', + 'Υψηλομετώπου', + 'Υψηλού Χωρίου', + 'Φάρου', + 'Φάρσων', + 'Φήκης', + 'Φίλια', + 'Φίλιας', + 'Φαβατάτων', + 'Φαλάνθης', + 'Φαλάννης', + 'Φαλαισίας', + 'Φαλατάδου', + 'Φαλελιανών', + 'Φαμίλας', + 'Φαναρίου', + 'Φανερωμένης', + 'Φανού', + 'Φανών', + 'Φαράκλας', + 'Φαραγγίου', + 'Φαρακλάδας', + 'Φαρακλάτων', + 'Φαρακλού', + 'Φαρσάλων', + 'Φαρών', + 'Φασκομηλιάς', + 'Φελλίου', + 'Φελλού', + 'Φενεού', + 'Φερών', + 'Φιγαλείας', + 'Φιδακίων', + 'Φιλίας', + 'Φιλίππων', + 'Φιλίων', + 'Φιλαδελφίου', + 'Φιλαδελφείας', + 'Φιλιατρών', + 'Φιλιατών', + 'Φιλιππαίων', + 'Φιλλύρα', + 'Φιλοθέης', + 'Φιλοτίου', + 'Φιλυρίας', + 'Φιλωτείας', + 'Φιλύρας', + 'Φιλύρου', + 'Φιλώτα', + 'Φιολίτη', + 'Φισίνης', + 'Φισκάρδου', + 'Φιχτίου', + 'Φλαμουριάς', + 'Φλαμπουραρίου', + 'Φλαμπουρεσίου', + 'Φλαμπούρου', + 'Φλαμπούρων', + 'Φλατσίων', + 'Φλογητών', + 'Φλωρίνης', + 'Φλόκα', + 'Φλόκας', + 'Φοινίκης', + 'Φοινικίου', + 'Φολεγάνδρου', + 'Φολόης', + 'Φοναϊτίκων', + 'Φορτοσίου', + 'Φουντωτού', + 'Φουρνάς', + 'Φουρνέ', + 'Φουρνής', + 'Φουρφουρά', + 'Φούρκας', + 'Φούρνων', + 'Φούστανης', + 'Φούφα', + 'Φράγκας', + 'Φράγκου', + 'Φρίξης', + 'Φραγκάδων', + 'Φραγκουλαιίκων', + 'Φραντάτου', + 'Φραντζή', + 'Φραντζεσκιανών Μετοχίων', + 'Φρατσίων', + 'Φρε', + 'Φρεγκαίνης', + 'Φριλιγκιανίκων', + 'Φροσύνης', + 'Φρουσιούνας', + 'Φτέρης', + 'Φτελιάς', + 'Φτερνού', + 'Φυλάκης', + 'Φυλής', + 'Φυλακής', + 'Φυλακίου', + 'Φυλακτής', + 'Φυλακτού', + 'Φυτείας', + 'Φυτειών', + 'Φυτών', + 'Φωκαίας', + 'Φωλεάς', + 'Φωσταίνης', + 'Φωτάδας', + 'Φωτεινού', + 'Φωτεινών', + 'Φωτολίβους', + 'Φόδελε', + 'Φύλλου', + 'Φύλλων', + 'Φύσκας', + 'Χάλκης', + 'Χέρσου', + 'Χίνκας', + 'Χίου', + 'Χαβαρίου', + 'Χαβδάτων', + 'Χαβριάτων', + 'Χαιρεθιανών', + 'Χαιρωνείας', + 'Χαλάνδρων', + 'Χαλάρων', + 'Χαλάστρας', + 'Χαλαζονίου', + 'Χαλανδρίου', + 'Χαλανδρίτσης', + 'Χαλικίου', + 'Χαλικίου Αμβρακίας', + 'Χαλιωτάτων', + 'Χαλκείου', + 'Χαλκερού', + 'Χαλκιά', + 'Χαλκιάδων', + 'Χαλκιδέων', + 'Χαλκιοπούλων', + 'Χαμαλευρίου', + 'Χαμεζίου', + 'Χανίων', + 'Χανδρά', + 'Χανδρινού', + 'Χανιώτη', + 'Χαράδρου', + 'Χαράς', + 'Χαράσου', + 'Χαραδιατίκων', + 'Χαρακίου', + 'Χαρακοπίου', + 'Χαραυγής', + 'Χαριάς', + 'Χαριέσσης', + 'Χαριτωμένης', + 'Χαρκίων', + 'Χαροκόπιον', + 'Χαροπού', + 'Χατζή', + 'Χαϊδαρίου', + 'Χαϊκαλίου', + 'Χειμάρρου', + 'Χειμαδιού', + 'Χειμερινού', + 'Χειμωνίου', + 'Χελιδονίου', + 'Χελυδορέου', + 'Χερσονήσου', + 'Χιδήρων', + 'Χιλιοδένδρου', + 'Χιλιομοδίου', + 'Χιονάδου', + 'Χιονάδων', + 'Χιονάτων', + 'Χιράδων', + 'Χιόνας', + 'Χλοματιανών', + 'Χλομού', + 'Χολαργού', + 'Χορηγού', + 'Χορτάτων', + 'Χορτερού', + 'Χορτιάτη', + 'Χουδετσίου', + 'Χουλιαράδων', + 'Χουμερίου', + 'Χουμεριάκου', + 'Χουμνικού', + 'Χουστουλιανών', + 'Χούνης', + 'Χράνων', + 'Χρισσού', + 'Χριστιανουπόλεως', + 'Χριστού', + 'Χρομοναστηρίου', + 'Χρούσων', + 'Χρυσάφων', + 'Χρυσής', + 'Χρυσανθίου', + 'Χρυσαυγής', + 'Χρυσοβίτσας', + 'Χρυσοβίτσης', + 'Χρυσοβεργίου', + 'Χρυσοβιτσίου', + 'Χρυσοκάστρου', + 'Χρυσοκελλαριάς', + 'Χρυσοκεφάλου', + 'Χρυσομηλέας', + 'Χρυσοπέτρας', + 'Χρυσοπηγής', + 'Χρυσορράχης', + 'Χρυσοστόμου', + 'Χρυσουπόλεως', + 'Χρυσοχωράφων', + 'Χρυσοχωρίου', + 'Χρυσού', + 'Χρωμίου', + 'Χρύσως', + 'Χωματάδας', + 'Χωρέμη', + 'Χωρίου', + 'Χωρίου Αποκορρώνου', + 'Χωρίου Κυδωνίας', + 'Χωρδακίου', + 'Χωρεπισκόπων', + 'Χωριστής', + 'Χωρυγίου', + 'Χωσιαρίου', + 'Χωστιά', + 'Χωτούσσης', + 'Χόβολης', + 'Χόικας', + 'Χόμορης', + 'Χόνδρου', + 'Χόχλιας', + 'Χώνου', + 'Χώρας', + 'Χώρας Σφακίων', + 'Ψάκας', + 'Ψήνας', + 'Ψίνθου', + 'Ψαθογιάννου', + 'Ψαθοπύργου', + 'Ψαθοτοπίου', + 'Ψαράδων', + 'Ψαρίου', + 'Ψαρών', + 'Ψαχνών', + 'Ψηλής Βρύσης', + 'Ψηλοβράχου', + 'Ψιανών', + 'Ψυχικού', + 'Ψυχρού', + 'Ωλένης', + 'Ωραίου', + 'Ωραιοκάστρου', + 'Ωρεών', + 'Ωριάς', + 'Ωρολογίου', + 'Ωρωπού', + 'Όθους', + 'Όρμης', + 'Όρμου Κορθίου', + 'Όρους', + 'Όσσης', + 'Όχθιας', + 'Ύδρας', + ) diff --git a/testbed/joke2k__faker/faker/providers/address/en/__init__.py b/testbed/joke2k__faker/faker/providers/address/en/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7078be3ef1f044f9a217d48b3c80c0db366c0607 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en/__init__.py @@ -0,0 +1,53 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + countries = ( + 'Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola', 'Anguilla', + 'Antarctica (the territory South of 60 deg S)', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', + 'Australia', 'Austria', 'Azerbaijan', + 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', + 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island (Bouvetoya)', 'Brazil', + 'British Indian Ocean Territory (Chagos Archipelago)', 'British Virgin Islands', 'Brunei Darussalam', + 'Bulgaria', 'Burkina Faso', 'Burundi', + 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Cayman Islands', 'Central African Republic', 'Chad', 'Chile', + 'China', 'Christmas Island', 'Cocos (Keeling) Islands', 'Colombia', 'Comoros', 'Congo', 'Congo', 'Cook Islands', + 'Costa Rica', 'Cote d\'Ivoire', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', + 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', + 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', + 'Faroe Islands', 'Falkland Islands (Malvinas)', 'Fiji', 'Finland', 'France', 'French Guiana', + 'French Polynesia', 'French Southern Territories', + 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', + 'Guam', 'Guatemala', 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', + 'Haiti', 'Heard Island and McDonald Islands', 'Holy See (Vatican City State)', 'Honduras', 'Hong Kong', + 'Hungary', + 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Isle of Man', 'Israel', 'Italy', + 'Jamaica', 'Japan', 'Jersey', 'Jordan', + 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea', 'Korea', 'Kuwait', 'Kyrgyz Republic', + 'Lao People\'s Democratic Republic', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libyan Arab Jamahiriya', + 'Liechtenstein', 'Lithuania', 'Luxembourg', + 'Macao', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', + 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', + 'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', + 'Namibia', 'Nauru', 'Nepal', 'Netherlands Antilles', 'Netherlands', 'New Caledonia', 'New Zealand', 'Nicaragua', + 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'Northern Mariana Islands', 'Norway', + 'Oman', + 'Pakistan', 'Palau', 'Palestinian Territory', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', + 'Pitcairn Islands', 'Poland', 'Portugal', 'Puerto Rico', + 'Qatar', + 'Reunion', 'Romania', 'Russian Federation', 'Rwanda', + 'Saint Barthelemy', 'Saint Helena', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin', + 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', + 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia (Slovak Republic)', + 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands', + 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Svalbard & Jan Mayen Islands', 'Swaziland', 'Sweden', 'Switzerland', + 'Syrian Arab Republic', + 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', + 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands', 'Tuvalu', + 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States of America', + 'United States Minor Outlying Islands', 'United States Virgin Islands', 'Uruguay', 'Uzbekistan', + 'Vanuatu', 'Venezuela', 'Vietnam', + 'Wallis and Futuna', 'Western Sahara', + 'Yemen', + 'Zambia', 'Zimbabwe', + ) diff --git a/testbed/joke2k__faker/faker/providers/address/en_AU/__init__.py b/testbed/joke2k__faker/faker/providers/address/en_AU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..854ace870ba93be2601ef905bae3fa05ef9b6a43 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en_AU/__init__.py @@ -0,0 +1,138 @@ +from ..en import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_prefixes = ('North', 'East', 'West', 'South', 'New', 'Lake', 'Port', + 'St.') + + city_suffixes = ('town', 'ton', 'land', 'ville', 'berg', 'burgh', + 'borough', 'bury', 'view', 'port', 'mouth', 'stad', + 'furt', 'chester', 'mouth', 'fort', 'haven', 'side', + 'shire') + + building_number_formats = ('###', '##', '#') + + street_suffixes = ( + 'Access', 'Alley', 'Alleyway', 'Amble', 'Anchorage', 'Approach', + 'Arcade', 'Artery', 'Avenue', 'Basin', 'Beach', 'Bend', 'Block', + 'Boulevard', 'Brace', 'Brae', 'Break', 'Bridge', 'Broadway', 'Brow', + 'Bypass', 'Byway', 'Causeway', 'Centre', 'Centreway', 'Chase', + 'Circle', 'Circlet', 'Circuit', 'Circus', 'Close', 'Colonnade', + 'Common', 'Concourse', 'Copse', 'Corner', 'Corso', 'Court', + 'Courtyard', 'Cove', 'Crescent', 'Crest', 'Cross', 'Crossing', + 'Crossroad', 'Crossway', 'Cruiseway', 'Cul-de-sac', 'Cutting', 'Dale', + 'Dell', 'Deviation', 'Dip', 'Distributor', 'Drive', 'Driveway', 'Edge', + 'Elbow', 'End', 'Entrance', 'Esplanade', 'Estate', 'Expressway', + 'Extension', 'Fairway', 'Fire Track', 'Firetrail', 'Flat', 'Follow', + 'Footway', 'Foreshore', 'Formation', 'Freeway', 'Front', 'Frontage', + 'Gap', 'Garden', 'Gardens', 'Gate', 'Gates', 'Glade', 'Glen', 'Grange', + 'Green', 'Ground', 'Grove', 'Gully', 'Heights', 'Highroad', 'Highway', + 'Hill', 'Interchange', 'Intersection', 'Junction', 'Key', 'Landing', + 'Lane', 'Laneway', 'Lees', 'Line', 'Link', 'Little', 'Lookout', 'Loop', + 'Lower', 'Mall', 'Meander', 'Mew', 'Mews', 'Motorway', 'Mount', 'Nook', + 'Outlook', 'Parade', 'Park', 'Parklands', 'Parkway', 'Part', 'Pass', + 'Path', 'Pathway', 'Piazza', 'Place', 'Plateau', 'Plaza', 'Pocket', + 'Point', 'Port', 'Promenade', 'Quad', 'Quadrangle', 'Quadrant', 'Quay', + 'Quays', 'Ramble', 'Ramp', 'Range', 'Reach', 'Reserve', 'Rest', + 'Retreat', 'Ride', 'Ridge', 'Ridgeway', 'Right Of Way', 'Ring', 'Rise', + 'River', 'Riverway', 'Riviera', 'Road', 'Roads', 'Roadside', 'Roadway', + 'Ronde', 'Rosebowl', 'Rotary', 'Round', 'Route', 'Row', 'Rue', 'Run', + 'Service Way', 'Siding', 'Slope', 'Sound', 'Spur', 'Square', 'Stairs', + 'State Highway', 'Steps', 'Strand', 'Street', 'Strip', 'Subway', + 'Tarn', 'Terrace', 'Thoroughfare', 'Tollway', 'Top', 'Tor', 'Towers', + 'Track', 'Trail', 'Trailer', 'Triangle', 'Trunkway', 'Turn', + 'Underpass', 'Upper', 'Vale', 'Viaduct', 'View', 'Villas', 'Vista', + 'Wade', 'Walk', 'Walkway', 'Way', 'Wynd') + + postcode_formats = ( + # as per https://en.wikipedia.org/wiki/Postcodes_in_Australia + # NSW + '1###', + '20##', + '21##', + '22##', + '23##', + '24##', + '25##', + '2619', + '262#', + '263#', + '264#', + '265#', + '266#', + '267#', + '268#', + '269#', + '27##', + '28##', + '292#', + '293#', + '294#', + '295#', + '296#', + '297#', + '298#', + '299#', + # ACT + '02##', + '260#', + '261#', + '290#', + '291#', + '2920', + # VIC + '3###', + '8###', + # QLD + '4###', + '9###', + # SA + '5###', + # WA + '6###', + # TAS + '7###', + # NT + '08##', + '09##', + ) + + states = ('Australian Capital Territory', 'New South Wales', + 'Northern Territory', 'Queensland', 'South Australia', + 'Tasmania', 'Victoria', 'Western Australia') + + states_abbr = ('ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA') + + city_formats = ('{{city_prefix}} {{first_name}}{{city_suffix}}', + '{{city_prefix}} {{first_name}}', + '{{first_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}') + + street_name_formats = ('{{first_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}') + + street_address_formats = ( + '{{building_number}} {{street_name}}', + '{{secondary_address}}\n {{building_number}} {{street_name}}', + ) + + address_formats = ( + "{{street_address}}\n{{city}}, {{state_abbr}}, {{postcode}}", ) + + secondary_address_formats = ('Apt. ###', 'Flat ##', 'Suite ###', 'Unit ##', + 'Level #', '### /', '## /', '# /') + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def state(self): + return self.random_element(self.states) + + def state_abbr(self): + return self.random_element(self.states_abbr) diff --git a/testbed/joke2k__faker/faker/providers/address/en_CA/__init__.py b/testbed/joke2k__faker/faker/providers/address/en_CA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a13f73845458acff885b505e0fc9474643bf2523 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en_CA/__init__.py @@ -0,0 +1,371 @@ +import re + +from ..en import Provider as AddressProvider + + +class Provider(AddressProvider): + + # Source: https://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1449294 + # + # 'W' and 'Z' are valid in non-initial position (easily verified in the + # wild), but online official documentation is hard to find, so just ignore + # them for now. + postal_code_letters = ( + 'A', 'B', 'C', 'E', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', + 'T', 'V', 'X', 'Y', + ) + + city_prefixes = ('North', 'East', 'West', 'South', 'New', 'Lake', 'Port') + + city_suffixes = ( + 'town', + 'ton', + 'land', + 'ville', + 'berg', + 'burgh', + 'borough', + 'bury', + 'view', + 'port', + 'mouth', + 'stad', + 'furt', + 'chester', + 'mouth', + 'fort', + 'haven', + 'side', + 'shire') + + building_number_formats = ('#####', '####', '###') + + street_suffixes = ( + 'Alley', + 'Avenue', + 'Branch', + 'Bridge', + 'Brook', + 'Brooks', + 'Burg', + 'Burgs', + 'Bypass', + 'Camp', + 'Canyon', + 'Cape', + 'Causeway', + 'Center', + 'Centers', + 'Circle', + 'Circles', + 'Cliff', + 'Cliffs', + 'Club', + 'Common', + 'Corner', + 'Corners', + 'Course', + 'Court', + 'Courts', + 'Cove', + 'Coves', + 'Creek', + 'Crescent', + 'Crest', + 'Crossing', + 'Crossroad', + 'Curve', + 'Dale', + 'Dam', + 'Divide', + 'Drive', + 'Drive', + 'Drives', + 'Estate', + 'Estates', + 'Expressway', + 'Extension', + 'Extensions', + 'Fall', + 'Falls', + 'Ferry', + 'Field', + 'Fields', + 'Flat', + 'Flats', + 'Ford', + 'Fords', + 'Forest', + 'Forge', + 'Forges', + 'Fork', + 'Forks', + 'Fort', + 'Freeway', + 'Garden', + 'Gardens', + 'Gateway', + 'Glen', + 'Glens', + 'Green', + 'Greens', + 'Grove', + 'Groves', + 'Harbor', + 'Harbors', + 'Haven', + 'Heights', + 'Highway', + 'Hill', + 'Hills', + 'Hollow', + 'Inlet', + 'Inlet', + 'Island', + 'Island', + 'Islands', + 'Islands', + 'Isle', + 'Isle', + 'Junction', + 'Junctions', + 'Key', + 'Keys', + 'Knoll', + 'Knolls', + 'Lake', + 'Lakes', + 'Land', + 'Landing', + 'Lane', + 'Light', + 'Lights', + 'Loaf', + 'Lock', + 'Locks', + 'Locks', + 'Lodge', + 'Lodge', + 'Loop', + 'Mall', + 'Manor', + 'Manors', + 'Meadow', + 'Meadows', + 'Mews', + 'Mill', + 'Mills', + 'Mission', + 'Mission', + 'Motorway', + 'Mount', + 'Mountain', + 'Mountain', + 'Mountains', + 'Mountains', + 'Neck', + 'Orchard', + 'Oval', + 'Overpass', + 'Park', + 'Parks', + 'Parkway', + 'Parkways', + 'Pass', + 'Passage', + 'Path', + 'Pike', + 'Pine', + 'Pines', + 'Place', + 'Plain', + 'Plains', + 'Plains', + 'Plaza', + 'Plaza', + 'Point', + 'Points', + 'Port', + 'Port', + 'Ports', + 'Ports', + 'Prairie', + 'Prairie', + 'Radial', + 'Ramp', + 'Ranch', + 'Rapid', + 'Rapids', + 'Rest', + 'Ridge', + 'Ridges', + 'River', + 'Road', + 'Road', + 'Roads', + 'Roads', + 'Route', + 'Row', + 'Rue', + 'Run', + 'Shoal', + 'Shoals', + 'Shore', + 'Shores', + 'Skyway', + 'Spring', + 'Springs', + 'Springs', + 'Spur', + 'Spurs', + 'Square', + 'Square', + 'Squares', + 'Squares', + 'Station', + 'Station', + 'Stravenue', + 'Stravenue', + 'Stream', + 'Stream', + 'Street', + 'Street', + 'Streets', + 'Summit', + 'Summit', + 'Terrace', + 'Throughway', + 'Trace', + 'Track', + 'Trafficway', + 'Trail', + 'Trail', + 'Tunnel', + 'Tunnel', + 'Turnpike', + 'Turnpike', + 'Underpass', + 'Union', + 'Unions', + 'Valley', + 'Valleys', + 'Via', + 'Viaduct', + 'View', + 'Views', + 'Village', + 'Village', + 'Villages', + 'Ville', + 'Vista', + 'Vista', + 'Walk', + 'Walks', + 'Wall', + 'Way', + 'Ways', + 'Well', + 'Wells') + + postal_code_formats = ('?%? %?%', '?%?%?%') + + provinces = ( + 'Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', + 'Newfoundland and Labrador', 'Northwest Territories', + 'Nova Scotia', 'Nunavut', 'Ontario', + 'Prince Edward Island', 'Quebec', 'Saskatchewan', 'Yukon Territory') + + provinces_abbr = ( + 'AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', + 'NU', 'ON', 'PE', 'QC', 'SK', 'YT') + + provinces_postcode_prefixes = { + 'NL': ['A'], 'NS': ['B'], 'PE': ['C'], 'NB': ['E'], + 'QC': ['G', 'H', 'J'], 'ON': ['K', 'L', 'M', 'N', 'P'], + 'MB': ['R'], 'SK': ['S'], 'AB': ['T'], 'BC': ['V'], + 'NU': ['X'], 'NT': ['X'], 'YT': ['Y'], + } + + city_formats = ( + '{{city_prefix}} {{first_name}}{{city_suffix}}', + '{{city_prefix}} {{first_name}}', + '{{first_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + ) + street_name_formats = ( + '{{first_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + ) + street_address_formats = ( + '{{building_number}} {{street_name}}', + '{{building_number}} {{street_name}} {{secondary_address}}', + ) + address_formats = ( + "{{street_address}}\n{{city}}, {{province_abbr}} {{postalcode}}", + ) + secondary_address_formats = ('Apt. ###', 'Suite ###') + + def province(self): + """ + """ + return self.random_element(self.provinces) + + def province_abbr(self): + return self.random_element(self.provinces_abbr) + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def postal_code_letter(self): + """ + Returns a random letter from the list of allowable + letters in a canadian postal code + """ + return self.random_element(self.postal_code_letters) + + def _postcode_replace(self, postal_code_format): + """ + Replaces all question mark ('?') occurrences with a random letter + from given postal_code_format, then passes result to numerify to insert + numbers + """ + temp = re.sub(r'\?', + lambda x: self.postal_code_letter(), + postal_code_format) + return self.numerify(temp) + + def postcode(self): + """ + Returns a random postcode + """ + return self._postcode_replace( + self.random_element(self.postal_code_formats)) + + def postcode_in_province(self, province_abbr=None): + """ + Returns a random postcode within the provided province abbreviation + """ + if province_abbr is None: + province_abbr = self.random_element(self.provinces_abbr) + + if province_abbr in self.provinces_abbr: + postal_code_format = self.random_element(self.postal_code_formats) + postal_code_format = postal_code_format.replace( + '?', + self.generator.random_element( + self.provinces_postcode_prefixes[province_abbr]), + 1) + return self._postcode_replace(postal_code_format) + else: + raise Exception('Province Abbreviation not found in list') + + def postalcode_in_province(self, province_abbr=None): + return self.postcode_in_province(province_abbr) + + def postalcode(self): + return self.postcode() diff --git a/testbed/joke2k__faker/faker/providers/address/en_GB/__init__.py b/testbed/joke2k__faker/faker/providers/address/en_GB/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9bc758bac4f9218fcf190f60cd30e1eab2f08986 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en_GB/__init__.py @@ -0,0 +1,331 @@ +from collections import OrderedDict + +from ..en import Provider as AddressProvider + + +class Provider(AddressProvider): + city_prefixes = ('North', 'East', 'West', 'South', 'New', 'Lake', 'Port') + city_suffixes = ( + 'town', + 'ton', + 'land', + 'ville', + 'berg', + 'burgh', + 'borough', + 'bury', + 'view', + 'port', + 'mouth', + 'stad', + 'furt', + 'chester', + 'mouth', + 'fort', + 'haven', + 'side', + 'shire', + ) + building_number_formats = ('#', '##', '###') + street_suffixes = ( + 'alley', + 'avenue', + 'branch', + 'bridge', + 'brook', + 'brooks', + 'burg', + 'burgs', + 'bypass', + 'camp', + 'canyon', + 'cape', + 'causeway', + 'center', + 'centers', + 'circle', + 'circles', + 'cliff', + 'cliffs', + 'club', + 'common', + 'corner', + 'corners', + 'course', + 'court', + 'courts', + 'cove', + 'coves', + 'creek', + 'crescent', + 'crest', + 'crossing', + 'crossroad', + 'curve', + 'dale', + 'dam', + 'divide', + 'drive', + 'drive', + 'drives', + 'estate', + 'estates', + 'expressway', + 'extension', + 'extensions', + 'fall', + 'falls', + 'ferry', + 'field', + 'fields', + 'flat', + 'flats', + 'ford', + 'fords', + 'forest', + 'forge', + 'forges', + 'fork', + 'forks', + 'fort', + 'freeway', + 'garden', + 'gardens', + 'gateway', + 'glen', + 'glens', + 'green', + 'greens', + 'grove', + 'groves', + 'harbor', + 'harbors', + 'haven', + 'heights', + 'highway', + 'hill', + 'hills', + 'hollow', + 'inlet', + 'inlet', + 'island', + 'island', + 'islands', + 'islands', + 'isle', + 'isle', + 'junction', + 'junctions', + 'key', + 'keys', + 'knoll', + 'knolls', + 'lake', + 'lakes', + 'land', + 'landing', + 'lane', + 'light', + 'lights', + 'loaf', + 'lock', + 'locks', + 'locks', + 'lodge', + 'lodge', + 'loop', + 'mall', + 'manor', + 'manors', + 'meadow', + 'meadows', + 'mews', + 'mill', + 'mills', + 'mission', + 'mission', + 'motorway', + 'mount', + 'mountain', + 'mountain', + 'mountains', + 'mountains', + 'neck', + 'orchard', + 'oval', + 'overpass', + 'park', + 'parks', + 'parkway', + 'parkways', + 'pass', + 'passage', + 'path', + 'pike', + 'pine', + 'pines', + 'place', + 'plain', + 'plains', + 'plains', + 'plaza', + 'plaza', + 'point', + 'points', + 'port', + 'port', + 'ports', + 'ports', + 'prairie', + 'prairie', + 'radial', + 'ramp', + 'ranch', + 'rapid', + 'rapids', + 'rest', + 'ridge', + 'ridges', + 'river', + 'road', + 'road', + 'roads', + 'roads', + 'route', + 'row', + 'rue', + 'run', + 'shoal', + 'shoals', + 'shore', + 'shores', + 'skyway', + 'spring', + 'springs', + 'springs', + 'spur', + 'spurs', + 'square', + 'square', + 'squares', + 'squares', + 'station', + 'station', + 'stravenue', + 'stravenue', + 'stream', + 'stream', + 'street', + 'street', + 'streets', + 'summit', + 'summit', + 'terrace', + 'throughway', + 'trace', + 'track', + 'trafficway', + 'trail', + 'trail', + 'tunnel', + 'tunnel', + 'turnpike', + 'turnpike', + 'underpass', + 'union', + 'unions', + 'valley', + 'valleys', + 'via', + 'viaduct', + 'view', + 'views', + 'village', + 'village', + 'villages', + 'ville', + 'vista', + 'vista', + 'walk', + 'walks', + 'wall', + 'way', + 'ways', + 'well', + 'wells') + + POSTAL_ZONES = ( + 'AB', 'AL', 'B', 'BA', 'BB', 'BD', 'BH', 'BL', 'BN', 'BR', + 'BS', 'BT', 'CA', 'CB', 'CF', 'CH', 'CM', 'CO', 'CR', 'CT', + 'CV', 'CW', 'DA', 'DD', 'DE', 'DG', 'DH', 'DL', 'DN', 'DT', + 'DY', 'E', 'EC', 'EH', 'EN', 'EX', 'FK', 'FY', 'G', 'GL', + 'GY', 'GU', 'HA', 'HD', 'HG', 'HP', 'HR', 'HS', 'HU', 'HX', + 'IG', 'IM', 'IP', 'IV', 'JE', 'KA', 'KT', 'KW', 'KY', 'L', + 'LA', 'LD', 'LE', 'LL', 'LN', 'LS', 'LU', 'M', 'ME', 'MK', + 'ML', 'N', 'NE', 'NG', 'NN', 'NP', 'NR', 'NW', 'OL', 'OX', + 'PA', 'PE', 'PH', 'PL', 'PO', 'PR', 'RG', 'RH', 'RM', 'S', + 'SA', 'SE', 'SG', 'SK', 'SL', 'SM', 'SN', 'SO', 'SP', 'SR', + 'SS', 'ST', 'SW', 'SY', 'TA', 'TD', 'TF', 'TN', 'TQ', 'TR', + 'TS', 'TW', 'UB', 'W', 'WA', 'WC', 'WD', 'WF', 'WN', 'WR', + 'WS', 'WV', 'YO', 'ZE', + ) + + POSTAL_ZONES_ONE_CHAR = [zone for zone in POSTAL_ZONES if len(zone) == 1] + POSTAL_ZONES_TWO_CHARS = [zone for zone in POSTAL_ZONES if len(zone) == 2] + + postcode_formats = ( + 'AN NEE', + 'ANN NEE', + 'PN NEE', + 'PNN NEE', + 'ANC NEE', + 'PND NEE', + ) + + _postcode_sets = OrderedDict(( + (' ', ' '), + ('N', [str(i) for i in range(0, 10)]), + ('A', POSTAL_ZONES_ONE_CHAR), + ('B', 'ABCDEFGHKLMNOPQRSTUVWXY'), + ('C', 'ABCDEFGHJKSTUW'), + ('D', 'ABEHMNPRVWXY'), + ('E', 'ABDEFGHJLNPQRSTUWXYZ'), + ('P', POSTAL_ZONES_TWO_CHARS), + )) + + city_formats = ( + '{{city_prefix}} {{first_name}}{{city_suffix}}', + '{{city_prefix}} {{first_name}}', + '{{first_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + ) + street_name_formats = ( + '{{first_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + ) + street_address_formats = ( + '{{building_number}} {{street_name}}', + '{{secondary_address}}\n{{street_name}}', + ) + address_formats = ( + "{{street_address}}\n{{city}}\n{{postcode}}", + ) + secondary_address_formats = ( + 'Flat #', 'Flat ##', 'Flat ##?', 'Studio #', 'Studio ##', 'Studio ##?') + + def postcode(self): + """ + See + http://web.archive.org/web/20090930140939/http://www.govtalk.gov.uk/gdsc/html/noframes/PostCode-2-1-Release.htm + """ + postcode = '' + pattern = self.random_element(self.postcode_formats) + for placeholder in pattern: + postcode += self.random_element(self._postcode_sets[placeholder]) + return postcode + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def secondary_address(self): + return self.bothify(self.random_element(self.secondary_address_formats)) diff --git a/testbed/joke2k__faker/faker/providers/address/en_NZ/__init__.py b/testbed/joke2k__faker/faker/providers/address/en_NZ/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..60e92b116de8f2bd8fc405a648e1de12f6d6b3ca --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en_NZ/__init__.py @@ -0,0 +1,252 @@ +from ..en import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_prefixes = ( + 'North', + 'East', + 'West', + 'South', + 'New', + 'Lake', + 'Port', + 'Upper', + 'Lower', + 'High', + 'Mount', + ) + + city_suffixes = ( + 'town', 'ton', 'land', 'ville', 'berg', 'burgh', + 'borough', 'bury', 'burn', 'ing', 'port', 'mouth', 'stone', 'ings' + 'mouth', 'fort', 'haven', 'leigh', 'side', 'gate', 'neath', 'side', + ' Flats', ' Hill', + ) + + building_number_formats = ('%##', '%#', '%') + + street_suffixes = ( + # Most common: + 'Arcade', 'Arcade', 'Arcade', + 'Avenue', 'Avenue', 'Avenue', 'Avenue', + 'Avenue', 'Avenue', 'Avenue', 'Avenue', + 'Beach Road', 'Beach Road', 'Beach Road', 'Beach Road', + 'Crescent', 'Crescent', 'Crescent', 'Crescent', 'Crescent', + 'Drive', 'Drive', 'Drive', 'Drive', + 'Mews', 'Mews', 'Mews', + 'Place', 'Place', 'Place', 'Place', + 'Range Road', 'Range Road', + 'Road', 'Road', 'Road', 'Road', 'Road', 'Road', 'Road', 'Road', 'Road', + 'Street', 'Street', 'Street', 'Street', 'Street', 'Street', 'Street', + 'Street', 'Street', 'Street', 'Street', 'Street', 'Street', 'Street', + 'Street', 'Street', 'Street', 'Street', 'Street', 'Street', 'Street', + 'Terrace', 'Terrace', 'Terrace', + 'Way', 'Way', 'Way', + + # Other: + 'Access', 'Alley', 'Alleyway', 'Amble', 'Anchorage', 'Approach', + 'Broadway', 'Bypass', 'Causeway', 'Centre', + 'Circle', 'Circuit', 'Close', 'Concourse', 'Copse', 'Corner', 'Court', + 'Cove', + 'Crest', 'Cross', 'Crossing', + 'Cutting', + 'Esplanade', + 'Flats', + 'Gardens', 'Grove', 'Heights', 'Highway', + 'Lane', 'Line', 'Keys', + 'Parade', 'Park', 'Pass', + 'Plaza', + 'Point', 'Quay', + 'Reserve', + 'Ridge', + 'Rise', + 'Square', + 'Track', 'Trail', + 'View', + ) + + # Māori nouns commonly present in placenames. + te_reo_parts = ( + 'ara', + 'awa', + 'horo', + 'kawa', + 'koro', + 'kowhai', + 'manawa', + 'mata', + 'maunga', + 'moko', + 'motu', + 'ngauru', + 'pa' + 'papa', + 'po', + 'puke', + 'rangi', + 'rohe', + 'rongo', + 'roto', + 'tahi', + 'tai', + 'tangi', + 'tau', + 'tere', + 'tipu', + 'wai', + 'waka', + 'whaka', + 'whanga', + 'whare', + 'weka', + ) + + # Māori endings (usually adjectives) commonly present in placenames. + te_reo_endings = ( + 'hanga', + 'hope', + 'iti', + 'iti', + 'kiwi', + 'makau', + 'nui', + 'nui', + 'nui', + 'nuku', + 'roa', + 'rua', + 'tanga', + 'tapu', + 'toa', + 'whenua', + 'whero', + 'whitu', + ) + + postcode_formats = ( + # as per https://en.wikipedia.org/wiki/Postcodes_in_New_Zealand + # Northland + '0%##', + # Auckland + '1###', + '20##', + '21##', + '22##', + '23##', + '24##', + '25##', + '26##', + # Central North Island + '3###', + '4###', + # Lower North Island + '50##', + '51##', + '52##', + '53##', + '55##', + '57##', + '58##', + # Wellington + '60##', + '61##', + '62##', + '64##', + '69##', + # Upper South Island + '7###', + # Christchurch + '80##', + '81##', + '82##', + '84##', + '85##', + '86##', + '88##', + '89##', + # Southland + '90##', + '92##', + '93##', + '94##', + '95##', + '96##', + '97##', + '98##', + ) + + city_formats = ( + '{{first_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{city_prefix}} {{last_name}}{{city_suffix}}', + '{{te_reo_first}}{{te_reo_ending}}', + '{{te_reo_first}}{{te_reo_ending}}', + '{{te_reo_first}}{{te_reo_ending}}', + '{{te_reo_first}}{{te_reo_ending}}', + '{{te_reo_first}}{{te_reo_part}}{{te_reo_ending}}', + '{{te_reo_first}}{{te_reo_part}}{{te_reo_ending}}', + ) + + street_name_formats = ( + '{{first_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + '{{last_name}}-{{last_name}} {{street_suffix}}', + '{{te_reo_first}}{{te_reo_ending}} {{street_suffix}}', + '{{te_reo_first}}{{te_reo_ending}} {{street_suffix}}', + '{{te_reo_first}}{{te_reo_part}}{{te_reo_ending}} {{street_suffix}}', + ) + + street_address_formats = ( + '{{building_number}} {{street_name}}', + '{{building_number}} {{street_name}}', + '{{building_number}} {{street_name}}', + '{{building_number}} {{street_name}}\nRD {{rd_number}}', + '{{secondary_address}}\n{{building_number}} {{street_name}}', + 'PO Box {{building_number}}', + ) + + address_formats = ( + "{{street_address}}\n{{city}} {{postcode}}", + ) + + secondary_address_formats = ( + 'Apt. %##', + 'Flat %#', + 'Suite %##', + 'Unit %#', + 'Level %', + ) + + def state(self): + # New Zealand does not have states. + return '' + + def te_reo_part(self): + return self.random_element(self.te_reo_parts) + + def te_reo_first(self): + return self.random_element(self.te_reo_parts).capitalize() + + def te_reo_ending(self): + return self.random_element(self.te_reo_parts + self.te_reo_endings) + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def city_suffix(self): + return self.random_element(self.city_suffixes) + + def rd_number(self): + return self.random_element([str(i) for i in range(1, 11)]) + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) diff --git a/testbed/joke2k__faker/faker/providers/address/en_PH/__init__.py b/testbed/joke2k__faker/faker/providers/address/en_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b87cc67dfa265b489d9ebc629146479aff4c5c30 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en_PH/__init__.py @@ -0,0 +1,474 @@ +from collections import OrderedDict +from string import ascii_uppercase + +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + """ + Provider for addresses for en_PH locale + + Like many things in the Philippines, even addresses are more complicated than necessary. This provider is already + a gross oversimplification, and it is still a lot more complicated VS providers from other locales despite taking + shortcuts. Below are some tidbits of information that, as a whole, shaped the design decisions of this provider. + + - There are many levels of geopolitical division, thus many levels of local government: + * There are three major island groups - Luzon, Visayas, Mindanao + * Those major groups are divided into 17 different regions. + * Each region is divided into provinces with the exception of the National Capital Region aka Metro Manila. + * Each province is composed of multiple cities/municipalities. + * Metro Manila, like a province, is composed of multiple cities/municipalities, but it is a region. + * Each city/municipality is composed of multiple smaller local government units called barangays. + * In some places, some barangays are divided further, and as of 2019, there are 42,045 barangays on record. + - Metro Manila is part of Luzon geographically, but it is almost always treated as a separate entity politically, + economically, statistically, and so on, since it is home to around 13% of the population despite being only around + 0.2% of the country's total land area. + - Names of cities, municipalities, and barangays vary a lot. Furthermore, if a place has a non-English name, there + will almost always be no English translation and vice-versa. It is essentially impossible to generate fake city, + municipality, and barangay names in a similar manner used in the other "en" locales while being locale specific. + - Subdivisions and other higher density housing (like high-rise condominiums) are popular in real estate. + - The 13th floor is omitted in buildings like in many parts of the world. + - The floor number distribution is partly based on the tallest buildings in the Philippines and partly anecdotal, + but the general idea is that the higher the floor number is, the lower probability of it appearing. Furthermore, + as the floor number approaches the highest floors of the tallest buildings, the probability plummets further. + - The address distribution is based on the official 2015 population census. + - Addresses should include a barangay, but it has been dropped to keep things sane, all things considered. + - In addition to numbered floors, buildings have ground floors and may have lower ground, upper ground, mezzanine, + and basement floors. Buildings may also have units on any of those floors, but the naming scheme varies, so they + have been dropped, again to keep things sane. + + Sources: + - https://en.wikipedia.org/wiki/Provinces_of_the_Philippines + - https://en.wikipedia.org/wiki/List_of_cities_and_municipalities_in_the_Philippines + - https://en.wikipedia.org/wiki/Barangay + - https://en.wikipedia.org/wiki/Postal_addresses_in_the_Philippines + - https://en.wikipedia.org/wiki/List_of_ZIP_codes_in_the_Philippines + - https://www.phlpost.gov.ph/ + - http://en.wikipedia.org/wiki/List_of_tallest_buildings_in_the_Philippines + - https://psa.gov.ph/sites/default/files/attachments/hsd/pressrelease/2015%20population%20counts%20Summary_0.xlsx + """ + + metro_manila_postcodes = tuple(x for x in range(400, 1849)) + luzon_province_postcodes = ( + tuple(x for x in range(1850, 5000)) + + tuple(x for x in range(5100, 5600)) + ) + visayas_province_postcodes = ( + tuple(x for x in range(5000, 5100)) + + tuple(x for x in range(5600, 5800)) + + tuple(x for x in range(6000, 6900)) + ) + mindanao_province_postcodes = ( + tuple(x for x in range(7000, 7600)) + + tuple(x for x in range(8000, 8900)) + + tuple(x for x in range(9000, 9900)) + ) + postcodes = ( + metro_manila_postcodes + + luzon_province_postcodes + + visayas_province_postcodes + + mindanao_province_postcodes + ) + metro_manila_lgus = ( + 'Caloocan', 'Las Piñas', 'Makati', 'Malabon', 'Mandaluyong', 'Manila', 'Marikina', 'Muntinlupa', 'Navotas', + 'Parañaque', 'Pasay', 'Pasig', 'Pateros', 'Quezon City', 'San Juan', 'Taguig', 'Valenzuela', + ) + province_lgus = ( + 'Aborlan', 'Abra de Ilog', 'Abucay', 'Abulug', 'Abuyog', 'Adams', 'Agdangan', 'Aglipay', 'Agno', 'Agoncillo', + 'Agoo', 'Aguilar', 'Aguinaldo', 'Agutaya', 'Ajuy', 'Akbar', 'Al-Barka', 'Alabat', 'Alabel', 'Alamada', + 'Alaminos', 'Alangalang', 'Albuera', 'Alburquerque', 'Alcala', 'Alcantara', 'Alcoy', 'Alegria', 'Aleosan', + 'Alfonso Castañeda', 'Alfonso Lista', 'Alfonso', 'Aliaga', 'Alicia', 'Alilem', 'Alimodian', 'Alitagtag', + 'Allacapan', 'Allen', 'Almagro', 'Almeria', 'Aloguinsan', 'Aloran', 'Altavas', 'Alubijid', 'Amadeo', + 'Amai Manabilang', 'Ambaguio', 'Amlan', 'Ampatuan', 'Amulung', 'Anahawan', 'Anao', 'Anda', 'Angadanan', 'Angat', + 'Angeles', 'Angono', 'Anilao', 'Anini-y', 'Antequera', 'Antipas', 'Antipolo', 'Apalit', 'Aparri', 'Araceli', + 'Arakan', 'Arayat', 'Argao', 'Aringay', 'Aritao', 'Aroroy', 'Arteche', 'Asingan', 'Asipulo', 'Asturias', + 'Asuncion', 'Atimonan', 'Atok', 'Aurora', 'Ayungon', 'Baao', 'Babatngon', 'Bacacay', 'Bacarra', 'Baclayon', + 'Bacnotan', 'Baco', 'Bacolod-Kalawi', 'Bacolod', 'Bacolor', 'Bacong', 'Bacoor', 'Bacuag', 'Badian', 'Badiangan', + 'Badoc', 'Bagabag', 'Bagac', 'Bagamanoc', 'Baganga', 'Baggao', 'Bago', 'Baguio', 'Bagulin', 'Bagumbayan', + 'Bais', 'Bakun', 'Balabac', 'Balabagan', 'Balagtas', 'Balamban', 'Balanga', 'Balangiga', 'Balangkayan', + 'Balaoan', 'Balasan', 'Balatan', 'Balayan', 'Balbalan', 'Baleno', 'Baler', 'Balete', 'Baliangao', 'Baliguian', + 'Balilihan', 'Balindong', 'Balingasag', 'Balingoan', 'Baliuag', 'Ballesteros', 'Baloi', 'Balud', 'Balungao', + 'Bamban', 'Bambang', 'Banate', 'Banaue', 'Banaybanay', 'Banayoyo', 'Banga', 'Bangar', 'Bangued', 'Bangui', + 'Banguingui', 'Bani', 'Banisilan', 'Banna', 'Bansalan', 'Bansud', 'Bantay', 'Bantayan', 'Banton', 'Baras', + 'Barbaza', 'Barcelona', 'Barili', 'Barira', 'Barlig', 'Barobo', 'Barotac Nuevo', 'Barotac Viejo', 'Baroy', + 'Barugo', 'Basay', 'Basco', 'Basey', 'Basilisa', 'Basista', 'Basud', 'Batac', 'Batad', 'Batan', 'Batangas City', + 'Bataraza', 'Bato', 'Batuan', 'Bauan', 'Bauang', 'Bauko', 'Baungon', 'Bautista', 'Bay', 'Bayabas', 'Bayambang', + 'Bayang', 'Bayawan', 'Baybay', 'Bayog', 'Bayombong', 'Bayugan', 'Belison', 'Benito Soliven', 'Besao', + 'Bien Unido', 'Bilar', 'Biliran', 'Binalbagan', 'Binalonan', 'Biñan', 'Binangonan', 'Bindoy', 'Bingawan', + 'Binidayan', 'Binmaley', 'Binuangan', 'Biri', 'Bislig', 'Boac', 'Bobon', 'Bocaue', 'Bogo', 'Bokod', 'Bolinao', + 'Boliney', 'Boljoon', 'Bombon', 'Bongabon', 'Bongabong', 'Bongao', 'Bonifacio', 'Bontoc', 'Borbon', 'Borongan', + 'Boston', 'Botolan', 'Braulio E. Dujali', "Brooke's Point", 'Buadiposo-Buntong', 'Bubong', 'Bucay', 'Bucloc', + 'Buenavista', 'Bugallon', 'Bugasong', 'Buguey', 'Buguias', 'Buhi', 'Bula', 'Bulakan', 'Bulalacao', 'Bulan', + 'Buldon', 'Buluan', 'Bulusan', 'Bunawan', 'Burauen', 'Burdeos', 'Burgos', 'Buruanga', 'Bustos', 'Busuanga', + 'Butig', 'Butuan', 'Buug', 'Caba', 'Cabadbaran', 'Cabagan', 'Cabanatuan', 'Cabangan', 'Cabanglasan', + 'Cabarroguis', 'Cabatuan', 'Cabiao', 'Cabucgayan', 'Cabugao', 'Cabusao', 'Cabuyao', 'Cadiz', 'Cagayan de Oro', + 'Cagayancillo', 'Cagdianao', 'Cagwait', 'Caibiran', 'Cainta', 'Cajidiocan', 'Calabanga', 'Calaca', 'Calamba', + 'Calanasan', 'Calanogas', 'Calapan', 'Calape', 'Calasiao', 'Calatagan', 'Calatrava', 'Calauag', 'Calauan', + 'Calayan', 'Calbayog', 'Calbiga', 'Calinog', 'Calintaan', 'Calubian', 'Calumpit', 'Caluya', 'Camalaniugan', + 'Camalig', 'Camaligan', 'Camiling', 'Can-avid', 'Canaman', 'Candaba', 'Candelaria', 'Candijay', 'Candon', + 'Candoni', 'Canlaon', 'Cantilan', 'Caoayan', 'Capalonga', 'Capas', 'Capoocan', 'Capul', 'Caraga', 'Caramoan', + 'Caramoran', 'Carasi', 'Carcar', 'Cardona', 'Carigara', 'Carles', 'Carmen', 'Carmona', 'Carranglan', + 'Carrascal', 'Casiguran', 'Castilla', 'Castillejos', 'Cataingan', 'Catanauan', 'Catarman', 'Catbalogan', + 'Cateel', 'Catigbian', 'Catmon', 'Catubig', 'Cauayan', 'Cavinti', 'Cavite City', 'Cawayan', 'Cebu City', + 'Cervantes', 'Clarin', 'Claver', 'Claveria', 'Columbio', 'Compostela', 'Concepcion', 'Conner', 'Consolacion', + 'Corcuera', 'Cordon', 'Cordova', 'Corella', 'Coron', 'Cortes', 'Cotabato City', 'Cuartero', 'Cuenca', 'Culaba', + 'Culasi', 'Culion', 'Currimao', 'Cuyapo', 'Cuyo', 'Daanbantayan', 'Daet', 'Dagami', 'Dagohoy', 'Daguioman', + 'Dagupan', 'Dalaguete', 'Damulog', 'Danao', 'Dangcagan', 'Danglas', 'Dao', 'Dapa', 'Dapitan', 'Daraga', 'Daram', + 'Dasmariñas', 'Dasol', 'Datu Abdullah Sangki', 'Datu Anggal Midtimbang', 'Datu Blah T. Sinsuat', + 'Datu Hoffer Ampatuan', 'Datu Montawal', 'Datu Odin Sinsuat', 'Datu Paglas', 'Datu Piang', 'Datu Salibo', + 'Datu Saudi-Ampatuan', 'Datu Unsay', 'Dauin', 'Dauis', 'Davao City', 'Del Carmen', 'Del Gallego', + 'Delfin Albano', 'Diadi', 'Diffun', 'Digos', 'Dilasag', 'Dimasalang', 'Dimataling', 'Dimiao', 'Dinagat', + 'Dinalungan', 'Dinalupihan', 'Dinapigue', 'Dinas', 'Dingalan', 'Dingle', 'Dingras', 'Dipaculao', 'Diplahan', + 'Dipolog', 'Ditsaan-Ramain', 'Divilacan', 'Dolores', 'Don Carlos', 'Don Marcelino', 'Don Victoriano Chiongbian', + 'Doña Remedios Trinidad', 'Donsol', 'Dueñas', 'Duero', 'Dulag', 'Dumaguete', 'Dumalag', 'Dumalinao', 'Dumalneg', + 'Dumangas', 'Dumanjug', 'Dumaran', 'Dumarao', 'Dumingag', 'Dupax del Norte', 'Dupax del Sur', 'Echague', + 'El Nido', 'El Salvador', 'Enrile', 'Enrique B. Magalona', 'Enrique Villanueva', 'Escalante', 'Esperanza', + 'Estancia', 'Famy', 'Ferrol', 'Flora', 'Floridablanca', 'Gabaldon', 'Gainza', 'Galimuyod', 'Gamay', 'Gamu', + 'Ganassi', 'Gandara', 'Gapan', 'Garchitorena', 'Garcia Hernandez', 'Gasan', 'Gattaran', + 'General Emilio Aguinaldo', 'General Luna', 'General MacArthur', 'General Mamerto Natividad', + 'General Mariano Alvarez', 'General Nakar', 'General Salipada K. Pendatun', 'General Santos', 'General Tinio', + 'General Trias', 'Gerona', 'Getafe', 'Gigaquit', 'Gigmoto', 'Ginatilan', 'Gingoog', 'Giporlos', 'Gitagum', + 'Glan', 'Gloria', 'Goa', 'Godod', 'Gonzaga', 'Governor Generoso', 'Gregorio del Pilar', 'Guagua', 'Gubat', + 'Guiguinto', 'Guihulngan', 'Guimba', 'Guimbal', 'Guinayangan', 'Guindulman', 'Guindulungan', 'Guinobatan', + 'Guinsiliban', 'Guipos', 'Guiuan', 'Gumaca', 'Gutalac', 'Hadji Mohammad Ajul', 'Hadji Muhtamad', + 'Hadji Panglima Tahil', 'Hagonoy', 'Hamtic', 'Hermosa', 'Hernani', 'Hilongos', 'Himamaylan', 'Hinabangan', + 'Hinatuan', 'Hindang', 'Hingyon', 'Hinigaran', 'Hinoba-an', 'Hinunangan', 'Hinundayan', 'Hungduan', 'Iba', + 'Ibaan', 'Ibajay', 'Igbaras', 'Iguig', 'Ilagan', 'Iligan', 'Ilog', 'Iloilo City', 'Imelda', 'Impasugong', + 'Imus', 'Inabanga', 'Indanan', 'Indang', 'Infanta', 'Initao', 'Inopacan', 'Ipil', 'Iriga', 'Irosin', 'Isabel', + 'Isabela City', 'Isabela', 'Isulan', 'Itbayat', 'Itogon', 'Ivana', 'Ivisan', 'Jabonga', 'Jaen', 'Jagna', + 'Jalajala', 'Jamindan', 'Janiuay', 'Jaro', 'Jasaan', 'Javier', 'Jiabong', 'Jimalalud', 'Jimenez', 'Jipapad', + 'Jolo', 'Jomalig', 'Jones', 'Jordan', 'Jose Abad Santos', 'Jose Dalman', 'Jose Panganiban', 'Josefina', + 'Jovellar', 'Juban', 'Julita', 'Kabacan', 'Kabankalan', 'Kabasalan', 'Kabayan', 'Kabugao', 'Kabuntalan', + 'Kadingilan', 'Kalamansig', 'Kalawit', 'Kalayaan', 'Kalibo', 'Kalilangan', 'Kalingalan Caluang', 'Kananga', + 'Kapai', 'Kapalong', 'Kapangan', 'Kapatagan', 'Kasibu', 'Katipunan', 'Kauswagan', 'Kawayan', 'Kawit', 'Kayapa', + 'Kiamba', 'Kiangan', 'Kibawe', 'Kiblawan', 'Kibungan', 'Kidapawan', 'Kinoguitan', 'Kitaotao', 'Kitcharao', + 'Kolambugan', 'Koronadal', 'Kumalarang', 'La Carlota', 'La Castellana', 'La Libertad', 'La Paz', 'La Trinidad', + 'Laak', 'Labangan', 'Labason', 'Labo', 'Labrador', 'Lacub', 'Lagangilang', 'Lagawe', 'Lagayan', 'Lagonglong', + 'Lagonoy', 'Laguindingan', 'Lake Sebu', 'Lakewood', 'Lal-lo', 'Lala', 'Lambayong', 'Lambunao', 'Lamitan', + 'Lamut', 'Langiden', 'Languyan', 'Lantapan', 'Lantawan', 'Lanuza', 'Laoac', 'Laoag', 'Laoang', 'Lapinig', + 'Lapu-Lapu', 'Lapuyan', 'Larena', 'Las Navas', 'Las Nieves', 'Lasam', 'Laua-an', 'Laur', 'Laurel', 'Lavezares', + 'Lawaan', 'Lazi', 'Lebak', 'Leganes', 'Legazpi', 'Lemery', 'Leon B. Postigo', 'Leon', 'Leyte', 'Lezo', 'Lian', + 'Lianga', 'Libacao', 'Libagon', 'Libertad', 'Libjo', 'Libmanan', 'Libon', 'Libona', 'Libungan', 'Licab', + 'Licuan-Baay', 'Lidlidda', 'Ligao', 'Lila', 'Liliw', 'Liloan', 'Liloy', 'Limasawa', 'Limay', 'Linamon', + 'Linapacan', 'Lingayen', 'Lingig', 'Lipa', 'Llanera', 'Llorente', 'Loay', 'Lobo', 'Loboc', 'Looc', 'Loon', + 'Lope de Vega', 'Lopez Jaena', 'Lopez', 'Loreto', 'Los Baños', 'Luba', 'Lubang', 'Lubao', 'Lubuagan', 'Lucban', + 'Lucena', 'Lugait', 'Lugus', 'Luisiana', 'Lumba-Bayabao', 'Lumbaca-Unayan', 'Lumban', 'Lumbatan', + 'Lumbayanague', 'Luna', 'Lupao', 'Lupi', 'Lupon', 'Lutayan', 'Luuk', "M'lang", 'Maasim', 'Maasin', 'Maayon', + 'Mabalacat', 'Mabinay', 'Mabini', 'Mabitac', 'Mabuhay', 'Macabebe', 'Macalelon', 'MacArthur', 'Maco', + 'Maconacon', 'Macrohon', 'Madalag', 'Madalum', 'Madamba', 'Maddela', 'Madrid', 'Madridejos', 'Magalang', + 'Magallanes', 'Magarao', 'Magdalena', 'Magdiwang', 'Magpet', 'Magsaysay', 'Magsingal', 'Maguing', 'Mahaplag', + 'Mahatao', 'Mahayag', 'Mahinog', 'Maigo', 'Maimbung', 'Mainit', 'Maitum', 'Majayjay', 'Makato', 'Makilala', + 'Malabang', 'Malabuyoc', 'Malalag', 'Malangas', 'Malapatan', 'Malasiqui', 'Malay', 'Malaybalay', 'Malibcong', + 'Malilipot', 'Malimono', 'Malinao', 'Malita', 'Malitbog', 'Mallig', 'Malolos', 'Malungon', 'Maluso', 'Malvar', + 'Mamasapano', 'Mambajao', 'Mamburao', 'Mambusao', 'Manabo', 'Manaoag', 'Manapla', 'Manay', 'Mandaon', 'Mandaue', + 'Mangaldan', 'Mangatarem', 'Mangudadatu', 'Manito', 'Manjuyod', 'Mankayan', 'Manolo Fortich', 'Mansalay', + 'Manticao', 'Manukan', 'Mapanas', 'Mapandan', 'Mapun', 'Marabut', 'Maragondon', 'Maragusan', 'Maramag', + 'Marantao', 'Marawi', 'Marcos', 'Margosatubig', 'Maria Aurora', 'Maria', 'Maribojoc', 'Marihatag', 'Marilao', + 'Maripipi', 'Mariveles', 'Marogong', 'Masantol', 'Masbate City', 'Masinloc', 'Masiu', 'Maslog', 'Mataasnakahoy', + 'Matag-ob', 'Matalam', 'Matalom', 'Matanao', 'Matanog', 'Mati', 'Matnog', 'Matuguinao', 'Matungao', 'Mauban', + 'Mawab', 'Mayantoc', 'Maydolong', 'Mayorga', 'Mayoyao', 'Medellin', 'Medina', 'Mendez', 'Mercedes', 'Merida', + 'Mexico', 'Meycauayan', 'Miagao', 'Midsalip', 'Midsayap', 'Milagros', 'Milaor', 'Mina', 'Minalabac', 'Minalin', + 'Minglanilla', 'Moalboal', 'Mobo', 'Mogpog', 'Moises Padilla', 'Molave', 'Moncada', 'Mondragon', 'Monkayo', + 'Monreal', 'Montevista', 'Morong', 'Motiong', 'Mulanay', 'Mulondo', 'Munai', 'Muñoz', 'Murcia', 'Mutia', + 'Naawan', 'Nabas', 'Nabua', 'Nabunturan', 'Naga', 'Nagbukel', 'Nagcarlan', 'Nagtipunan', 'Naguilian', 'Naic', + 'Nampicuan', 'Narra', 'Narvacan', 'Nasipit', 'Nasugbu', 'Natividad', 'Natonin', 'Naujan', 'Naval', 'New Bataan', + 'New Corella', 'New Lucena', 'New Washington', 'Norala', 'Northern Kabuntalan', 'Norzagaray', 'Noveleta', + 'Nueva Era', 'Nueva Valencia', 'Numancia', 'Nunungan', 'Oas', 'Obando', 'Ocampo', 'Odiongan', 'Old Panamao', + 'Olongapo', 'Olutanga', 'Omar', 'Opol', 'Orani', 'Oras', 'Orion', 'Ormoc', 'Oroquieta', 'Oslob', 'Oton', + 'Ozamiz', 'Padada', 'Padre Burgos', 'Padre Garcia', 'Paete', 'Pagadian', 'Pagalungan', 'Pagayawan', 'Pagbilao', + 'Paglat', 'Pagsanghan', 'Pagsanjan', 'Pagudpud', 'Pakil', 'Palanan', 'Palanas', 'Palapag', 'Palauig', 'Palayan', + 'Palimbang', 'Palo', 'Palompon', 'Paluan', 'Pambujan', 'Pamplona', 'Panabo', 'Panaon', 'Panay', 'Pandag', + 'Pandami', 'Pandan', 'Pandi', 'Panganiban', 'Pangantucan', 'Pangil', 'Panglao', 'Panglima Estino', + 'Panglima Sugala', 'Pangutaran', 'Paniqui', 'Panitan', 'Pantabangan', 'Pantao Ragat', 'Pantar', 'Pantukan', + 'Panukulan', 'Paoay', 'Paombong', 'Paracale', 'Paracelis', 'Paranas', 'Parang', 'Pasacao', 'Pasil', 'Passi', + 'Pastrana', 'Pasuquin', 'Pata', 'Patikul', 'Patnanungan', 'Patnongon', 'Pavia', 'Payao', 'Peñablanca', + 'Peñaranda', 'Peñarrubia', 'Perez', 'Piagapo', 'Piat', 'Picong', 'Piddig', 'Pidigan', 'Pigcawayan', 'Pikit', + 'Pila', 'Pilar', 'Pili', 'Pililla', 'Pinabacdao', 'Pinamalayan', 'Pinamungajan', 'Piñan', 'Pinili', 'Pintuyan', + 'Pinukpuk', 'Pio Duran', 'Pio V. Corpuz', 'Pitogo', 'Placer', 'Plaridel', 'Pola', 'Polanco', 'Polangui', + 'Polillo', 'Polomolok', 'Pontevedra', 'Poona Bayabao', 'Poona Piagapo', 'Porac', 'Poro', 'Pototan', + 'Pozorrubio', 'Presentacion', 'President Carlos P. Garcia', 'President Manuel A. Roxas', 'President Quirino', + 'President Roxas', 'Prieto Diaz', 'Prosperidad', 'Pualas', 'Pudtol', 'Puerto Galera', 'Puerto Princesa', 'Pugo', + 'Pulilan', 'Pulupandan', 'Pura', 'Quezon', 'Quinapondan', 'Quirino', 'Ragay', 'Rajah Buayan', 'Ramon Magsaysay', + 'Ramon', 'Ramos', 'Rapu-Rapu', 'Real', 'Reina Mercedes', 'Remedios T. Romualdez', 'Rizal', 'Rodriguez', + 'Romblon', 'Ronda', 'Rosales', 'Rosario', 'Roseller Lim', 'Roxas City', 'Roxas', 'Sabangan', 'Sablan', + 'Sablayan', 'Sabtang', 'Sadanga', 'Sagada', 'Sagay', 'Sagbayan', 'Sagñay', 'Saguday', 'Saguiaran', + 'Saint Bernard', 'Salay', 'Salcedo', 'Sallapadan', 'Salug', 'Salvador Benedicto', 'Salvador', 'Samal', + 'Samboan', 'Sampaloc', 'San Agustin', 'San Andres', 'San Antonio', 'San Benito', 'San Carlos', 'San Clemente', + 'San Dionisio', 'San Emilio', 'San Enrique', 'San Esteban', 'San Fabian', 'San Felipe', 'San Fernando', + 'San Francisco', 'San Gabriel', 'San Guillermo', 'San Ildefonso', 'San Isidro', 'San Jacinto', 'San Joaquin', + 'San Jorge', 'San Jose de Buan', 'San Jose de Buenavista', 'San Jose del Monte', 'San Jose', 'San Juan', + 'San Julian', 'San Leonardo', 'San Lorenzo Ruiz', 'San Lorenzo', 'San Luis', 'San Manuel', 'San Marcelino', + 'San Mariano', 'San Mateo', 'San Miguel', 'San Narciso', 'San Nicolas', 'San Pablo', 'San Pascual', 'San Pedro', + 'San Policarpo', 'San Quintin', 'San Rafael', 'San Remigio', 'San Ricardo', 'San Roque', 'San Sebastian', + 'San Simon', 'San Teodoro', 'San Vicente', 'Sanchez-Mira', 'Santa Ana', 'Santa Barbara', 'Santa Catalina', + 'Santa Cruz', 'Santa Elena', 'Santa Fe', 'Santa Ignacia', 'Santa Josefa', 'Santa Lucia', 'Santa Magdalena', + 'Santa Marcela', 'Santa Margarita', 'Santa Maria', 'Santa Monica', 'Santa Praxedes', 'Santa Rita', 'Santa Rosa', + 'Santa Teresita', 'Santa', 'Santander', 'Santiago', 'Santo Domingo', 'Santo Niño', 'Santo Tomas', 'Santol', + 'Sapa-Sapa', 'Sapad', 'Sapang Dalaga', 'Sapian', 'Sara', 'Sarangani', 'Sariaya', 'Sarrat', 'Sasmuan', 'Sebaste', + 'Senator Ninoy Aquino', 'Sergio Osmeña Sr.', 'Sevilla', 'Shariff Aguak', 'Shariff Saydona Mustapha', 'Siasi', + 'Siaton', 'Siay', 'Siayan', 'Sibagat', 'Sibalom', 'Sibonga', 'Sibuco', 'Sibulan', 'Sibunag', 'Sibutad', + 'Sibutu', 'Sierra Bullones', 'Sigay', 'Sigma', 'Sikatuna', 'Silago', 'Silang', 'Silay', 'Silvino Lobos', + 'Simunul', 'Sinacaban', 'Sinait', 'Sindangan', 'Siniloan', 'Siocon', 'Sipalay', 'Sipocot', 'Siquijor', + 'Sirawai', 'Siruma', 'Sison', 'Sitangkai', 'Socorro', 'Sofronio Española', 'Sogod', 'Solana', 'Solano', + 'Solsona', 'Sominot', 'Sorsogon City', 'South Ubian', 'South Upi', 'Sual', 'Subic', 'Sudipen', 'Sugbongcogon', + 'Sugpon', 'Sulat', 'Sulop', 'Sultan Dumalondong', 'Sultan Kudarat', 'Sultan Mastura', 'Sultan Naga Dimaporo', + 'Sultan sa Barongis', 'Sultan Sumagka', 'Sumilao', 'Sumisip', 'Surallah', 'Surigao City', 'Suyo', "T'Boli", + 'Taal', 'Tabaco', 'Tabango', 'Tabina', 'Tabogon', 'Tabontabon', 'Tabuan-Lasa', 'Tabuelan', 'Tabuk', 'Tacloban', + 'Tacurong', 'Tadian', 'Taft', 'Tagana-an', 'Tagapul-an', 'Tagaytay', 'Tagbilaran', 'Tagbina', 'Tagkawayan', + 'Tago', 'Tagoloan II', 'Tagoloan', 'Tagudin', 'Tagum', 'Talacogon', 'Talaingod', 'Talakag', 'Talalora', + 'Talavera', 'Talayan', 'Talibon', 'Talipao', 'Talisay', 'Talisayan', 'Talugtug', 'Talusan', 'Tambulig', + 'Tampakan', 'Tamparan', 'Tampilisan', 'Tanauan', 'Tanay', 'Tandag', 'Tandubas', 'Tangalan', 'Tangcal', 'Tangub', + 'Tanjay', 'Tantangan', 'Tanudan', 'Tanza', 'Tapaz', 'Tapul', 'Taraka', 'Tarangnan', 'Tarlac City', 'Tarragona', + 'Tayabas', 'Tayasan', 'Taysan', 'Taytay', 'Tayug', 'Tayum', 'Teresa', 'Ternate', 'Tiaong', 'Tibiao', 'Tigaon', + 'Tigbao', 'Tigbauan', 'Tinambac', 'Tineg', 'Tinglayan', 'Tingloy', 'Tinoc', 'Tipo-Tipo', 'Titay', 'Tiwi', + 'Tobias Fornier', 'Toboso', 'Toledo', 'Tolosa', 'Tomas Oppus', 'Torrijos', 'Trece Martires', 'Trento', + 'Trinidad', 'Tuao', 'Tuba', 'Tubajon', 'Tubao', 'Tubaran', 'Tubay', 'Tubigon', 'Tublay', 'Tubo', 'Tubod', + 'Tubungan', 'Tuburan', 'Tudela', 'Tugaya', 'Tuguegarao', 'Tukuran', 'Tulunan', 'Tumauini', 'Tunga', 'Tungawan', + 'Tupi', 'Turtle Islands', 'Tuy', 'Ubay', 'Umingan', 'Ungkaya Pukan', 'Unisan', 'Upi', 'Urbiztondo', 'Urdaneta', + 'Uson', 'Uyugan', 'Valderrama', 'Valencia', 'Valladolid', 'Vallehermoso', 'Veruela', 'Victoria', 'Victorias', + 'Viga', 'Vigan', 'Villaba', 'Villanueva', 'Villareal', 'Villasis', 'Villaverde', 'Villaviciosa', + 'Vincenzo A. Sagun', 'Vintar', 'Vinzons', 'Virac', 'Wao', 'Zamboanga City', 'Zamboanguita', 'Zaragoza', + 'Zarraga', 'Zumarraga', + ) + luzon_provinces = ( + 'Abra', 'Albay', 'Apayao', 'Aurora', 'Bataan', 'Batanes', 'Batangas', 'Benguet', 'Bulacan', 'Cagayan', + 'Camarines Norte', 'Camarines Sur', 'Catanduanes', 'Cavite', 'Ifugao', 'Ilocos Norte', 'Ilocos Sur', 'Isabela', + 'Kalinga', 'La Union', 'Laguna', 'Marinduque', 'Masbate', 'Mountain Province', 'Nueva Ecija', 'Nueva Vizcaya', + 'Occidental Mindoro', 'Oriental Mindoro', 'Palawan', 'Pampanga', 'Pangasinan', 'Quezon', 'Quirino', 'Rizal', + 'Romblon', 'Sorsogon', 'Tarlac', 'Zambales', + ) + visayas_provinces = ( + 'Aklan', 'Antique', 'Biliran', 'Bohol', 'Capiz', 'Cebu', 'Eastern Samar', 'Guimaras', 'Iloilo', 'Leyte', + 'Negros Occidental', 'Negros Oriental', 'Northern Samar', 'Samar', 'Siquijor', 'Southern Leyte', + ) + mindanao_provinces = ( + 'Agusan del Norte', 'Agusan del Sur', 'Basilan', 'Bukidnon', 'Camiguin', 'Compostela Valley', 'Cotabato', + 'Davao del Norte', 'Davao del Sur', 'Davao Occidental', 'Davao Oriental', 'Dinagat Islands', 'Lanao del Norte', + 'Lanao del Sur', 'Maguindanao', 'Misamis Occidental', 'Misamis Oriental', 'Sarangani', 'South Cotabato', + 'Sultan Kudarat', 'Sulu', 'Surigao del Norte', 'Surigao del Sur', 'Tawi-Tawi', 'Zamboanga del Norte', + 'Zamboanga del Sur', 'Zamboanga Sibugay', + ) + provinces = luzon_provinces + visayas_provinces + mindanao_provinces + + partitioned_building_number_formats = ( + '{{standalone_building_number}}?', + '{{standalone_building_number}} ?', + '{{standalone_building_number}}-?', + '{{standalone_building_number}} Unit ?', + ) + building_unit_number_formats = ( + 'Unit {{floor_unit_number}}', + 'Room {{floor_unit_number}}', + '{{floor_number}}F', + '{{ordinal_floor_number}} Floor', + ) + building_name_formats = ( + '{{last_name}} {{building_name_suffix}}', + '{{random_object_name}} {{building_name_suffix}}', + ) + building_name_suffixes = ( + 'Apartment', 'Apartments', + 'Building', 'Building %', 'Building Tower %', + 'Condominiums', 'Condominiums %', 'Condominiums Tower %', + 'Place', 'Place %', 'Place Tower %', + 'Residences', 'Residences %', 'Residences Tower %', + 'Suites', 'Suites %', 'Suites Tower %', + 'Tower', 'Towers', 'Towers %', + ) + subdivision_unit_number_formats = ( + 'B{{subdivision_block_number}} L{{subdivision_lot_number}}', + 'Block {{subdivision_block_number}} Lot {{subdivision_lot_number}}', + ) + subdivision_name_formats = ( + '{{last_name}} {{subdivision_name_suffix}}', + '{{random_object_name}} {{subdivision_name_suffix}}', + ) + subdivision_name_suffixes = ( + 'Cove', 'Cove %', 'Cove Phase %', + 'Estates', 'Estates %', 'Estates Phase %', + 'Grove', 'Grove %', 'Grove Phase %', + 'Homes', 'Homes %', 'Homes Phase %', + 'Subdivision', 'Subdivision %', 'Subdivision Phase %', + 'Village', 'Village %', 'Village Phase %', + ) + floor_numbers = OrderedDict([ + (str(x), 0.08) for x in range(2, 5) # Floors 2 to 4, 24% of the time + ] + [ + (str(x), 0.32356832089420257 / x) for x in range(5, 13) # Floors 5 to 12, 33% of the time + ] + [ + (str(x), 0.30341265418486174 / (x - 1)) for x in range(14, 30) # Floors 14 to 29, 25% of the time + ] + [ + (str(x), 0.30096338222652870 / (x - 1)) for x in range(30, 50) # Floors 30 to 49, 16% of the time + ] + [ + (str(x), 0.04570476167856688 / (x - 1)) for x in range(50, 75) # Floors 50 to 74, 1.9% of the time + ] + [ + (str(x), 0.003415677066138734 / (x - 1)) for x in range(75, 100) # Floors 75 to 99, 0.1% of the time + ]) + + street_suffixes = OrderedDict([ + ('Avenue', 0.12), + ('Avenue Extension', 0.01), + ('Boulevard', 0.05), + ('Boulevard Extension', 0.008), + ('Circle', 0.002), + ('Drive', 0.15), + ('Drive Extension', 0.03), + ('Expressway', 0.01), + ('Extension', 0.05), + ('Highway', 0.02), + ('Road', 0.2), + ('Road Extension', 0.04), + ('Service Road', 0.01), + ('Street', 0.3), + ]) + street_name_formats = ( + '{{last_name}} {{street_suffix}}', + '{{ordinal_street_number}} {{street_suffix}}', + '{{gemstone_name}} {{street_suffix}}', + '{{mountain_name}} {{street_suffix}}', + '{{plant_name}} {{street_suffix}}', + '{{space_object_name}} {{street_suffix}}', + ) + street_address_formats = ( + '{{standalone_building_number}} {{street_name}}', + '{{partitioned_building_number}} {{street_name}}', + '{{subdivision_unit_number}} {{subdivision_name}}, {{street_name}}', + '{{subdivision_unit_number}} {{street_name}}, {{subdivision_name}}', + '{{standalone_building_number}} {{street_name}}, {{subdivision_name}}', + '{{building_unit_number}} {{building_name}}, {{standalone_building_number}} {{street_name}}', + ) + + metro_manila_address_formats = ( + '{{street_address}}, {{metro_manila_lgu}}, {{metro_manila_postcode}} Metro Manila', + ) + luzon_province_address_formats = ( + '{{street_address}}, {{province_lgu}}, {{luzon_province_postcode}} {{luzon_province}}', + ) + visayas_province_address_formats = ( + '{{street_address}}, {{province_lgu}}, {{visayas_province_postcode}} {{visayas_province}}', + ) + mindanao_province_address_formats = ( + '{{street_address}}, {{province_lgu}}, {{mindanao_province_postcode}} {{mindanao_province}}', + ) + address_formats = OrderedDict([ + (metro_manila_address_formats, 0.127524), + (luzon_province_address_formats, 0.485317), + (visayas_province_address_formats, 0.148142), + (mindanao_province_address_formats, 0.239017), + ]) + + def _ordinal_string(self, num): + if isinstance(num, str): + num = int(num) + suffix = ['th', 'st', 'nd', 'rd', 'th'][min(num % 10, 4)] + if 11 <= num % 100 <= 13: + suffix = 'th' + return str(num) + suffix + + def _create_postcode(self, postcodes): + return '{postcode:04d}'.format(postcode=self.random_element(postcodes)) + + def _create_address(self, address_formats): + return self.generator.parse(self.random_element(address_formats)) + + def metro_manila_postcode(self): + return self._create_postcode(self.metro_manila_postcodes) + + def luzon_province_postcode(self): + return self._create_postcode(self.luzon_province_postcodes) + + def visayas_province_postcode(self): + return self._create_postcode(self.visayas_province_postcodes) + + def mindanao_province_postcode(self): + return self._create_postcode(self.mindanao_province_postcodes) + + def postcode(self): + return self._create_postcode(self.postcodes) + + def luzon_province(self): + return self.random_element(self.luzon_provinces) + + def visayas_province(self): + return self.random_element(self.visayas_provinces) + + def mindanao_province(self): + return self.random_element(self.mindanao_provinces) + + def province(self): + return self.random_element(self.provinces) + + def standalone_building_number(self): + return str(self.random_int(min=1)) + + def partitioned_building_number(self): + pattern = self.lexify( + self.random_element(self.partitioned_building_number_formats), letters=ascii_uppercase[:10], + ) + return self.generator.parse(pattern) + + def building_number(self): + if self.random_int() % 2 == 0: + return self.standalone_building_number() + else: + return self.partitioned_building_number() + + def ordinal_street_number(self): + return self._ordinal_string(self.random_int(1, 99)) + + def floor_number(self): + return self.random_element(self.floor_numbers) + + def ordinal_floor_number(self): + return self._ordinal_string(self.floor_number()) + + def floor_unit_number(self): + return '{floor_number}{unit_number:02d}'.format( + floor_number=self.floor_number(), + unit_number=self.random_int(1, 40), + ) + + def building_unit_number(self): + return self.generator.parse(self.random_element(self.building_unit_number_formats)) + + def building_name(self): + return self.generator.parse(self.random_element(self.building_name_formats)) + + def building_name_suffix(self): + return self.numerify(self.random_element(self.building_name_suffixes)) + + def subdivision_block_number(self): + return '{block_number:02d}'.format(block_number=self.random_int(1, 25)) + + def subdivision_lot_number(self): + return '{lot_number:02d}'.format(lot_number=self.random_int(1, 99)) + + def subdivision_unit_number(self): + return self.generator.parse(self.random_element(self.subdivision_unit_number_formats)) + + def subdivision_name(self): + return self.generator.parse(self.random_element(self.subdivision_name_formats)) + + def subdivision_name_suffix(self): + return self.numerify(self.random_element(self.subdivision_name_suffixes)) + + def metro_manila_lgu(self): + return self.random_element(self.metro_manila_lgus) + + def province_lgu(self): + return self.random_element(self.province_lgus) + + def metro_manila_address(self): + return self._create_address(self.metro_manila_address_formats) + + def luzon_province_address(self): + return self._create_address(self.luzon_province_address_formats) + + def visayas_province_address(self): + return self._create_address(self.visayas_province_address_formats) + + def mindanao_province_address(self): + return self._create_address(self.mindanao_province_address_formats) + + def address(self): + return self._create_address(self.random_element(self.address_formats)) diff --git a/testbed/joke2k__faker/faker/providers/address/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/address/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36c673ea6bf5a47b40cbbbf92704de6235c47ec3 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/en_US/__init__.py @@ -0,0 +1,435 @@ +from collections import OrderedDict + +from ..en import Provider as AddressProvider + + +class Provider(AddressProvider): + city_prefixes = ('North', 'East', 'West', 'South', 'New', 'Lake', 'Port') + + city_suffixes = ( + 'town', + 'ton', + 'land', + 'ville', + 'berg', + 'burgh', + 'borough', + 'bury', + 'view', + 'port', + 'mouth', + 'stad', + 'furt', + 'chester', + 'mouth', + 'fort', + 'haven', + 'side', + 'shire') + + building_number_formats = ('#####', '####', '###') + + street_suffixes = ( + 'Alley', + 'Avenue', + 'Branch', + 'Bridge', + 'Brook', + 'Brooks', + 'Burg', + 'Burgs', + 'Bypass', + 'Camp', + 'Canyon', + 'Cape', + 'Causeway', + 'Center', + 'Centers', + 'Circle', + 'Circles', + 'Cliff', + 'Cliffs', + 'Club', + 'Common', + 'Corner', + 'Corners', + 'Course', + 'Court', + 'Courts', + 'Cove', + 'Coves', + 'Creek', + 'Crescent', + 'Crest', + 'Crossing', + 'Crossroad', + 'Curve', + 'Dale', + 'Dam', + 'Divide', + 'Drive', + 'Drive', + 'Drives', + 'Estate', + 'Estates', + 'Expressway', + 'Extension', + 'Extensions', + 'Fall', + 'Falls', + 'Ferry', + 'Field', + 'Fields', + 'Flat', + 'Flats', + 'Ford', + 'Fords', + 'Forest', + 'Forge', + 'Forges', + 'Fork', + 'Forks', + 'Fort', + 'Freeway', + 'Garden', + 'Gardens', + 'Gateway', + 'Glen', + 'Glens', + 'Green', + 'Greens', + 'Grove', + 'Groves', + 'Harbor', + 'Harbors', + 'Haven', + 'Heights', + 'Highway', + 'Hill', + 'Hills', + 'Hollow', + 'Inlet', + 'Inlet', + 'Island', + 'Island', + 'Islands', + 'Islands', + 'Isle', + 'Isle', + 'Junction', + 'Junctions', + 'Key', + 'Keys', + 'Knoll', + 'Knolls', + 'Lake', + 'Lakes', + 'Land', + 'Landing', + 'Lane', + 'Light', + 'Lights', + 'Loaf', + 'Lock', + 'Locks', + 'Locks', + 'Lodge', + 'Lodge', + 'Loop', + 'Mall', + 'Manor', + 'Manors', + 'Meadow', + 'Meadows', + 'Mews', + 'Mill', + 'Mills', + 'Mission', + 'Mission', + 'Motorway', + 'Mount', + 'Mountain', + 'Mountain', + 'Mountains', + 'Mountains', + 'Neck', + 'Orchard', + 'Oval', + 'Overpass', + 'Park', + 'Parks', + 'Parkway', + 'Parkways', + 'Pass', + 'Passage', + 'Path', + 'Pike', + 'Pine', + 'Pines', + 'Place', + 'Plain', + 'Plains', + 'Plains', + 'Plaza', + 'Plaza', + 'Point', + 'Points', + 'Port', + 'Port', + 'Ports', + 'Ports', + 'Prairie', + 'Prairie', + 'Radial', + 'Ramp', + 'Ranch', + 'Rapid', + 'Rapids', + 'Rest', + 'Ridge', + 'Ridges', + 'River', + 'Road', + 'Road', + 'Roads', + 'Roads', + 'Route', + 'Row', + 'Rue', + 'Run', + 'Shoal', + 'Shoals', + 'Shore', + 'Shores', + 'Skyway', + 'Spring', + 'Springs', + 'Springs', + 'Spur', + 'Spurs', + 'Square', + 'Square', + 'Squares', + 'Squares', + 'Station', + 'Station', + 'Stravenue', + 'Stravenue', + 'Stream', + 'Stream', + 'Street', + 'Street', + 'Streets', + 'Summit', + 'Summit', + 'Terrace', + 'Throughway', + 'Trace', + 'Track', + 'Trafficway', + 'Trail', + 'Trail', + 'Tunnel', + 'Tunnel', + 'Turnpike', + 'Turnpike', + 'Underpass', + 'Union', + 'Unions', + 'Valley', + 'Valleys', + 'Via', + 'Viaduct', + 'View', + 'Views', + 'Village', + 'Village', + 'Villages', + 'Ville', + 'Vista', + 'Vista', + 'Walk', + 'Walks', + 'Wall', + 'Way', + 'Ways', + 'Well', + 'Wells') + + postcode_formats = ('#####', '#####-####') + + states = ( + 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', + 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', + 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', + 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', + 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', + 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', + 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', + 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', + 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', + 'West Virginia', 'Wisconsin', 'Wyoming', + ) + states_abbr = ( + 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', + 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', + 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', + 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', + 'WV', 'WI', 'WY', + ) + + states_postcode = { + 'AL': (35004, 36925), 'AK': (99501, 99950), 'AZ': (85001, 86556), + 'AR': (71601, 72959), 'CA': (90001, 96162), 'CO': (80001, 81658), + 'CT': (6001, 6389), 'DE': (19701, 19980), 'DC': (20001, 20039), + 'FL': (32004, 34997), 'GA': (30001, 31999), 'HI': (96701, 96898), + 'ID': (83201, 83876), 'IL': (60001, 62999), 'IN': (46001, 47997), + 'IA': (50001, 52809), 'KS': (66002, 67954), 'KY': (40003, 42788), + 'LA': (70001, 71232), 'ME': (3901, 4992), 'MD': (20331, 20331), + 'MA': (1001, 2791), 'MI': (48001, 49971), 'MN': (55001, 56763), + 'MS': (38601, 39776), 'MO': (63001, 65899), 'MT': (59001, 59937), + 'NE': (68001, 68118), 'NV': (88901, 89883), 'NH': (3031, 3897), + 'NJ': (7001, 8989), 'NM': (87001, 88441), 'NY': (10001, 14905), + 'NC': (27006, 28909), 'ND': (58001, 58856), 'OH': (43001, 45999), + 'OK': (73001, 73199), 'OR': (97001, 97920), 'PA': (15001, 19640), + 'RI': (2801, 2940), 'SC': (29001, 29948), 'SD': (57001, 57799), + 'TN': (37010, 38589), 'TX': (73301, 73301), 'UT': (84001, 84784), + 'VT': (5001, 5495), 'VA': (20040, 20041), 'WA': (98001, 99403), + 'WV': (24701, 26886), 'WI': (53001, 54990), 'WY': (82001, 83128), + } + + territories_abbr = ( + 'AS', 'FM', 'GU', 'MH', 'MP', 'PW', 'PR', 'VI', + ) + + states_and_territories_abbr = states_abbr + territories_abbr + + military_state_abbr = ('AE', 'AA', 'AP') + + military_ship_prefix = ('USS', 'USNS', 'USNV', 'USCGC') + + military_apo_format = ("PSC ####, Box ####") + + military_dpo_format = ("Unit #### Box ####") + + city_formats = ( + '{{city_prefix}} {{first_name}}{{city_suffix}}', + '{{city_prefix}} {{first_name}}', + '{{first_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + ) + + street_name_formats = ( + '{{first_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + ) + + street_address_formats = ( + '{{building_number}} {{street_name}}', + '{{building_number}} {{street_name}} {{secondary_address}}', + ) + + address_formats = ( + "{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", + ) + + address_formats = OrderedDict(( + ("{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", 25), + # military address formatting. + ("{{military_apo}}\nAPO {{military_state}} {{postcode}}", 1), + ("{{military_ship}} {{last_name}}\nFPO {{military_state}} {{postcode}}", 1), + ("{{military_dpo}}\nDPO {{military_state}} {{postcode}}", 1), + )) + + secondary_address_formats = ('Apt. ###', 'Suite ###') + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def state(self): + return self.random_element(self.states) + + def state_abbr(self, include_territories=True): + """ + :returns: A random state or territory abbreviation. + + :param include_territories: If True, territories will be included. + If False, only states will be returned. + """ + if include_territories: + self.random_element(self.states_and_territories_abbr) + return self.random_element(self.states_abbr) + + def postcode(self): + return "%05d" % self.generator.random.randint(501, 99950) + + def zipcode_plus4(self): + return "%s-%04d" % (self.zipcode(), + self.generator.random.randint(1, 9999)) + + def postcode_in_state(self, state_abbr=None): + """ + :returns: A random postcode within the provided state abbreviation + + :param state_abbr: A state abbreviation + """ + if state_abbr is None: + state_abbr = self.random_element(self.states_abbr) + + if state_abbr in self.states_abbr: + postcode = "%d" % (self.generator.random.randint( + self.states_postcode[state_abbr][0], + self.states_postcode[state_abbr][1])) + + if len(postcode) == 4: + postcode = "0%s" % postcode + + return postcode + + else: + raise Exception('State Abbreviation not found in list') + + def military_ship(self): + """ + :example 'USS' + """ + return self.random_element(self.military_ship_prefix) + + def military_state(self): + """ + :example 'APO' + """ + return self.random_element(self.military_state_abbr) + + def military_apo(self): + """ + :example 'PSC 5394 Box 3492 + """ + return self.numerify(self.military_apo_format) + + def military_dpo(self): + """ + :example 'Unit 3333 Box 9342' + """ + return self.numerify(self.military_dpo_format) + + # Aliases + def zipcode(self): + return self.postcode() + + def zipcode_in_state(self, state_abbr=None): + return self.postcode_in_state(state_abbr) + + def postalcode(self): + return self.postcode() + + def postalcode_in_state(self, state_abbr=None): + return self.postcode_in_state(state_abbr) + + def postalcode_plus4(self): + return self.zipcode_plus4() diff --git a/testbed/joke2k__faker/faker/providers/address/es/__init__.py b/testbed/joke2k__faker/faker/providers/address/es/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7d41c0d9e4e4c8b61f2de2081ba4735425767f30 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/es/__init__.py @@ -0,0 +1,49 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + # List of Countries https://www.un.org/es/members/ + countries = ( + 'Afganistán', 'Albania', 'Alemania', 'Andorra', 'Angola', + 'Antigua y Barbuda', 'Arabia Saudita', 'Argelia', 'Argentina', + 'Armenia', 'Australia', 'Austria', 'Azerbaiyán', 'Bahamas', 'Bahrein', + 'Bangladesh', 'Barbados', 'Belarús', 'Bélgica', 'Belice', 'Benin', + 'Bhután', 'Bolivia', 'Bosnia y Herzegovina', 'Botswana', 'Brasil', + 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', + 'Cabo Verde', 'Camboya', 'Camerún', 'Canadá', 'Chad', 'Chile', 'China', + 'Chipre', 'Colombia', 'Comoras', 'Congo', 'Costa Rica', + 'Côte d\'Ivoire', 'Croacia', 'Cuba', 'Dinamarca', 'Djibouti', + 'Dominicana', 'Ecuador', 'Egipto', 'El Salvador', + 'Emiratos Árabes Unidos', 'Eritrea', 'Eslovaquia', 'Eslovenia', + 'España', 'Estados Unidos de América', 'Estonia', 'Etiopía', + 'ex República Yugoslava de Macedonia', 'Federación de Rusia', 'Fiji', + 'Filipinas', 'Finlandia', 'Francia', 'Gabón', 'Gambia', 'Georgia', + 'Ghana', 'Granada', 'Grecia', 'Guatemala', 'Guinea', 'Guinea Bissau', + 'Guinea Ecuatorial', 'Guyana', 'Haití', 'Honduras', 'Hungría', 'India', + 'Indonesia', 'Irán', 'Iraq', 'Irlanda', 'Islandia', 'Islas Marshall', + 'Islas Salomón', 'Israel', 'Italia', 'Jamaica', 'Japón', 'Jordania', + 'Kazajstán', 'Kenya', 'Kirguistán', 'Kiribati', 'Kuwait', 'Lesotho', + 'Letonia', 'Líbano', 'Liberia', 'Libia', 'Liechtenstein', 'Lituania', + 'Luxemburgo', 'Madagascar', 'Malasia', 'Malawi', 'Maldivas', 'Mali', + 'Malta', 'Marruecos', 'Mauricio', 'Mauritania', 'México', 'Micronesia', + 'Mónaco', 'Mongolia', 'Montenegro', 'Mozambique', 'Myanmar', 'Namibia', + 'Nauru', 'Nicaragua', 'Niger', 'Nigeria', 'Noruega', 'Nueva Zelandia', + 'Omán', 'Países Bajos', 'Pakistán', 'Palau', 'Panamá', + 'Papua Nueva Guinea', 'Paraguay', 'Perú', 'Polonia', 'Portugal', + 'Qatar', 'Reino Unido de Gran Bretaña e Irlanda del Norte', + 'República Árabe Siria', 'República Centroafricana', 'República Checa', + 'República de Corea', 'República de Moldova', + 'República Democrática del Congo', 'República Democrática Popular Lao', + 'República Dominicana', 'República Federal Democrática de Nepal', + 'República Popular Democrática de Corea', 'República Unida de Tanzanía', + 'Rumania', 'Rwanda', 'Saint Kitts y Nevis', 'Samoa', 'San Marino', + 'Santa Lucía', 'Santo Tomé y Príncipe', 'San Vicente y las Granadinas', + 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leona', 'Singapur', + 'Somalia', 'Sri Lanka', 'Sudáfrica', 'Sudán', 'Sudán del Sur', 'Suecia', + 'Suiza', 'Suriname', 'Swazilandia', 'Tailandia', 'Tayikistán', + 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad y Tabago', 'Túnez', + 'Turkmenistán', 'Turquía', 'Tuvalu', 'Ucrania', 'Uganda', 'Uruguay', + 'Uzbekistán', 'Vanuatu', 'Venezuela', 'Vietman', 'Yemen', 'Zambia', + 'Zimbabwe', + ) diff --git a/testbed/joke2k__faker/faker/providers/address/es_ES/__init__.py b/testbed/joke2k__faker/faker/providers/address/es_ES/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd46d265c5f8140c1ed3087974e7e3c216baab2 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/es_ES/__init__.py @@ -0,0 +1,96 @@ +from ..es import Provider as AddressProvider + + +class Provider(AddressProvider): + building_number_formats = ('%', '%#', '%#', '%#', '%##') + street_prefixes = ( + 'Plaza', 'Calle', 'Avenida', 'Via', 'Vial', 'Rambla', 'Glorieta', + 'Urbanización', 'Callejón', 'Cañada', 'Alameda', 'Acceso', 'C.', + 'Ronda', 'Pasaje', 'Cuesta', 'Pasadizo', 'Paseo', 'Camino', + ) + postcode_formats = ('#####', ) + states = ( + 'Álava', + 'Albacete', + 'Alicante', + 'Almería', + 'Asturias', + 'Ávila', + 'Badajoz', + 'Baleares', + 'Barcelona', + 'Burgos', + 'Cáceres', + 'Cádiz', + 'Cantabria', + 'Castellón', + 'Ceuta', + 'Ciudad', + 'Córdoba', + 'Cuenca', + 'Girona', + 'Granada', + 'Guadalajara', + 'Guipúzcoa', + 'Huelva', + 'Huesca', + 'Jaén', + 'La Coruña', + 'La Rioja', + 'Las Palmas', + 'León', + 'Lleida', + 'Lugo', + 'Madrid', + 'Málaga', + 'Melilla', + 'Murcia', + 'Navarra', + 'Ourense', + 'Palencia', + 'Pontevedra', + 'Salamanca', + 'Santa Cruz de Tenerife', + 'Segovia', + 'Sevilla', + 'Soria', + 'Tarragona', + 'Teruel', + 'Toledo', + 'Valencia', + 'Valladolid', + 'Vizcaya', + 'Zamora', + 'Zaragoza') + + city_formats = ( + '{{state_name}}', + ) + + street_name_formats = ( + '{{street_prefix}} {{first_name}} {{last_name}}', + '{{street_prefix}} de {{first_name}} {{last_name}}', + + ) + street_address_formats = ( + '{{street_name}} {{building_number}}', + '{{street_name}} {{building_number}} {{secondary_address}} ', + ) + address_formats = ( + "{{street_address}}\n{{city}}, {{postcode}}", + ) + secondary_address_formats = ('Apt. ##', 'Piso #', 'Puerta #') + + def state_name(self): + return self.random_element(self.states) + + def street_prefix(self): + return self.random_element(self.street_prefixes) + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/es_MX/__init__.py b/testbed/joke2k__faker/faker/providers/address/es_MX/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..556536786e24abb1ecabe1f0fa45556df1577a82 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/es_MX/__init__.py @@ -0,0 +1,127 @@ +from collections import OrderedDict + +from ..es import Provider as AddressProvider + + +class Provider(AddressProvider): + city_prefixes = ('Sur', 'Norte') + city_adjectives = ('Nueva', 'Vieja') + city_suffixes = ('de la Montaña', 'los bajos', 'los altos') + street_prefixes = ( + 'Ampliación', 'Andador', 'Avenida', 'Boulevard', 'Calle', 'Callejón', + 'Calzada', 'Cerrada', 'Circuito', 'Circunvalación', 'Continuación', + 'Corredor', 'Diagonal', 'Eje vial', 'Pasaje', 'Peatonal', 'Periférico', + 'Privada', 'Prolongación', 'Retorno', 'Viaducto', + ) + building_number_formats = ('#####', '####', '###') + postcode_formats = ('#####', '#####-####') + + # States and abbrs from Mexico from INEGI + # http://www.inegi.org.mx/geo/contenidos/geoestadistica/CatalogoClaves.aspx + states = ( + ('AGS', 'Aguascalientes'), ('BC', 'Baja California'), + ('BCS', 'Baja California Sur'), ('CAMP', 'Campeche'), + ('COAH', 'Coahuila de Zaragoza'), ('COL', 'Colima'), + ('CHIS', 'Chiapas'), ('CHIH', 'Chihuahua'), + ('DF', 'Distrito Federal'), ('DGO', 'Durango'), + ('GTO', 'Guanajuato'), ('GRO', 'Guerrero'), ('HGO', 'Hidalgo'), + ('JAL', 'Jalisco'), ('MEX', 'México'), + ('MICH', 'Michoacán de Ocampo'), ('MOR', 'Morelos'), + ('NAY', 'Nayarit'), ('NL', 'Nuevo León'), ('OAX', 'Oaxaca'), + ('PUE', 'Puebla'), ('QRO', 'Querétaro'), + ('Q. ROO', 'Quintana Roo'), ('SLP', 'San Luis Potosí'), + ('SIN', 'Sinaloa'), ('SON', 'Sonora'), ('TAB', 'Tabasco'), + ('TAMPS', 'Tamaulipas'), ('TLAX', 'Tlaxcala'), + ('VER', 'Veracruz de Ignacio de la Llave'), + ('YUC', 'Yucatán'), ('ZAC', 'Zacatecas')) + + zip_codes = OrderedDict(( + # The ZipCodes has a begin & final range + # Source: Norma Técnica de Domicilios INEGI + ('AGS', (20000, 20999)), + ('BC', (21000, 22999)), + ('BCS', (23000, 23999)), + ('CAMP', (24000, 24999)), + ('COAH', (25000, 27999)), + ('COL', (28000, 28999)), + ('CHIS', (29000, 30999)), + ('CHIH', (31000, 33999)), + ('DF', (1000, 19999)), + ('DGO', (36000, 35999)), + ('GTO', (36000, 38999)), + ('GRO', (39000, 41999)), + ('HGO', (42000, 43999)), + ('JAL', (44000, 49999)), + ('MEX', (50000, 57999)), + ('MICH', (58000, 61999)), + ('MOR', (62000, 62999)), + ('NAY', (63000, 63999)), + ('NL', (64000, 67999)), + ('OAX', (68000, 71999)), + ('PUE', (72000, 75999)), + ('QRO', (76000, 76999)), + ('Q. ROO', (77000, 75999)), + ('SLP', (78000, 79999)), + ('SIN', (80000, 82999)), + ('SON', (83000, 85999)), + ('TAB', (86000, 86999)), + ('TAMPS', (87000, 89999)), + ('TLAX', (90000, 90999)), + ('VER', (91000, 97999)), + ('YUC', (97000, 97999)), + ('ZAC', (98000, 99999)), + )) + + city_formats = ( + '{{city_adjective}} {{country}}', + 'San {{first_name}} {{city_suffix}}', + ) + street_name_formats = ( + '{{street_prefix}} {{last_name}}', + '{{street_prefix}} {{country}}', + '{{street_prefix}} {{state}}', + '{{street_prefix}} {{city_prefix}} {{last_name}}', + ) + street_address_formats = ( + '{{street_name}} {{secondary_address}}', + ) + address_formats = ( + "{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", + ) + secondary_address_formats = ('### ###', '### Interior ###', + '### Edif. ### , Depto. ###') + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def city_suffix(self): + return self.random_element(self.city_suffixes) + + def city_adjective(self): + return self.random_element(self.city_adjectives) + + def street_prefix(self): + """ + :example 'Avenida' + """ + return self.random_element(self.street_prefixes) + + def secondary_address(self): + """ + :example '020 Interior 999' + """ + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def state(self): + """ + example: u'Guerrero' + """ + return self.random_element(self.states)[1] + + def state_abbr(self): + """ + example: u'GRO' + """ + return self.random_element(self.states)[0] diff --git a/testbed/joke2k__faker/faker/providers/address/fa_IR/__init__.py b/testbed/joke2k__faker/faker/providers/address/fa_IR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78fff9edada203ef666b211b0179655b3c4fb356 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/fa_IR/__init__.py @@ -0,0 +1,86 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_prefixes = ( + 'شمال', 'غرب', 'شرق', 'جنوب', 'بندر', 'شهر', 'روستای', 'دهستان', + 'شهرستان', 'باغات', 'استان', + ) + building_number_formats = ('#####', '####', '###') + street_suffixes = ( + 'کوچه', 'خیابان', 'پل', 'دره', 'میدان', 'چهار راه', 'بن بست', 'بلوار', + 'جنب', 'تقاطع', 'آزاد راه', 'بزرگ راه', 'جزیره', 'کوه', 'جاده', 'تونل', + ) + postcode_formats = ('###', '####', '#####', '######', '##########') + states = ( + 'آذربایجان شرقی', 'آذربایجان غربی', 'اردبیل', 'خراسان', 'کردستان', + 'گیلان', 'اصفهان', 'البرز', 'ایلام', 'بوشهر', 'تهران', + 'چهارمحال و بختیاری', 'خراسان جنوبی', 'خراسان رضوی', 'خراسان شمالی', + 'خوزستان', 'زنجان', 'سمنان', 'سیستان و بلوچستان', 'فارس', 'قزوین', 'قم', + 'کرمان', 'کرمانشاه', 'کهگیلویه و بویراحمد', 'گلستان', 'لرستان', + 'مازندران', 'مرکزی', 'هرمزگان', 'همدان', 'یزد', + ) + countries = ( + 'جمهوری آذربایجان', 'آرژانتین', 'آفریقای جنوبی', 'جمهوری آفریقای مرکزی', + 'آلبانی', 'آلمان', 'آنتیگوا و باربودا', 'آندورا', 'آنگولا', 'اتریش', + 'اتیوپی', 'اردن', 'ارمنستان', 'اروگوئه', 'اریتره', 'ازبکستان', + 'اسپانیا', 'استرالیا', 'استونی', 'اسرائیل', 'اسلواکی', 'اسلوونی', + 'افغانستان', 'اکوادور', 'الجزایر', 'السالوادور', 'امارات متحده عربی', + 'اندونزی', 'اوکراین', 'اوگاندا', 'ایالات متحده آمریکا', 'ایتالیا', + 'ایران', 'جمهوری ایرلند', 'ایسلند', 'باربادوس', 'باهاما', 'بحرین', + 'برزیل', 'برونئی', 'بریتانیا', 'بلاروس', 'بلژیک', 'بلغارستان', 'بلیز', + 'بنگلادش', 'بنین', 'پادشاهی بوتان', 'بوتسوانا', 'بورکینافاسو', + 'بوروندی', 'بوسنی و هرزگوین', 'بولیوی', 'پاپوآ گینه نو', 'پاراگوئه', + 'پاناما', 'پاکستان', 'پرتغال', 'پرو', 'پورتوریکو', 'تاجیکستان', + 'تانزانیا', 'تایلند', 'جمهوری چین', 'ترکمنستان', 'ترکیه', + 'ترینیداد و توباگو', 'توگو', 'تونس', 'تونگا', 'تووالو', 'تیمور شرقی', + 'جامائیکا', 'جزایر سلیمان', 'جزایر مارشال', 'جمهوری چک', + 'جمهوری دومینیکن', 'جیبوتی', 'چاد', 'چین', 'دانمارک', 'دومینیکا', + 'جمهوری دومینیکن', 'رواندا', 'روسیه', 'رومانی', 'زامبیا', 'نیوزیلند', + 'زیمباوه', 'جمهوری دموکراتیک کنگو (زئیر)', 'ژاپن', 'سائوتومه و پرینسیپ', + 'ساحل عاج', 'ساموآی غربی', 'سن مارینو', 'سری‌لانکا', 'سنت کیتس و نویس', + 'سنت لوسیا', 'سنت وینسنت و گرنادین‌ها', 'سنگاپور', 'سنگال', 'سوئد', + 'سوئیس', 'سوازیلند', 'سودان', 'سودان جنوبی', 'سورینام', 'سوریه', + 'سومالی', 'سیرالئون', 'سیشل', 'شیلی', 'صربستان', 'عراق', + 'عربستان سعودی', 'عمان', 'غنا', 'فرانسه', 'فلسطین', 'فنلاند', 'فیجی', + 'فیلیپین', 'قبرس', 'قرقیزستان', 'قزاقستان', 'قطر', 'کامبوج', 'کامرون', + 'کانادا', 'کره جنوبی', 'کره شمالی', 'کرواسی', 'کاستاریکا', 'کلمبیا', + 'جمهوری کنگو', 'جمهوری دموکراتیک کنگو', 'کنیا', 'کوبا', 'کوزوو', + 'مجمع‌الجزایر قمر', 'کویت', 'کیپ ورد', 'کیریباتی', 'گابن', 'گامبیا', + 'گرجستان', 'گرنادا', 'گرینلند(از مستعمرات دانمارک)', 'گواتمالا', + 'گویان', 'گینه', 'گینه استوایی', 'گینه بیسائو', 'لائوس', 'لبنان', + 'لتونی', 'لسوتو', 'لهستان', 'لوکزامبورگ', 'لیبریا', 'لیبی', 'لیتوانی', + 'لیختن‌اشتاین', 'ماداگاسکار', 'مالاوی', 'مالت', 'مالدیو', 'مالزی', + 'مالی', 'مجارستان', 'مراکش', 'مصر', 'مغولستان', 'مقدونیه', 'مکزیک', + 'موریتانی', 'موریس', 'موزامبیک', 'مولداوی', 'موناکو', 'مونته‌نگرو', + 'میانمار', 'ایالات فدرال میکرونزی', 'نائورو', 'نامیبیا', 'نپال', + 'نروژ', 'نیجریه', 'نیکاراگوئه', 'نیوزیلند', 'واتیکان', 'وانواتو', + 'ونزوئلا', 'ویتنام', 'هائیتی', 'هلند', 'هندوراس', 'هند', 'یمن', 'یونان', + ) + + city_formats = ( + '{{city_prefix}} {{first_name}}', + ) + street_name_formats = ( + '{{first_name}} {{street_suffix}}', + '{{last_name}} {{street_suffix}}', + ) + street_address_formats = ( + '{{building_number}} {{street_name}}', + '{{building_number}} {{street_name}} {{secondary_address}}', + ) + address_formats = ( + "{{street_address}}\n{{city}}, {{state}} {{postcode}}", + ) + secondary_address_formats = ('سوئیت ###', 'واحد ###') + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/fi_FI/__init__.py b/testbed/joke2k__faker/faker/providers/address/fi_FI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ecf4bfbeddaeab08287399b0c3a4c6842cf891 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/fi_FI/__init__.py @@ -0,0 +1,162 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + building_number_formats = ('###', '##', '#') + + postcode_formats = ('#####', ) + + city_formats = ('{{city_name}}', ) + + street_name_formats = ('{{street_prefix}}{{street_suffix}}', ) + + street_address_formats = ('{{street_name}} {{building_number}}', ) + + address_formats = ("{{street_address}}\n{{postcode}} {{city}}", ) + + # Data from: + # https://www.avoindata.fi/data/en/dataset/kunnat/resource/b1cb9870-191f-4616-9c53-5388b7ca6beb + cities = ( + 'Alajärvi', 'Alavieska', 'Alavus', 'Asikkala', 'Askola', 'Aura', 'Akaa', 'Brändö', 'Eckerö', 'Enonkoski', + 'Enontekiö', 'Espoo', 'Eura', 'Eurajoki', 'Evijärvi', 'Finström', 'Forssa', 'Föglö', 'Geta', 'Haapajärvi', + 'Haapavesi', 'Hailuoto', 'Halsua', 'Hamina', 'Hammarland', 'Hankasalmi', 'Hanko', 'Harjavalta', 'Hartola', + 'Hattula', 'Hausjärvi', 'Heinävesi', 'Helsinki', 'Vantaa', 'Hirvensalmi', 'Hollola', 'Honkajoki', 'Huittinen', + 'Humppila', 'Hyrynsalmi', 'Hyvinkää', 'Hämeenkyrö', 'Hämeenlinna', 'Heinola', 'Ii', 'Iisalmi', 'Iitti', + 'Ikaalinen', 'Ilmajoki', 'Ilomantsi', 'Inari', 'Inkoo', 'Isojoki', 'Isokyrö', 'Imatra', 'Janakkala', 'Joensuu', + 'Jokioinen', 'Jomala', 'Joroinen', 'Joutsa', 'Juuka', 'Juupajoki', 'Juva', 'Jyväskylä', 'Jämijärvi', 'Jämsä', + 'Järvenpää', 'Kaarina', 'Kaavi', 'Kajaani', 'Kalajoki', 'Kangasala', 'Kangasniemi', 'Kankaanpää', 'Kannonkoski', + 'Kannus', 'Karijoki', 'Karkkila', 'Karstula', 'Karvia', 'Kaskinen', 'Kauhajoki', 'Kauhava', 'Kauniainen', + 'Kaustinen', 'Keitele', 'Kemi', 'Keminmaa', 'Kempele', 'Kerava', 'Keuruu', 'Kihniö', 'Kinnula', 'Kirkkonummi', + 'Kitee', 'Kittilä', 'Kiuruvesi', 'Kivijärvi', 'Kokemäki', 'Kokkola', 'Kolari', 'Konnevesi', 'Kontiolahti', + 'Korsnäs', 'Koski Tl', 'Kotka', 'Kouvola', 'Kristiinankaupunki', 'Kruunupyy', 'Kuhmo', 'Kuhmoinen', 'Kumlinge', + 'Kuopio', 'Kuortane', 'Kurikka', 'Kustavi', 'Kuusamo', 'Outokumpu', 'Kyyjärvi', 'Kärkölä', 'Kärsämäki', 'Kökar', + 'Kemijärvi', 'Kemiönsaari', 'Lahti', 'Laihia', 'Laitila', 'Lapinlahti', 'Lappajärvi', 'Lappeenranta', + 'Lapinjärvi', 'Lapua', 'Laukaa', 'Lemi', 'Lemland', 'Lempäälä', 'Leppävirta', 'Lestijärvi', 'Lieksa', 'Lieto', + 'Liminka', 'Liperi', 'Loimaa', 'Loppi', 'Loviisa', 'Luhanka', 'Lumijoki', 'Lumparland', 'Luoto', 'Luumäki', + 'Lohja', 'Parainen', 'Maalahti', 'Maarianhamina', 'Marttila', 'Masku', 'Merijärvi', 'Merikarvia', 'Miehikkälä', + 'Mikkeli', 'Muhos', 'Multia', 'Muonio', 'Mustasaari', 'Muurame', 'Mynämäki', 'Myrskylä', 'Mäntsälä', + 'Mäntyharju', 'Mänttä-Vilppula', 'Naantali', 'Nakkila', 'Nivala', 'Nokia', 'Nousiainen', 'Nurmes', 'Nurmijärvi', + 'Närpiö', 'Orimattila', 'Oripää', 'Orivesi', 'Oulainen', 'Oulu', 'Padasjoki', 'Paimio', 'Paltamo', 'Parikkala', + 'Parkano', 'Pelkosenniemi', 'Perho', 'Pertunmaa', 'Petäjävesi', 'Pieksämäki', 'Pielavesi', 'Pietarsaari', + 'Pedersören kunta', 'Pihtipudas', 'Pirkkala', 'Polvijärvi', 'Pomarkku', 'Pori', 'Pornainen', 'Posio', + 'Pudasjärvi', 'Pukkila', 'Punkalaidun', 'Puolanka', 'Puumala', 'Pyhtää', 'Pyhäjoki', 'Pyhäjärvi', 'Pyhäntä', + 'Pyhäranta', 'Pälkäne', 'Pöytyä', 'Porvoo', 'Raahe', 'Raisio', 'Rantasalmi', 'Ranua', 'Rauma', 'Rautalampi', + 'Rautavaara', 'Rautjärvi', 'Reisjärvi', 'Riihimäki', 'Ristijärvi', 'Rovaniemi', 'Ruokolahti', 'Ruovesi', + 'Rusko', 'Rääkkylä', 'Raasepori', 'Saarijärvi', 'Salla', 'Salo', 'Saltvik', 'Sauvo', 'Savitaipale', + 'Savonlinna', 'Savukoski', 'Seinäjoki', 'Sievi', 'Siikainen', 'Siikajoki', 'Siilinjärvi', 'Simo', 'Sipoo', + 'Siuntio', 'Sodankylä', 'Soini', 'Somero', 'Sonkajärvi', 'Sotkamo', 'Sottunga', 'Sulkava', 'Sund', + 'Suomussalmi', 'Suonenjoki', 'Sysmä', 'Säkylä', 'Vaala', 'Sastamala', 'Siikalatva', 'Taipalsaari', + 'Taivalkoski', 'Taivassalo', 'Tammela', 'Tampere', 'Tervo', 'Tervola', 'Teuva', 'Tohmajärvi', 'Toholampi', + 'Toivakka', 'Tornio', 'Turku', 'Pello', 'Tuusniemi', 'Tuusula', 'Tyrnävä', 'Ulvila', 'Urjala', 'Utajärvi', + 'Utsjoki', 'Uurainen', 'Uusikaarlepyy', 'Uusikaupunki', 'Vaasa', 'Valkeakoski', 'Valtimo', 'Varkaus', 'Vehmaa', + 'Vesanto', 'Vesilahti', 'Veteli', 'Vieremä', 'Vihti', 'Viitasaari', 'Vimpeli', 'Virolahti', 'Virrat', 'Värdö', + 'Vöyri', 'Ylitornio', 'Ylivieska', 'Ylöjärvi', 'Ypäjä', 'Ähtäri', 'Äänekoski', + ) + + countries = ( + 'Afganistan', 'Alankomaat', 'Albania', 'Algeria', 'Andorra', 'Angola', + 'Antigua ja Barbuda', 'Argentiina', 'Armenia', 'Australia', + 'Azerbaidžan', 'Bahama', 'Bahrain', 'Bangladesh', 'Barbados', 'Belgia', + 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia ja Hertsegovina', + 'Botswana', 'Brasilia', 'Brunei', 'Bulgaria', 'Burkina', 'Faso', + 'Burundi', 'Chile', 'Costa', 'Rica', 'Djibouti', 'Dominica', + 'Dominikaaninen tasavalta', 'Ecuador', 'Egypti', 'El', 'Salvador', + 'Eritrea', 'Espanja', 'Etelä-Afrikka', 'Korean tasavalta', + 'Etelä-Sudan', 'Etiopia', 'Fidži', 'Filippiinit', 'Gabon', 'Gambia', + 'Georgia', 'Ghana', 'Grenada', 'Guatemala', 'Guinea-Bissau', 'Guinea', + 'Guyana', 'Haiti', 'Honduras', 'Indonesia', 'Intia', 'Irak', 'Iran', + 'Irlanti', 'Islanti', 'Israel', 'Italia', 'Itä-Timor', 'Itävalta', + 'Jamaika', 'Japani', 'Jemen', 'Jordania', 'Kambodža', 'Kamerun', + 'Kanada', 'Kap', 'Verde', 'Kazakstan', 'Kenia', + 'Keski-Afrikan tasavalta', 'Kiina', 'Kirgisia', 'Kiribati', + 'Kolumbia', 'Komorit', 'Kongon demokraattinen tasavalta', + 'Kongon tasavalta', 'Kosovo', 'Kreikka', 'Kroatia', 'Kuuba', 'Kuwait', + 'Kypros', 'Laos', 'Latvia', 'Lesotho', 'Libanon', 'Liberia', 'Libya', + 'Liechtenstein', 'Liettua', 'Luxemburg', 'Madagaskar', 'Makedonia', + 'Malawi', 'Malediivit', 'Malesia', 'Mali', 'Malta', 'Marokko', + 'Marshallinsaaret', 'Mauritania', 'Mauritius', 'Meksiko', 'Mikronesia', + 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Mosambik', 'Myanmar', + 'Namibia', 'Nauru', 'Nepal', 'Nicaragua', 'Nigeria', 'Niger', 'Norja', + 'Norsunluurannikko', 'Oman', 'Pakistan', 'Palau', 'Panama', + 'Papua-Uusi-Guinea', 'Paraguay', 'Peru', + 'Korean demokraattinen kansantasavalta', 'Portugali', 'Puola', + 'Päiväntasaajan Guinea', 'Qatar', 'Ranska', 'Romania', 'Ruanda', + 'Ruotsi', 'Saint Kitts ja Nevis', 'Saint Lucia', + 'Saint Vincent ja Grenadiinit', 'Saksa', 'Salomonsaaret', 'Sambia', + 'Samoa', 'San Marino', 'São Tomé ja Príncipe', + 'Saudi-Arabia', 'Senegal', 'Serbia', 'Seychellit', 'Sierra', 'Leone', + 'Singapore', 'Slovakia', 'Slovenia', 'Somalia', 'Sri', 'Lanka', 'Sudan', + 'Suomi', 'Suriname', 'Swazimaa', 'Sveitsi', 'Syyria', 'Tadžikistan', + 'Tansania', 'Tanska', 'Thaimaa', 'Togo', 'Tonga', 'Trinidad ja Tobago', + 'Tšad', 'Tšekki', 'Tunisia', 'Turkki', 'Turkmenistan', 'Tuvalu', + 'Uganda', 'Ukraina', 'Unkari', 'Uruguay', 'Uusi-Seelanti', 'Uzbekistan', + 'Valko-Venäjä', 'Vanuatu', 'Vatikaanivaltio', 'Venezuela', 'Venäjä', + 'Vietnam', 'Viro', 'Yhdistyneet arabiemiirikunnat', + 'Yhdistynyt kuningaskunta', 'Yhdysvallat', 'Zimbabwe', + ) + + states = ( + 'Turun ja Porin lääni', 'Uudenmaan ja Hämeen lääni', 'Pohjanmaan lääni', + 'Viipurin ja Savonlinnan lääni', 'Käkisalmen lääni', + 'Savonlinnan ja Kymenkartanon lääni', 'Kymenkartanon ja Savon lääni', + 'Vaasan lääni', 'Oulun lääni', 'Kymenkartanon lääni', + 'Savon ja Karjalan lääni', 'Viipurin lääni', 'Uudenmaan lääni', + 'Hämeen lääni', 'Mikkelin lääni', 'Kuopion lääni', 'Ahvenanmaan lääni', + 'Petsamon lääni', 'Lapin lääni', 'Kymen lääni', 'Keski-Suomen lääni', + 'Pohjois-Karjalan lääni', 'Etelä-Suomen lääni', 'Länsi-Suomen lääni', + 'Itä-Suomen lääni', '', 'Turun ja Porin lääni', + 'Uudenmaan ja Hämeen lääni', 'Pohjanmaan lääni', + 'Viipurin ja Savonlinnan lääni', 'Käkisalmen lääni', + 'Savonlinnan ja Kymenkartanon lääni', 'Kymenkartanon ja Savon lääni', + 'Vaasan lääni', 'Oulun lääni', 'Kymenkartanon lääni', + 'Savon ja Karjalan lääni', 'Viipurin lääni', 'Uudenmaan lääni', + 'Hämeen lääni', 'Mikkelin lääni', 'Kuopion lääni', 'Ahvenanmaan lääni', + 'Petsamon lääni', 'Lapin lääni', 'Kymen lääni', 'Keski-Suomen lääni', + 'Pohjois-Karjalan lääni', 'Etelä-Suomen lääni', 'Länsi-Suomen lääni', + 'Itä-Suomen lääni', + ) + + street_suffixes = ('tie', 'katu', 'polku', 'kuja', 'bulevardi') + + # Prefixes parsed from a street list of Helsinki: + # http://kartta.hel.fi/ws/geoserver/avoindata/wfs?outputFormat=application/json&REQUEST=GetFeature&typeNames=avoindata:Helsinki_osoiteluettelo + + street_prefixes = ( + 'Adolf Lindforsin ', 'Agnes Sjöbergin ', 'Agnetan', 'Agricolan', 'Ahomäen', 'Ahvenkosken', 'Aidasmäen', + 'Agroksen', 'Agronomin', 'Ahdekaunokin', 'Bertel Jungin ', 'Bertha Pauligin ', 'Betlehemin', 'Betoni', + 'Biologin', 'Birger Kaipiaisen ', 'Bysantin', 'Böstaksen', 'Bengalin', 'Benktan', 'Bergan', 'Caloniuksen', + 'Capellan puisto', 'Castrénin', 'Chydeniuksen', 'Cygnaeuksen', 'Dagmarin', 'Damaskuksen', 'Degermosan', 'Disan', + 'Dosentin', 'Dunckerin', 'Döbelnin', 'Ehrensvärdin', 'Eino Leinon ', 'Elimäen', 'Elisabeth Kochin ', 'Eljaksen', + 'Elon', 'Elon', 'Edelfeltin', 'Eduskunta', 'Eerik Pyhän ', 'Franzénin', 'Fredrikin', 'Freesen', + 'Fabianin', 'Fagotti', 'Fahlanderin puisto', 'Fallin', 'Fallkullan', 'Fallpakan', 'Fastbölen', 'Gadolinin', + 'Gneissi', 'Granfeltin', 'Gunillan', 'Gunnel Nymanin ', 'Graniitti', 'Gustav Pauligin ', 'Gyldénin', + 'Gotlannin', 'Haapa', 'Haagan pappilan', 'Haahka', 'Haakoninlahden', 'Haaksi', 'Hankasuon', 'Hannukselan', + 'Harakkamyllyn', 'Harava', 'Harbon', 'Ilmattaren', 'Ilomäen', 'Ilotulitus', 'Iltaruskon', 'Iltatähden', 'Ilves', + 'Immolan', 'Ilkan', 'Ida Ekmanin ', 'Ies', 'Jälsi', 'Jämsän', 'Jänkä', 'Jänne', 'Järkäle', 'Jätkäsaaren', + 'Jättiläisen', 'Jyvä', 'Jägerhornin', 'Jäkälä', 'Kukkaniityn', 'Kolsin', 'Kolu', 'Kolvi', 'Kuhankeittäjän', + 'Katajaharjun', 'Kiitäjän', 'Kilpolan', 'Kimalais', 'Kimmon', 'Laajasalon', 'Laakavuoren', 'Lemun', + 'Lentokapteenin ', 'Lepolan', 'Louhen', 'Louhikko', 'Lukkarimäen', 'Laurinniityn', 'Lautamiehen', + 'Mamsellimyllyn', 'Mannerheimin', 'Maanmittarin', 'Maapadon', 'Maa', 'Maasalon', 'Maasälvän', 'Maatullin', + 'Malminkartanon', 'Maneesi', 'Niittylän', 'Niemi', 'Niitynperän', 'Nikon', 'Nils Westermarckin ', + 'Nordenskiöldin', 'Nelikko', 'Neon', 'Nervanderin', 'Neulapadon', 'Ostos', 'Orapihlaja', 'Oras', 'Orava', + 'Osmon', 'Osuuskunnan', 'Orisaaren', 'Ormus', 'Orvokki', 'Oterman', 'Pore', 'Porin', 'Porkkalan', 'Pyörökiven', + 'Puusepän', 'Puuska', 'Pohjolan', 'Poikasaarten', 'Purjetuulen', 'Puroniityn', 'Rukkilan', 'Ruko', + 'Rukoushuoneen', 'Runebergin', 'Runoilijan', 'Runokylän', 'Runonlaulajan', 'Rantavaraston', 'Rapakiven', + 'Rapolan', 'Santerlan', 'Saparon', 'Sapilas', 'Saramäen', 'Saanatunturin', 'Sade', 'Sahaajan', 'Salakka', + 'Salama', 'Salava', 'Tuomarinkylän', 'Tuulilasin', 'Taavetti Laitisen ', 'Taavin', 'Tahti', 'Taimiston', + 'Tukkisillan', 'Tuohikoivun', 'Tyynelän', 'Tyynylaavan', 'Uussillan', 'Urheilu', 'Urkurin', 'Urpu', 'Uskalikon', + 'Usva', 'Uudenkaupungin', 'Uunilinnun', 'Uunisepän', 'Uurtajan', 'Vanha Raja', 'Veropellon', 'Veräjämäen', + 'Vesakko', 'Vesalan', 'Vellikellon', 'Verkko', 'Verso', 'Vaakalinnun', 'Vaarna', 'Wavulinin', + 'Walentin Chorellin ', 'Wallinin', 'Waseniuksen puisto', 'Wecksellin', 'Willebrandin', 'Winqvistin', + 'Wäinö Aaltosen ', 'Werner Wirénin ', 'Yhteiskoulun', 'Ylipalon', 'Yllästunturin', 'Ylä-Fallin ', 'Yläkasken', + 'Ylänkö', 'Ylätuvan', 'Yrjö-Koskisen ', 'Yrjön', 'Yrttimaan', 'Zaidan', + ) + + def street_prefix(self): + return self.random_element(self.street_prefixes) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/fil_PH/__init__.py b/testbed/joke2k__faker/faker/providers/address/fil_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10fd37a784a9cf241ca82695ef429bb1d06d95a0 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/fil_PH/__init__.py @@ -0,0 +1,6 @@ +from ..en_PH import Provider as EnPhAddressProvider + + +class Provider(EnPhAddressProvider): + """No difference from Address Provider for en_PH locale""" + pass diff --git a/testbed/joke2k__faker/faker/providers/address/fr_CH/__init__.py b/testbed/joke2k__faker/faker/providers/address/fr_CH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dcfea192dee95ee5565d6e2f8518db880cac3f47 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/fr_CH/__init__.py @@ -0,0 +1,131 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_suffixes = ('-des-Bois', '-les-Bains', '-la-Ville', '-Dessus', + '-Dessous', ' am Rhein', ' am See', ' am Albis', + ' an der Aare') + city_prefixes = ('Saint ', 'Sainte ', 'San ', 'Ober', 'Unter') + street_prefixes = ('rue', 'rue', 'chemin', 'avenue', 'boulevard') + + address_formats = ("{{street_address}}\n{{postcode}} {{city}}", ) + + building_number_formats = ('%', '%#', '%#', '%#', '%##') + + city_formats = ('{{last_name}}', '{{last_name}}', '{{last_name}}', + '{{last_name}}', '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}-près-{{last_name}}', + '{{last_name}}-sur-{{last_name}}', + '{{city_prefix}}{{last_name}}', + '{{last_name}} ({{canton_code}})') + + street_address_formats = ('{{street_name}}', + '{{street_name}} {{building_number}}', + '{{street_name}} {{building_number}}', + '{{street_name}} {{building_number}}', + '{{street_name}} {{building_number}}', + '{{street_name}} {{building_number}}') + street_name_formats = ('{{street_prefix}} {{last_name}}', + '{{street_prefix}} {{first_name}} {{last_name}}', + '{{street_prefix}} de {{last_name}}') + + postcode_formats = ('1###', '2###', '3###', '4###', '5###', '6###', '7###', + '8###', '9###') + + cantons = (('AG', 'Argovie'), ('AI', 'Appenzell Rhodes-Intérieures'), + ('AR', 'Appenzell Rhodes-Extérieures'), ('BE', 'Berne'), + ('BL', 'Bâle-Campagne'), ('BS', 'Bâle-Ville'), ('FR', 'Fribourg'), + ('GE', 'Genève'), ('GL', 'Glaris'), ('GR', 'Grisons'), ('JU', 'Jura'), + ('LU', 'Lucerne'), ('NE', 'Neuchâtel'), ('NW', 'Nidwald'), ('OW', 'Obwald'), + ('SG', 'Saint-Gall'), ('SH', 'Schaffhouse'), ('SO', 'Soleure'), + ('SZ', 'Schwytz'), ('TG', 'Thurgovie'), ('TI', 'Tessin'), ('UR', 'Uri'), + ('VD', 'Vaud'), ('VS', 'Valais'), ('ZG', 'Zoug'), ('ZH', 'Zurich')) + + countries = ( + 'Afghanistan', 'Afrique du sud', 'Albanie', 'Algérie', 'Allemagne', + 'Andorre', 'Angola', 'Anguilla', 'Antarctique', 'Antigua et Barbuda', + 'Antilles néerlandaises', 'Arabie saoudite', 'Argentine', 'Arménie', + 'Aruba', 'Australie', 'Autriche', 'Azerbaïdjan', 'Bahamas', 'Bahrain', + 'Bangladesh', 'Belgique', 'Belize', 'Benin', 'Bermudes (Les)', + 'Bhoutan', 'Biélorussie', 'Bolivie', 'Bosnie-Herzégovine', 'Botswana', + 'Bouvet (Îles)', 'Brunei', 'Brésil', 'Bulgarie', 'Burkina Faso', + 'Burundi', 'Cambodge', 'Cameroun', 'Canada', 'Cap Vert', + 'Cayman (Îles)', 'Chili', 'Chine (Rép. pop.)', 'Christmas (Île)', + 'Chypre', 'Cocos (Îles)', 'Colombie', 'Comores', 'Cook (Îles)', + 'Corée du Nord', 'Corée, Sud', 'Costa Rica', 'Croatie', 'Cuba', + 'Côte d\'Ivoire', 'Danemark', 'Djibouti', 'Dominique', 'Égypte', + 'El Salvador', 'Émirats arabes unis', 'Équateur', 'Érythrée', + 'Espagne', 'Estonie', 'États-Unis', 'Ethiopie', 'Falkland (Île)', + 'Fidji (République des)', 'Finlande', 'France', + 'Féroé (Îles)', 'Gabon', 'Gambie', 'Ghana', 'Gibraltar', 'Grenade', + 'Groenland', 'Grèce', 'Guadeloupe', 'Guam', 'Guatemala', 'Guinée', + 'Guinée Equatoriale', 'Guinée-Bissau', 'Guyane', 'Guyane française', + 'Géorgie', 'Géorgie du Sud et Sandwich du Sud (Îles)', 'Haïti', + 'Heard et McDonald (Îles)', 'Honduras', 'Hong Kong', 'Hongrie', + 'Îles Mineures Éloignées des États-Unis', 'Inde', 'Indonésie', 'Irak', + 'Iran', 'Irlande', 'Islande', 'Israël', 'Italie', 'Jamaïque', 'Japon', + 'Jordanie', 'Kazakhstan', 'Kenya', 'Kirghizistan', 'Kiribati', + 'Koweit', 'La Barbad', 'Laos', 'Lesotho', 'Lettonie', 'Liban', 'Libye', + 'Libéria', 'Liechtenstein', 'Lithuanie', 'Luxembourg', 'Macau', + 'Macédoine', 'Madagascar', 'Malaisie', 'Malawi', 'Maldives (Îles)', + 'Mali', 'Malte', 'Mariannes du Nord (Îles)', 'Maroc', + 'Marshall (Îles)', 'Martinique', 'Maurice', 'Mauritanie', 'Mayotte', + 'Mexique', 'Micronésie (États fédérés de)', 'Moldavie', 'Monaco', + 'Mongolie', 'Montserrat', 'Mozambique', 'Myanmar', 'Namibie', 'Nauru', + 'Nepal', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk (Îles)', + 'Norvège', 'Nouvelle Calédonie', 'Nouvelle-Zélande', 'Oman', 'Ouganda', + 'Ouzbékistan', 'Pakistan', 'Palau', 'Panama', + 'Papouasie-Nouvelle-Guinée', 'Paraguay', 'Pays-Bas', 'Philippines', + 'Pitcairn (Îles)', 'Pologne', 'Polynésie française', 'Porto Rico', + 'Portugal', 'Pérou', 'Qatar', 'Roumanie', 'Royaume-Uni', 'Russie', + 'Rwanda', 'Rép. Dém. du Congo', 'République centrafricaine', + 'République Dominicaine', 'République tchèque', 'Réunion (La)', + 'Sahara Occidental', 'Saint Pierre et Miquelon', + 'Saint Vincent et les Grenadines', 'Saint-Kitts et Nevis', + 'Saint-Marin (Rép. de)', 'Sainte Hélène', 'Sainte Lucie', 'Samoa', + 'Samoa', 'Seychelles', 'Sierra Leone', 'Singapour', 'Slovaquie', + 'Slovénie', 'Somalie', 'Soudan', 'Sri Lanka', 'Suisse', 'Suriname', + 'Suède', 'Svalbard et Jan Mayen (Îles)', 'Swaziland', 'Syrie', + 'São Tomé et Príncipe (Rép.)', 'Sénégal', 'Tadjikistan', 'Taiwan', + 'Tanzanie', 'Tchad', 'Territoire britannique de l\'océan Indien', + 'Territoires français du sud', 'Thailande', 'Timor', 'Togo', 'Tokelau', + 'Tonga', 'Trinité et Tobago', 'Tunisie', 'Turkménistan', + 'Turks et Caïques (Îles)', 'Turquie', 'Tuvalu', 'Ukraine', 'Uruguay', + 'Vanuatu', 'Vatican (Etat du)', 'Venezuela', 'Vierges (Îles)', + 'Vierges britanniques (Îles)', 'Vietnam', 'Wallis et Futuna (Îles)', + 'Yemen', 'Yougoslavie', 'Zambie', 'Zaïre', 'Zimbabwe') + + def street_prefix(self): + """ + :example 'rue' + """ + return self.random_element(self.street_prefixes) + + def city_prefix(self): + """ + :example 'rue' + """ + return self.random_element(self.city_prefixes) + + def canton(self): + """ + Randomly returns a swiss canton ('Abbreviated' , 'Name'). + :example ('VD' . 'Vaud') + """ + return self.random_element(self.cantons) + + def canton_name(self): + """ + Randomly returns a Swiss canton name. + :example 'Vaud' + """ + return self.canton()[1] + + def canton_code(self): + """ + Randomly returns a Swiss canton code. + :example 'VD' + """ + return self.canton()[0] diff --git a/testbed/joke2k__faker/faker/providers/address/fr_FR/__init__.py b/testbed/joke2k__faker/faker/providers/address/fr_FR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca2f9fce3725d6eaf0f606b5c68aab599999f98 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/fr_FR/__init__.py @@ -0,0 +1,176 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_suffixes = ('Ville', 'Bourg', '-les-Bains', + '-sur-Mer', '-la-Forêt', 'boeuf', 'nec', 'dan') + city_prefixes = ('Saint', 'Sainte') + street_prefixes = ('rue', 'rue', 'chemin', 'avenue', 'boulevard') + city_formats = ( + '{{city_prefix}} {{first_name}}', + '{{city_prefix}} {{first_name}}{{city_suffix}}', + '{{last_name}}', + '{{last_name}}', + '{{last_name}}', + '{{last_name}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}{{city_suffix}}', + '{{last_name}}-sur-{{last_name}}', + ) + street_name_formats = ( + '{{street_prefix}} {{last_name}}', + '{{street_prefix}} {{first_name}} {{last_name}}', + '{{street_prefix}} de {{last_name}}', + ) + + street_address_formats = ( + '{{street_name}}', + '{{building_number}}, {{street_name}}', + '{{building_number}}, {{street_name}}', + '{{building_number}}, {{street_name}}', + '{{building_number}}, {{street_name}}', + '{{building_number}}, {{street_name}}', + ) + + address_formats = ( + "{{street_address}}\n{{postcode}} {{city}}", + ) + + building_number_formats = ('%', '%#', '%#', '%#', '%##') + postcode_formats = ('#####', ) + countries = ( + 'Afghanistan', 'Afrique du sud', 'Albanie', 'Algérie', 'Allemagne', 'Andorre', 'Angola', 'Anguilla', + 'Antarctique', 'Antigua et Barbuda', 'Antilles néerlandaises', 'Arabie saoudite', 'Argentine', 'Arménie', + 'Aruba', 'Australie', 'Autriche', 'Azerbaïdjan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Belgique', 'Belize', + 'Benin', 'Bermudes (Les)', 'Bhoutan', 'Biélorussie', 'Bolivie', 'Bosnie-Herzégovine', 'Botswana', + 'Bouvet (Îles)', 'Brunei', 'Brésil', 'Bulgarie', 'Burkina Faso', 'Burundi', 'Cambodge', 'Cameroun', 'Canada', + 'Cap Vert', 'Cayman (Îles)', 'Chili', 'Chine (Rép. pop.)', 'Christmas (Île)', 'Chypre', 'Cocos (Îles)', + 'Colombie', 'Comores', 'Cook (Îles)', 'Corée du Nord', 'Corée, Sud', 'Costa Rica', 'Croatie', 'Cuba', + 'Côte d\'Ivoire', 'Danemark', 'Djibouti', 'Dominique', 'Égypte', 'El Salvador', 'Émirats arabes unis', + 'Équateur', 'Érythrée', 'Espagne', 'Estonie', 'États-Unis', 'Ethiopie', 'Falkland (Île)', + 'Fidji (République des)', 'Finlande', 'France', 'Féroé (Îles)', 'Gabon', + 'Gambie', 'Ghana', 'Gibraltar', 'Grenade', 'Groenland', 'Grèce', 'Guadeloupe', 'Guam', 'Guatemala', 'Guinée', + 'Guinée Equatoriale', 'Guinée-Bissau', 'Guyane', 'Guyane française', 'Géorgie', + 'Géorgie du Sud et Sandwich du Sud (Îles)', 'Haïti', 'Heard et McDonald (Îles)', 'Honduras', 'Hong Kong', + 'Hongrie', 'Îles Mineures Éloignées des États-Unis', 'Inde', 'Indonésie', 'Irak', 'Iran', 'Irlande', 'Islande', + 'Israël', 'Italie', 'Jamaïque', 'Japon', 'Jordanie', 'Kazakhstan', 'Kenya', 'Kirghizistan', 'Kiribati', + 'Koweit', 'La Barbad', 'Laos', 'Lesotho', 'Lettonie', 'Liban', 'Libye', 'Libéria', 'Liechtenstein', 'Lithuanie', + 'Luxembourg', 'Macau', 'Macédoine', 'Madagascar', 'Malaisie', 'Malawi', 'Maldives (Îles)', 'Mali', 'Malte', + 'Mariannes du Nord (Îles)', 'Maroc', 'Marshall (Îles)', 'Martinique', 'Maurice', 'Mauritanie', 'Mayotte', + 'Mexique', 'Micronésie (États fédérés de)', 'Moldavie', 'Monaco', 'Mongolie', 'Montserrat', 'Mozambique', + 'Myanmar', 'Namibie', 'Nauru', 'Nepal', + 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk (Îles)', 'Norvège', 'Nouvelle Calédonie', 'Nouvelle-Zélande', + 'Oman', 'Ouganda', 'Ouzbékistan', 'Pakistan', 'Palau', 'Panama', 'Papouasie-Nouvelle-Guinée', 'Paraguay', + 'Pays-Bas', 'Philippines', 'Pitcairn (Îles)', 'Pologne', 'Polynésie française', 'Porto Rico', 'Portugal', + 'Pérou', 'Qatar', 'Roumanie', 'Royaume-Uni', 'Russie', 'Rwanda', 'Rép. Dém. du Congo', + 'République centrafricaine', 'République Dominicaine', 'République tchèque', 'Réunion (La)', + 'Sahara Occidental', 'Saint Pierre et Miquelon', 'Saint Vincent et les Grenadines', 'Saint-Kitts et Nevis', + 'Saint-Marin (Rép. de)', 'Sainte Hélène', 'Sainte Lucie', 'Samoa', 'Samoa', 'Seychelles', 'Sierra Leone', + 'Singapour', 'Slovaquie', 'Slovénie', 'Somalie', 'Soudan', 'Sri Lanka', 'Suisse', 'Suriname', 'Suède', + 'Svalbard et Jan Mayen (Îles)', 'Swaziland', 'Syrie', 'São Tomé et Príncipe (Rép.)', 'Sénégal', 'Tadjikistan', + 'Taiwan', 'Tanzanie', 'Tchad', + 'Territoire britannique de l\'océan Indien', 'Territoires français du sud', 'Thailande', 'Timor', 'Togo', + 'Tokelau', 'Tonga', 'Trinité et Tobago', 'Tunisie', 'Turkménistan', 'Turks et Caïques (Îles)', 'Turquie', + 'Tuvalu', 'Ukraine', 'Uruguay', 'Vanuatu', 'Vatican (Etat du)', 'Venezuela', 'Vierges (Îles)', + 'Vierges britanniques (Îles)', 'Vietnam', 'Wallis et Futuna (Îles)', 'Yemen', 'Yougoslavie', 'Zambie', 'Zaïre', + 'Zimbabwe', + ) + regions = ( + 'Alsace', + 'Aquitaine', + 'Auvergne', + 'Bourgogne', + 'Bretagne', + 'Centre', + 'Champagne-Ardenne', + 'Corse', + 'Franche-Comté', + 'Île-de-France', + 'Languedoc-Roussillon', + 'Limousin', + 'Lorraine', + 'Midi-Pyrénées', + 'Nord-Pas-de-Calais', + 'Basse-Normandie', + 'Haute-Normandie', + 'Pays-de-Loire', + 'Picardie', + 'Poitou-Charentes', + "Province-Alpes-Côte d'Azur", + 'Rhone-Alpes', + 'Guadeloupe', + 'Martinique', + 'Guyane', + 'Réunion', + 'Saint-Pierre-et-Miquelon', + 'Mayotte', + 'Saint-Barthélémy', + 'Saint-Martin', + 'Wallis-et-Futuna', + 'Polynésie française', + 'Nouvelle-Calédonie') + + departments = ( + ('01', 'Ain'), ('02', 'Aisne'), ('03', 'Allier'), ('04', 'Alpes-de-Haute-Provence'), ('05', 'Hautes-Alpes'), + ('06', 'Alpes-Maritimes'), ('07', 'Ardèche'), ('08', 'Ardennes'), ('09', 'Ariège'), ('10', 'Aube'), + ('11', 'Aude'), ('12', 'Aveyron'), ('13', 'Bouches-du-Rhône'), ('14', 'Calvados'), ('15', 'Cantal'), + ('16', 'Charente'), ('17', 'Charente-Maritime'), ('18', 'Cher'), ('19', 'Corrèze'), ('2A', 'Corse-du-Sud'), + ('2B', 'Haute-Corse'), ('21', "Côte-d'Or"), ('22', "Côtes-d'Armor"), ('23', 'Creuse'), ('24', 'Dordogne'), + ('25', 'Doubs'), ('26', 'Drôme'), ('27', 'Eure'), ('28', 'Eure-et-Loir'), ('29', 'Finistère'), ('30', 'Gard'), + ('31', 'Haute-Garonne'), ('32', 'Gers'), ('33', 'Gironde'), ('34', 'Hérault'), ('35', 'Ille-et-Vilaine'), + ('36', 'Indre'), ('37', 'Indre-et-Loire'), ('38', 'Isère'), ('39', 'Jura'), ('40', 'Landes'), + ('41', 'Loir-et-Cher'), ('42', 'Loire'), ('43', 'Haute-Loire'), ('44', 'Loire-Atlantique'), ('45', 'Loiret'), + ('46', 'Lot'), ('47', 'Lot-et-Garonne'), ('48', 'Lozère'), ('49', 'Maine-et-Loire'), ('50', 'Manche'), + ('51', 'Marne'), ('52', 'Haute-Marne'), ('53', 'Mayenne'), ('54', 'Meurthe-et-Moselle'), ('55', 'Meuse'), + ('56', 'Morbihan'), ('57', 'Moselle'), ('58', 'Nièvre'), ('59', 'Nord'), ('60', 'Oise'), ('61', 'Orne'), + ('62', 'Pas-de-Calais'), ('63', 'Puy-de-Dôme'), ('64', 'Pyrénées-Atlantiques'), ('65', 'Hautes-Pyrénées'), + ('66', 'Pyrénées-Orientales'), ('67', 'Bas-Rhin'), ('68', 'Haut-Rhin'), ('69', 'Rhône'), ('70', 'Haute-Saône'), + ('71', 'Saône-et-Loire'), ('72', 'Sarthe'), ('73', 'Savoie'), ('74', 'Haute-Savoie'), ('75', 'Paris'), + ('76', 'Seine-Maritime'), ('77', 'Seine-et-Marne'), ('78', 'Yvelines'), ('79', 'Deux-Sèvres'), ('80', 'Somme'), + ('81', 'Tarn'), ('82', 'Tarn-et-Garonne'), ('83', 'Var'), ('84', 'Vaucluse'), ('85', 'Vendée'), + ('86', 'Vienne'), ('87', 'Haute-Vienne'), ('88', 'Vosges'), ('89', 'Yonne'), ('90', 'Territoire de Belfort'), + ('91', 'Essonne'), ('92', 'Hauts-de-Seine'), ('93', 'Seine-Saint-Denis'), ('94', 'Val-de-Marne'), + ('95', "Val-d'Oise"), ('971', 'Guadeloupe'), ('972', 'Martinique'), ('973', 'Guyane'), ('974', 'La Réunion'), + ('976', 'Mayotte'), + ) + + def street_prefix(self): + """ + :example 'rue' + """ + return self.random_element(self.street_prefixes) + + def city_prefix(self): + """ + :example 'rue' + """ + return self.random_element(self.city_prefixes) + + def region(self): + """ + :example 'Guadeloupe' + """ + return self.random_element(self.regions) + + def department(self): + """ + Randomly returns a french department ('departmentNumber' , 'departmentName'). + :example ('2B' . 'Haute-Corse') + """ + return self.random_element(self.departments) + + def department_name(self): + """ + Randomly returns a french department name. + :example 'Ardèche' + """ + return self.department()[1] + + def department_number(self): + """ + Randomly returns a french department number. + + :example '59' + """ + return self.department()[0] diff --git a/testbed/joke2k__faker/faker/providers/address/he_IL/__init__.py b/testbed/joke2k__faker/faker/providers/address/he_IL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..71dc858b1b0f5e9328dc70aaf7bb2b57b5cc3cc8 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/he_IL/__init__.py @@ -0,0 +1,621 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_formats = ('{{city_name}}', ) + street_name_formats = ('{{street_title}}', ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}, {{city}}, {{postcode}}', ) + postcode_formats = ('#######', ) + + # Data sourced from data.gov.il + # https://data.gov.il/dataset/321 + + street_titles = ( + "אביב", + "אביגיל", + "אבן מסעוד", + "אברבנאל", + "אברהם ברזילי", + "אגוז", + "אדמון", + "אהרון מאיר מזיא", + "אהרונוביץ", + "אולפן", + "אורנים", + "אזור בית הקברות", + "אזור תעשיה א'", + "אזור תעשיה הר יונה", + "אזור תעשייה", + "אזור תעשייה מזרח", + "אח\"י אילת", + "אייזיק ניוטון", + "איילת השחר )מ ק(", + "אייר", + "אילניה", + "אימבר", + "אירוס", + "אירוס", + "אל הודא סמ3", + "אלוורוד", + "אלול", + "אלומה", + "אלזאבוד", + "אל-זהרא'", + "אל זיתון סמ2", + "אלזיתונה סמ7", + "אל חגאג בן יוסף", + "אל-חראיק סמ3", + "אלחרש", + "אל-ט'הרה סמ7", + "אלישר", + "אלכנסת", + "אלכסנדר ינאי", + "אלכרום", + "אלכתאב", + "אל-לימון", + "אלמזדלפה", + "אל-מחאג'ר סמ3", + "אל-מחאג'ר סמ4", + "אלמנשיה-מושירפה", + "אל-מקפה סמ9", + "אל-סביל סמ6", + "אלסלילמה", + "אלסריס", + "אלעמשקה", + "אלעקבה", + "אל-פארוק סמ2", + "אלפג'ר", + "אלרשיד", + "אלתין", + "אלתרמן", + "אסא המלך", + "אפעל", + "ארבל", + "אשדוד", + "אשל", + "אתגר", + "אתר חפץ חיים", + "בועז", + "בורסת היהלומים", + "ביכורים", + "ביל\"ו", + "בילינסון", + "בית אבות", + "בית היוצר", + "בית יצחק-שער חפר", + "בית ראשון במולדת", + "בן יהודה", + "בן ישי", + "בן לברט", + "בן צבי יצחק", + "בן צבי יצחק", + "בן צבי שמעון", + "בקעת הירח", + "ברגמן אליעזר", + "ברוריה", + "ברזיל", + "ברקת", + "בשמת", + "בשמת", + "גבע", + "גבע", + "גבעת חיים )מאוחד(", + "גובר רבקה", + "גוטמכר", + "גולדה מאיר", + "ג'ו עמר", + "גיבתון חנוך", + "גינוסר", + "גפן", + "גפן", + "גרטרוד קראוס", + "גרינבוים", + "דבורה", + "דודו דותן", + "דולב", + "דולצ'ין אריה", + "דחי", + "דיה", + "דימיטר פשב", + "דרב אלברג'", + "דרומית-מג'ד אלכרום", + "דריפוס", + "דרך הארץ", + "דרך הגן", + "דרך חברון", + "דרך חלמית", + "דרך שועפאט סמ4", + "האדמו\"ר מויז'ניץ", + "האודם", + "האורן", + "האורנים", + "האחים בז'רנו", + "האילן", + "האילנות", + "האילתית", + "האלונים", + "האמוראים", + "האצטדיון", + "האצ\"ל", + "הברדלס", + "הברוש", + "הבריגדה", + "הגבורה", + "הגפן", + "הגפן", + "הדגניות", + "הדולב", + "הדייגים", + "הדרך האמריקאית סמ12", + "ההגנה", + "ההגנה", + "הולצברג שמחה", + "הופרט יעקב", + "הורדים", + "הורקנוס יוחנן", + "הזיתים", + "הזמיר", + "החבל", + "החותרים", + "החלוצים", + "החליל", + "החמנית", + "החסידה", + "החצב", + "החצב", + "החרוב", + "החרובים", + "החרמון", + "החשמל", + "היוזם", + "הינשוף", + "היקינטון", + "הל\"ה", + "המאה ואחד", + "המבריא", + "המברק", + "המגינים", + "המגינים", + "המורד", + "המייסדים", + "המלאכה", + "המלאכה", + "המלכים", + "הממונה", + "המנוע", + "המסגר", + "המעיין", + "המפרש", + "המצודה", + "המרגנית", + "המשור", + "הנוטר", + "הנורית", + "הנורית", + "הנקר", + "הנרד", + "הסיגלית", + "הסיפון", + "העבודה", + "העבודה", + "העצמון", + "הפעמון", + "הפרדס", + "הפרדס", + "הפרדס", + "הפרדס", + "הצאלון", + "הצבעוני", + "הקישון", + "הראשונים", + "הרב בידאני עובדיה", + "הרב וולף", + "הרב חכם שמעון", + "הרבי מליובאוויטש", + "הרב ניסים", + "הרב עוזיאל", + "הרב רפאל עבו", + "הרדוף", + "הרדוף", + "הרדוף", + "הרותם", + "הרי גולן", + "הר יהל", + "הרימון", + "הר כנען", + "הרליץ יוסף", + "הר סיני", + "הר עצמון", + "הר צרור", + "הרקפת", + "הרשקו אברהם", + "הרשת", + "השדות", + "השחר", + "השיזף", + "השיח", + "השיטה", + "השעורה", + "השר ברזילי", + "התאנה", + "התבור", + "התקוה", + "ויקטור ויוליוס", + "וערת סעד", + "ז'בוטינסקי", + "זגגי", + "זיגורד", + "זיו", + "ז'ילבר", + "זית", + "זכרון יעקב", + "חוחית", + "חוף הים", + "חושן", + "חזון איש", + "חזן יעקב", + "חיטה", + "חיים וייצמן", + "חלמיש", + "חצב", + "חרת א בוס", + "חתוכה יורם", + "טאבליא", + "טאחונת אלראהיב", + "טביב", + "טופז", + "י\"א באדר", + "יאפא", + "יד העפלה ממרוקו", + "ידידה", + "יהודה הלוי", + "יהודה המכבי", + "יהודה המכבי", + "יואב", + "יונה", + "יזרעאל", + "יחזקאל הנביא", + "יכין", + "ירושלים", + "ירקון", + "ישועת דוד", + "יששכר", + "כאבול", + "כהן אלי", + "כהנא", + "כוכב הצפון", + "כזיב", + "כיסופים", + "ככר ירדן", + "ככר נחשון", + "כנרת", + "כפר ילדים נרדים", + "כרם חמד", + "לב הקריה", + "לביא אריק", + "לבקוביץ", + "לוד הצעירה", + "לוטם", + "לוין מיכאל וחנה", + "לוין שמריהו", + "לוריא", + "לח\"י", + "לילינבלום", + "לכיש", + "לסקוב חיים", + "מבוא הדס", + "מבוא הזיתים", + "מבוא חיים מקובנה", + "מבוא חמה", + "מבצע הראל", + "מבצע חירם", + "מבצע עובדה", + "מגלן", + "מוסיוף שלמה", + "מופק דיאב", + "מוצא", + "מורדי הגטאות", + "מורן", + "מזל שור", + "מזרחי יוסף", + "מיכה", + "מירון", + "מישאל", + "מלון רויאל פארק", + "מנזר המארונים", + "מעבר לים", + "מעוז חיים", + "מעונות ים", + "מעלה כגן הלנה", + "מענית", + "מצדה", + "מצפה גילה", + "מרגיל מחוור", + "מרווה", + "מרחביה )מושב(", + "מרכז", + "משה דיין", + "משואות יצחק", + "משעול אבוקדו", + "משעול האלה", + "משעול המחתרות", + "משעול הסיפן", + "משעול הצופית", + "משעול התפוח", + "משעול מוריה", + "משעול נקר", + "משעול פארן", + "נאות אביבים", + "נאות אשכול", + "נאות הדקל", + "נדב יצחק", + "נהריה", + "נוה עוז", + "נוף כנרת", + "נורית", + "נחל נחשון", + "נחל סרפד", + "נחל ערוגות מ\"ר", + "נחל פארן", + "נחלת צדוק", + "ניר עם", + "נעמ\"ת", + "נצרת עילית", + "נשר", + "נתיב הפורצים", + "נתן", + "סביונים מכבים רעות", + "סומך עובדיה", + "סיתוונית", + "סלא איירין", + "סלעית", + "סמ 20 20", + "סמבורסקי דניאל", + "סמ בני ברית", + "סמ הבוסתן", + "סמ הרכבת", + "סמ השחף", + "סמטת השחר", + "סמ מאלה", + "סמ מסילה א", + "סמ עין גנים", + "סמ עינב", + "סמ שפיפון", + "סנט הלנה", + "עבד אל-גני", + "עגור", + "ע הלל", + "עובדי הנמל", + "עוגן", + "עולש מצוי", + "עומר", + "עידו הנביא", + "עין שביב", + "עירית", + "עמוס", + "עמוס הנביא", + "עמנואל )רינגלבלום(", + "ענזה", + "עפולה", + "עקבת א תות", + "פדויים", + "פטדה", + "פנינה", + "פקוד מרכז", + "פרומקין גד", + "פרופ' בירק יהודית", + "פרופס", + "פרי חדש", + "צדוק הכהן", + "צובה", + "צופית", + "צוקית", + "צור", + "צמחי היהודים", + "צפרירים", + "צפת", + "צפת", + "קבועה )שבט(", + "קדמת צבי", + "קישון אפרים", + "קנין הארץ", + "קרית עקרון", + "קרל נטר", + "קרן היסוד", + "רביבים", + "רבנו תם", + "רבקה אמנו", + "רח 101", + "רח 1043", + "רח 1060", + "רח 12", + "רח 1238", + "רח 124", + "רח 135", + "רח 14", + "רח 16", + "רח 16", + "רח 2001", + "רח 2306", + "רח 5041", + "רח 6020", + "רח 6073", + "רח 6087", + "רח 68", + "רח 7035", + "רח 7038", + "רח 7069", + "רח 71", + "רחבת פנינה", + "רח ה", + "רח מו כ שלם", + "רח רז", + "ריחאניה", + "רלב\"ג", + "רמב\"ם", + "רמב\"ן", + "רמת האירוסים", + "רמת כרמים", + "רקפת", + "רש\"י", + "ש אסבסטונים", + "ש אסבסט צפון", + "שאר ישוב", + "ש בבלי", + "שבזי", + "שבזי", + "שבטי ישראל", + "שבט ראובן", + "שביל הרקפות", + "שביל קליפות התפוזים", + "שד גאולים", + "שד גת", + "שד העצמאות", + "שד ח\"ן", + "שד יוספטל גיורא", + "ש הפועלים", + "שוהם", + "שומרון", + "שושנה דמארי", + "שושנת הכרמל", + "שז\"ר זלמן", + "שיזף", + "שכ 14", + "שכ החלוצים", + "שכ היובל", + "שכ הפועל המזרחי ג'", + "שכ הרכבת", + "שכ זאב", + "שכ חפצי בה", + "שכ מחניים", + "שכ נווה הדקל", + "שכ עראק אלשבאב", + "שכ קחאוש", + "שכ רסקו", + "שלדג", + "שמחוני", + "שמחוני אסף", + "שמעון המכבי", + "שני", + "ש סלע חדש", + "ש פועלים", + "ש\"ץ גרשון", + "ש ציונים כלליים", + "שקד", + "ש קואפרטיבים", + "שריג", + "ש רמת אביב", + "תאנה", + "תל חי", + "תפארת ישראל", + "תרס\"ח", + "תרצ\"ו") + + city_names = ( + "אבו רובייעה )שבט(", + "אביבים", + "אביחיל", + "אודם", + "אור הנר", + "אורטל", + "אטרש )שבט(", + "אליקים", + "אל סייד", + "באר מילכה", + "בית ברל", + "בית הלוי", + "בית חנן", + "בית חנניה", + "בית חשמונאי", + "בני ציון", + "ברקאי", + "ברקת", + "גבעת השלושה", + "גבעת ח\"ן", + "גבעת כ\"ח", + "גדות", + "גונן", + "גינתון", + "גיתית", + "גן שורק", + "גנות הדר", + "גני מודיעין", + "גרופית", + "דוב\"ב", + "דולב", + "האון", + "הסוללים", + "העוגן", + "הר אדר", + "ורד יריחו", + "זוהר", + "חיננית", + "חצור-אשדוד", + "חצור הגלילית", + "חשמונאים", + "טל-אל", + "יד רמב\"ם", + "כסלון", + "כפר אחים", + "כפר הנוער הדתי", + "כפר יונה", + "כפר מסריק", + "כפר סירקין", + "לוזית", + "לקיה", + "מגאר", + "מגן", + "מזכרת בתיה", + "מירון", + "מכמורת", + "מלאה", + "מסד", + "מעונה", + "מרחביה )מושב(", + "משמר העמק", + "נווה חריף", + "נוקדים", + "נורדיה", + "נחלה", + "נטע", + "נירן", + "נתיב השיירה", + "סגולה", + "סער", + "עדי", + "עזר", + "עין אל-אסד", + "עין השופט", + "עין צורים", + "עלי זהב", + "עמוקה", + "עמיר", + "עמקה", + "עספיא", + "עצמון שגב", + "פוריה - נווה עובד", + "פוריידיס", + "פקיעין חדשה", + "צורית", + "צפרירים", + "רגבה", + "רחוב", + "ריינה", + "רימונים", + "רמות מנשה", + "שדה אליהו", + "שדות מיכה", + "שדי תרומות", + "שומרה", + "שיטים", + "שעב", + "שפר", + "שתולים", + "תלמי אליהו") + + def city_name(self): + return self.random_element(self.city_names) + + def street_title(self): + return self.random_element(self.street_titles) diff --git a/testbed/joke2k__faker/faker/providers/address/hi_IN/__init__.py b/testbed/joke2k__faker/faker/providers/address/hi_IN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d596e157f007340a6f462f83b819e182453fe32 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/hi_IN/__init__.py @@ -0,0 +1,233 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + street_name_formats = ( + '{{first_name}} {{last_name}}', + '{{last_name}}', + ) + + street_address_formats = ('{{building_number}} {{street_name}}', ) + + address_formats = ('{{street_address}}\n{{city}} {{postcode}}', + '{{street_address}}\n{{city}}-{{postcode}}') + + building_number_formats = ( + '####', '###', '##', '#', '#/#', '##/##', '##/###', '##/####') + + postcode_formats = ('######', ) + + cities = ( + 'आदिलाबाद', + 'अगरतला', + 'अहमदाबाद', + 'अहमदनगर', + 'अजमेर', + 'अम्बाजी', + 'अमरपुर', + 'इलाहाबाद', + 'अकोला', + 'अखनूर', + 'अन्तर्गत', + 'अलांग', + 'अलीगढ', + 'दादरा और नगर हवेली', + 'अमरावती', + 'अमरोहा', + 'अनन्तपुर', + 'करना', + 'जिससेबेलारी', + 'अनंतनाग', + 'भागलपुर', + 'भद्रक', + 'बचेली', + 'बहादुरगंज', + 'बहादुरगढ', + 'चिरमिरी', + 'चिराला', + 'चित्रदुर्ग', + 'चित्तूर', + 'चित्रकूट', + 'देवगढ़', + 'दालखोला', + 'देवास', + 'चंडीगढ', + 'चिपलुन', + 'चक्रधरपुर', + 'चंबा', + 'फतहपुर', + 'फतेहपुर', + 'फतेहगढ', + 'सभापतिने', + 'देवगढ़', + 'धर्मापुरी', + 'पाकाला', + 'धारवाड', + 'असम', + 'देहरा', + 'रानीताल', + 'खडगपुर', + 'मोकामा', + 'मोकोकचुंग', + 'जिलोंपर', + 'विस्तारण', + 'मोतिहारी', + 'लखनऊ', + 'मुंबई', + 'हैदराबाद', + ) + + states = ( + 'अरूणाचल प्रदेश', + 'बिहार', + 'असम', + 'आंध्र प्रदेश', + 'छत्तीसगढ', + 'हरियाणा', + 'गुजरात', + 'हिमाचल प्रदेश', + 'गोवा', + 'मध्य प्रदेश', + 'महाराष्ट्र', + 'जम्मू और कश्मीर', + 'केरल', + 'कर्नाटक', + 'मणिपुर', + 'मिजोरम', + 'मेघालय', + 'सिक्किम', + 'राजस्थान', + 'पंजाब', + 'उडीसा', + 'उत्तरांचल', + 'उत्तर प्रदेश', + 'तमिलनाडु', + 'त्रिपुरा', + 'पश्चिमी बंगाल', + 'अंडमान और निकोबार', + 'दमन और दीव', + 'दादरा और नगर हवेली', + 'दिल्ली', + 'पांडिचेरी', + 'लक्षद्वीप', + ) + + countries = ( + 'आर्मीनिया', + 'यू.के.', + 'फ्रांस', + 'फलस्तीन', + 'मिस्र', + 'ब्राज़ील', + 'ईरान', + 'यूनान', + 'स्पेन', + 'जॉर्जिया', + 'लेबनान', + 'सायप्रस', + 'सीरिया', + 'कनाडा', + 'रूस', + 'संयुक्त राज्य अमरीका', + 'नेदर्लान्ड', + 'ऑस्ट्रेलिया', + 'एंटीगुआ', + 'बार्बुडा', + 'ऑस्ट्रिया', + 'अज़रबाइजान', + 'बारबाडोस', + 'बेलारूस', + 'बेल्जियम', + 'बेलीज़', + 'बेनिन', + 'बहामास', + 'बहरीन', + 'बांग्लादेश', + 'भूटान', + 'बोलिविया', + 'बोस्निया', + 'हर्जेगोविना', + 'बोत्सवाना', + 'ब्रुनेई', + 'बुल्गारिया', + 'बुर्किना फ़ासो', + 'बर्मा', + 'बुरूंडी', + 'डोमिनिकन रिपब्लिक', + 'गिनिया', + 'टीमोर', + 'फ़िनलैंड', + 'गेबोन', + 'गाम्बिया', + 'जर्मनी', + 'ग्रेनेडा', + 'घाना', + 'ग्रेट ब्रिटेन', + 'हंगरी', + 'भारत', + 'हिन्दुस्तान', + 'इराक', + 'आयरलैंड', + 'इंडोनेशिया', + 'इटली', + 'जमैका', + 'जॉर्डन', + 'जापान', + 'क़जाख़स्तान', + 'केन्या', + 'किरिबाती', + 'दक्षिण कोरिया', + 'लातविया', + 'लाओस', + 'उत्तर कोरिया', + 'कोसोवो', + 'कुवैत', + 'लेबनान', + 'लिचटीनस्टीन', + 'लिथुआनिया', + 'लक्समबर्ग', + 'लीबिया', + 'लाइबेरिया', + 'लेसोथो', + 'नेपाल', + 'न्यूज़ीलैण्ड', + 'निकारागुआ', + 'नाइजर', + 'नाउरू', + 'सेंट लुसिया', + 'रोमानिया', + 'अरब अमीरात', + 'यूएई', + 'युगांडा', + 'यूक्रेन', + 'उरूग्वे', + 'उज़बेकिस्तान', + 'यूनाइटेड किंगडम', + 'वानुआतू', + 'वेटिकन सिटी', + 'वेनेजुएला', + 'पश्चिमी सहारा', + 'वियतनाम', + 'यमन', + 'ज़ायर', + 'ज़ाम्बिया', + 'ज़िम्बाब्वे', + 'पाकिस्तान', + 'सउदी अरब', + 'ओमान', + 'क़तर', + 'ट्यूनीशिया', + 'मोरक्को', + 'तुर्की', + 'श्रीलंका', + 'अफ़ग़ानिस्तान', + ) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/hr_HR/__init__.py b/testbed/joke2k__faker/faker/providers/address/hr_HR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e03373571d8cb3cb41ff93b78b09ebaeecb2a0d6 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/hr_HR/__init__.py @@ -0,0 +1,174 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + street_name_formats = ('{{street_name}}', ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) + + building_number_formats = ('###', '##', '#', '#a', '#b', '#c', + '#a/#', '#b/#', '#c/#') + + postcode_formats = ('#####', ) + + street_suffixes_long = ( + '', 'ulica', 'cesta', 'put', 'avenija', + ) + street_suffixes_short = ( + '', 'ul.', 'c.', 'a.', + ) + + cities = ( + "Bakar", "Beli Manastir", "Belišće", "Benkovac", "Biograd na Moru", + "Bjelovar", "Buje", "Buzet", "Cres", "Crikvenica", "Čabar", "Čakovec", + "Čazma", "Daruvar", "Delnice", "Donja Stubica", "Donji Miholjac", + "Drniš", "Dubrovnik", "Duga Resa", "Dugo Selo", "Đakovo", "Đurđevac", + "Garešnica", "Glina", "Gospić", "Grubišno Polje", + "Hrvatska Kostajnica", "Hvar", "Ilok", "Imotski", "Ivanec", + "Ivanić-Grad", "Jastrebarsko", "Karlovac", "Kastav", "Kaštela", + "Klanjec", "Knin", "Komiža", "Koprivnica", "Korčula", "Kraljevica", + "Krapina", "Križevci", "Krk", "Kutina", "Kutjevo", "Labin", + "Lepoglava", "Lipik", "Ludbreg", "Makarska", "Mali Lošinj", + "Metković", "Mursko Središće", "Našice", "Nin", "Nova Gradiška", + "Novalja", "Novi Marof", "Novi Vinodolski", "Novigrad", "Novska", + "Obrovac", "Ogulin", "Omiš", "Opatija", "Opuzen", "Orahovica", + "Oroslavje", "Osijek", "Otočac", "Otok", "Ozalj", "Pag", "Pakrac", + "Pazin", "Petrinja", "Pleternica", "Ploče", "Popovača", "Poreč", + "Požega", "Pregrada", "Prelog", "Pula", "Rab", "Rijeka", "Rovinj", + "Samobor", "Senj", "Sinj", "Sisak", "Skradin", "Slatina", + "Slavonski Brod", "Slunj", "Solin", "Split", "Stari Grad", + "Supetar", "Sveta Nedelja", "Sveti Ivan Zelina", "Šibenik", + "Trilj", "Trogir", "Umag", "Valpovo", "Varaždin", + "Varaždinske Toplice", "Velika Gorica", "Vinkovci", "Virovitica", + "Vis", "Vodice", "Vodnjan", "Vrbovec", "Vrbovsko", "Vrgorac", + "Vrlika", "Vukovar", "Zabok", "Zadar", "Zagreb", "Zaprešić", "Zlatar", + ) + + streets = ( + "Arnoldova", "Bakačeva", "Bijenička", "Bosanska", "Bučarova", + "Cmrok", "Čačkovićeva", "Davor", "Demetrova", + "Dolac", "Donje Prekrižje", "Draškovićeva", "Dubravkin", + "Dverce", "Dvoranski prečac", "Glogovac", "Golubovac", "Goljačke", + "Goljak", "Gornje Prekrižje", "Gračanska", "Gradec", "Grič", + "Gupčeva zvijezda", "Harmica", "Hercegovačka", "Horvatovac", + "Ilica", "Istarska", "Jabukovac", "Jadranska", "Jagodnjak", + "Javorovac", "Jezuitski trg", "Jurišićeva", "Jurjeve", + "Jurjevska", "Jurkovićeva", "Kamaufova", "Kamenita", "Kamenjak", + "Kaptol", "Kapucinske", "Klanac Grgura Tepečića", "Klenovac", + "Klesarski put", "Kozarčev vijenac", "Kožarska", "Kraljevec", + "Kraljevec II.", "Kraljevečki odvojak", "Kraljevečki ogranak", + "Krležin gvozd", "Krvavi most", "Ksaver", "Ksaverska", "Kurelčeva", + "Lisinskoga", "Lobmayerove", "Ljubinkovac", "Magdićeve", "Mala", + "Male", "Mašekova", "Medvedgradska", "Medveščak", "Mesnička", + "Mihaljevac", "Mirogojska", "Mletačka", "Mlinarska", "Mlinovi", + "Mlinske", "Naumovac", "Nemetova", "Nova Ves", + "Novi Goljak", "Opatička", "Opatovina", "Orlovac", + "Palmotićeva", "Pantovčak", "Paunovac", + "Perivoj biskupa Stjepana II.", "Perivoj srpanjskih žrtava", + "Petrova", "Pod zidom", "Podgaj", "Radnički dol", "Remetska", + "Ribnjak", "Rikardove", "Rockefellerova", "Rokov perivoj", "Rokova", + "Ružičnjak", "Skalinska", "Slavujevac", "Splavnica", + "Srebrnjak", "Streljačka", "Strossmayerovo šetalište", "Svibovac", + "Svibovac", "Šalata", "Šestinski vijenac", "Šestinski vrh", + "Šilobodov put", "Šumski prečac", "Tkalčićeva", "Tošovac", + "Tuškanac", "Vijenac", "Vinogradska", "Visoka", "Višnjica", + "Višnjičke", "Vitezovićeva", "Vlaška", "Voćarska", "Voćarsko naselje", + "Vončinina", "Vrazovo šetalište", "Wickerhauserova", "Zamenhofova", + "Zamenhofove", "Zavojna", "Zelengaj", "Zeleni dol", + "Zelenjak", "Zmajevac", "Zvonarnička", + ) + + states = ( + "Zagrebačka", + "Krapinsko-zagorska", + "Sisačko-moslavačka", + "Karlovačka", + "Varaždinska", + "Koprivničko-križevačka", + "Bjelovarsko-bilogorska", + "Primorsko-goranska", + "Ličko-senjska", + "Virovitičko-podravska", + "Požeško-slavonska", + "Brodsko-posavska", + "Zadarska", + "Osječko-baranjska", + "Šibensko-kninska", + "Vukovarsko-srijemska", + "Splitsko-dalmatinska", + "Istarska", + "Dubrovačko-neretvanska", + "Međimurska", + "Grad Zagreb", + ) + + countries = ( + "Afganistan", "Alandski otoci", "Albanija", "Alžir", "Američka Samoa", + "Američki Djevičanski Otoci", "Andora", "Angola", "Anguila", + "Antarktik", "Antigua i Barbuda", "Argentina", "Armenija", "Aruba", + "Australija", "Austrija", "Azerbajdžan", "Bahami", + "Bahrein", "Bangladeš", "Barbados", "Belgija", "Belize", + "Benin", "Bermuda", "Bjelorusija", "Bocvana", "Bolivija", + "Bosna i Hercegovina", "Božićni Otok", "Brazil", + "Britanski Djevičanski Otoci", "Britanski Teritorij Indijskog Oceana", + "Brunei Darussalam", "Bugarska", "Burkina Faso", "Burundi", "Butan", + "Cipar", "Crna Gora", "Curacao", "Čad", "Čile", "Danska", "Dominika", + "Dominikanska Republika", "Džibuti", "Egipat", "Ekvador", + "Ekvatorska Gvineja", "El Salvador", "Eritreja", "Estonija", + "Etiopija", "Falklandi", "Farski Otoci", "Fidži", "Filipini", "Finska", + "Francuska", "Francuska Gvajana", "Francuska Polinezija", + "Francuski Južni Teritoriji", "Gabon", "Gambija", "Gana", "Gibraltar", + "Vatikan", "Grčka", "Grenada", "Grenland", "Gruzija", "Guadeloupe", + "Guam", "Guernsey", "Gvajana", "Gvatemala", "Gvineja", "Gvineja Bisau", + "Haiti", "Honduras", "Hong Kong", "Hrvatska", "Indija", "Indonezija", + "Irak", "Iran, Islamska Republika", "Irska", "Island", "Isle Of Man", + "Istočni Timor", "Italija", "Izrael", "Jamajka", "Japan", "Jemen", + "Jersey", "Jordan", "Južna Afrika", + "Južna Gruzija i Južni Sendvič Otoci", "Kajmanski Otoci", "Kambodža", + "Kamerun", "Kanada", "Katar", "Kazakstan", "Kenija", "Kina", + "Kirgistan", "Kiribati", "Kokosovi Otoci", "Kolumbija", "Komori", + "Kongo", "Kongo, Demokratska Republika", "Koreja, Južna", + "Koreja, Sjeverna", "Kosovo", "Kostarika", "Kuba", "Kukovi Otoci", + "Kuvajt", "Laoska Narodna Demokratska Republika", "Latvija", "Lesoto", + "Libanon", "Liberija", "Libijska Arapska Džamahirija", "Lihtenštajn", + "Litva", "Luksemburg", "Madagaskar", "Mađarska", "Majote", "Makao", + "Makedonija", "Malavi", "Maldivi Maldives", "Malezija", "Mali", + "Malta", "Maroko", "Maršalovi Otoci", "Martinik", "Mauricijus", + "Mauritanija", "Meksiko", "Mijanmar", "Mikronezija", + "Moldavija, Republika", "Monako", "Mongolija", "Montserat", "Mozambik", + "Namibija", "Nauru", "Nepal", "Niger", "Nigerija", "Nikaragva", "Niue", + "Nizozemska", "Norveška", "Nova Kaledonija", "Novi Zeland", "Njemačka", + "Obala Slonovače", "Oman", "Otok Bouvet", + "Otok Heard i Otoci McDonald", "Otok Norfolk", "Pakistan", "Palau", + "Palestinsko Područje", "Panama", "Papua Nova Gvineja", "Paragvaj", + "Peru", "Pitcairn", "Poljska Poland", "Portoriko", "Portugal", + "Republika Češka", "Reunion", "Ruanda", "Rumunjska", "Rusija", + "Salamunovi Otoci", "Samoa", "San Marino", "São Tomé ai Príncipe", + "Saudijska Arabija", "Sejšeli", "Senegal", "Sijera Leone", "Singapur", + "Sint Maarten", "Sirija", "Sjedinjene Američke Države", + "Sjeverni Marijanski Otoci", "Slovačka", "Slovenija", "Somalija", + "Južni Sudan", "Srbija", "Srednjoafrička Republika", "Sudan", + "Surinam", "Svalbard i Jan Mayen", "Svaziland", "Sveta Helena", + "Sveti Bartolomej", "Sveti Martin", "Sveti Petar i Miguel", + "Sv. Kristofor i Nevis", "Sv. Lucija", "Sv. Vincent i Grenadini", + "Španjolska", "Šri Lanka", "Švedska", "Švicarska", "Tadžikistan", + "Tajland", "Tajvan", "Tanzanija", "Togo", "Tokelau", "Tonga", + "Trinidad i Tobago", "Tunis", "Turkmenistan", "Turkski i Kaikos Otoci", + "Turska", "Tuvalu", "Uganda", + "Ujedinjene Države Manjih Pacifičkih Otoka", + "Ujedinjeni Arapski Emirati", "Ukrajina", "Urugvaj", "Uzbekistan", + "Vanuatu", "Velika Britanija", "Venezuela", "Vijetnam", + "Wallis i Futuna", "Zambija", "Zapadna Sahara", "Zeleni Rt", + ) + + def city_name(self): + return self.random_element(self.cities) + + def street_name(self): + return self.random_element(self.streets) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/hu_HU/__init__.py b/testbed/joke2k__faker/faker/providers/address/hu_HU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5674ae689fb7380fafe365a10edb35600a572171 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/hu_HU/__init__.py @@ -0,0 +1,244 @@ +from collections import OrderedDict + +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + street_suffixes = OrderedDict( + (('utca', 0.75), ('út', 0.1), ('tér', 0.1), ('köz', 0.001), ('körút', 0.001), ('sétány', 0.001))) + + street_name_formats = ( + '{{frequent_street_name}} {{street_suffix}}', + '{{real_city_name}}i {{street_suffix}}', + '{{city_part}}{{city_suffix}}i {{street_suffix}}', + '{{city_prefix}}{{city_part}}i {{street_suffix}}') + + # Currently deprecated. + # secondary_address_formats = ("#.em #.", "##. em. #.") + + city_formats = ('{{city_prefix}}{{city_part}}{{city_suffix}}', + '{{city_part}}{{city_suffix}}', '{{real_city_name}}') + + street_address_formats = ('{{street_name}} {{building_number}}',) + + address_formats = ("{{street_address}}\n{{postcode}} {{city}}",) + + frequent_street_names = ( + 'Ady Endre', + 'Dózsa György', + 'Petőfi', + 'Petőfi Sándor', + 'Arany János', + 'Béke', + 'Szabadság', + 'Kossuth', + 'József Attila') + + # The 'real city name' generator includes a number of real cities of + # Hungary that no generator could feasibly dispense. Please note that the + # post code generator is, at this point, not capable of generating a + # fitting post code. In Hungary, post codes are determined by the county of + # the place (see the county generator), and for this reason, often there + # will be a discrepancy. A patch is in the works - until then, use + # Wikipedia to resolve postcode issues. + # + # This generator was created by collecting the 30 largest Hungarian places + # by population, based on the Hungarian Gazetteer generated with effect as + # of 01 January 2016 (http://www.ksh.hu/docs/hun/hnk/hnk_2016.pdf). + + real_city_names = ( + 'Budapest', + 'Debrecen', + 'Szeged', + 'Miskolc', + 'Pécs', + 'Győr', + 'Nyíregyháza', + 'Kecskemét', + 'Székesfehérvár', + 'Szombathely', + 'Szolnok', + 'Tatabánya', + 'Érd', + 'Kaposvár', + 'Sopron', + 'Veszprém', + 'Békéscsaba', + 'Zalaegerszeg', + 'Eger', + 'Nagykanizsa', + 'Dunaújváros', + 'Hódmezővásárhely', + 'Dunakeszi', + 'Szigetszentmiklós', + 'Cegléd', + 'Baja', + 'Salgótarján', + 'Ózd', + 'Vác', + 'Mosonmagyaróvár') + + city_prefs = ( + 'kis', + 'nagy', + 'szent', + 'duna', + 'tisza', + 'alsó', + 'felső', + 'belső', + 'bakony', + 'vác', + 'mező', + 'nyék', + 'nyír', + 'balaton', + 'borsod', + 'buda', + 'hajdú', + 'kun', + 'moson', + 'pilis', + 'új', + 'egyházas', + 'dráva', + 'magyar', + 'mátra', + 'somogy', + 'lajos', + 'bács', + 'békés', + 'puszta', + 'orosz', + 'rác', + 'szerb', + 'német', + 'török') + + city_parts = ( + 'híd', + 'györgy', + 'mindszent', + 'kereszt', + 'márton', + 'hát', + 'hetven', + 'mellék', + 'tamási', + 'tapolca', + 'fürdő', + 'liget', + 'szék', + 'tót', + '') + + city_suffixes = ( + 'háza', + 'németi', + 'devecser', + 'fa', + 'nádasd', + 'apáti', + 'falu', + 'falva', + 'vég', + 'vár', + 'vára', + 'várad', + 'hida', + 'kövesd', + 'bánya', + 'halas', + 'berény', + 'kőrös', + 'haraszti', + 'város') + + counties = ( + 'Bács-Kiskun', + 'Baranya', + 'Békés', + 'Borsod-Abaúj-Zemplén', + 'Csongrád', + 'Fejér', + 'Győr-Moson-Sopron', + 'Hajdú-Bihar', + 'Heves', + 'Jász-Nagykun-Szolnok', + 'Komárom-Esztergom', + 'Nógrád', + 'Pest', + 'Somogy', + 'Szabolcs-Szatmár-Bereg', + 'Tolna', + 'Vas', + 'Veszprém', + 'Zala') + + countries = ( + "Afganisztán", "Aland-szigetek", "Albánia", "Algéria", "Amerikai Szamoa", "Amerikai Virgin-szigetek", "Andorra", + "Angola", "Anguilla", "Antarktisz", "Antigua és Barbuda", "Apostoli Szentszék", "Argentína", "Aruba", + "Ausztrália", "Ausztria", "Amerikai Egyesült Államok Külső Szigetei", "Azerbajdzsán", "Bahama-szigetek", + "Bahrein", "Banglades", "Barbados", "Fehéroroszország", "Belgium", "Belize", "Benin", "Bermuda", "Bhután", + "Bissa -Guinea", "Bolívia", "Bosznia-Hercegovina", "Botswana", "Bouvet-sziget", "Brazília", + "Brit Indiai-óceáni Terület", "Brit Virgin - szigetek", "Brunei", "Bulgária", "Burkina Faso", "Burundi", + "Chile", "Ciprus", "Comore-szigetek", "Cook-szigetek", "Costa Rica", "Csád", "Csehország", "Dánia", + "Dél-Afrika", "Dél-Korea", "Dominika", "Dominikai Köztársaság", "Dzsibuti", "Ecuador", "Egyenlítői-Guinea", + "Egyesült Államok", "Egyesült Arab Emírségek", "Egyesült Királyság", "Egyiptom", "Elefántcsontpart", "Eritrea", + "Északi Mariana-szigetek", "Észak-Korea", "Észtország", "Etiópia", "Falkland-szigetek", "Feröer szigetek", + "Fidzsi-szigetek", "Finnország", "Francia Déli Területek", "Francia Guyana", "Francia Polinézia", + "Franciaország", "Fülöp-szigetek", "Gabon", "Gambia", "Ghána", "Gibraltár", "Görögország", "Grenada", + "Grönland", "Grúzia", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guyana", "Haiti", "Holland Antillák", + "Hollandia", "Honduras", "Hongkong", "Horvátország", "India", "Indonézia", "Irak", "Irán", "Írország", "Izland", + "Izrael", "Jamaica", "Japán", "Jemen", "Jordánia", "Kajmán-szigetek", "Kambodzsa", "Kamerun", "Kanada", + "Karácsony-sziget", "Katar", "Kazahsztán", "Kelet-Timor", "Kenya", "Kína", "Kirgizisztán", "Kiribati", + "Keeling-szigetek", "Kolumbia", "Kongó", "Kongói Demokratikus Köztársaság", "Közép-afrikai Köztársaság", "Kuba", + "Kuvait", "Laosz", "Lengyelország", "Lesotho", "Lettország", "Libanon", "Libéria", "Líbia", "Liechtenstein", + "Litvánia", "Luxemburg", "Macedónia", "Madagaszkár", "Magyarország", "Makaó", "Malajzia", "Malawi", + "Maldív-szigetek", "Mali", "Málta", "Marokkó", "Marshall-szigetek", "Martinique", "Mauritánia", "Mauritius", + "Mayotte", "Mexikó", "Mianmar", "Mikronézia", "Moldova", "Monaco", "Mongólia", "Montenegró", "Montserrat", + "Mozambik", "Namíbia", "Nauru", "Németország", "Nepál", "Nicaragua", "Niger", "Nigéria", "Niue", + "Norfolk-sziget", "Norvégia", "Nyugat-Szahara", "Olaszország", "Omán", "Oroszország", "Örményország", + "Pakisztán", "Palau", "Panama", "Pápua", "Új-Guinea", "Paraguay", "Peru", "Pitcairn-szigetek", "Portugália", + "Puerto Rico", "Réunion", "Románia", "Ruanda", "Saint Kitts és Nevis", "Saint Lucia", + "Saint-Pierre és Miquelon", "Saint Vincent és Grenadine-szigetek", "Salamon-szigetek", "Salvador", "San Marino", + "São Tomé és Príncipe", "Seychelle-szigetek", "Sierra Leone", "Spanyolország", "Srí Lanka", "Suriname", "Svájc", + "Svalbard szigetek", "Svédország", "Szamoa", "Szaúdi-Arábia", "Szenegál", "Szent Ilona", "Szerbia", "Szingapúr", + "Szíria", "Szlovákia", "Szlovénia", "Szomália", "Szudán", "Szváziföld", "Tádzsikisztán", "Tajvan", "Tanzánia", + "Thaiföld", "Togo", "Tokelau-szigetek", "Tonga", "Törökország", "Trinidad és Tobago", "Tunézia", + "Turks- és Caicos-szigetek", "Tuvalu", "Türkmenisztán", "Uganda", "Új-Kaledónia", "Új-Zéland", "Ukrajna", + "Uruguay", "Üzbegisztán", "Vanuatu", "Venezuela", "Vietnam", "Wallis és Futuna", "Zambia", "Zimbabwe", + "Zöld-foki szigetek") + + def county(self): + return self.random_element(self.counties) + + def street_address_with_county(self): + return "{street_address}\n{county} megye\n{postcode} {city}".format( + street_address=self.street_address(), + county=self.county(), + postcode=self.postcode(), + city=self.city().capitalize()) + + def city_prefix(self): + return self.random_element(self.city_prefs) + + def city_part(self): + return self.random_element(self.city_parts) + + def real_city_name(self): + return self.random_element(self.real_city_names) + + def frequent_street_name(self): + return self.random_element(self.frequent_street_names) + + def postcode(self): + return "H-{}{}{}{}".format( + super().random_digit_not_null(), super().random_digit(), super().random_digit(), super().random_digit()) + + def street_name(self): + return super().street_name().capitalize() + + def building_number(self): + numeric_part = super().random_int(1, 250) + return str(numeric_part) + "." diff --git a/testbed/joke2k__faker/faker/providers/address/hy_AM/__init__.py b/testbed/joke2k__faker/faker/providers/address/hy_AM/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..988a9b4fe7f6fc075d0d41c633379dff6d57b739 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/hy_AM/__init__.py @@ -0,0 +1,679 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_prefixes = ('ք.',) + city_suffixes = ('',) + street_prefixes = ('փողոց', 'պողոտա') + street_suffixes = ('',) + village_prefixes = ('գ.',) + + address_formats = ( + '{{city_prefix}} {{city}}, {{street_name}} {{building_number}}', + '{{city_prefix}} {{city}}, {{street_name}} {{building_number}}, {{secondary_address}}', + '{{city_prefix}} {{city}}, {{postcode}}, {{street_name}} {{building_number}}', + '{{city_prefix}} {{city}}, {{postcode}}, {{street_name}} {{building_number}}, {{secondary_address}}', + '{{village_prefix}} {{village}}, {{state}}ի մարզ, {{postcode}}, {{street_name}} {{building_number}}', + ) + building_number_formats = ('#', '##', '###') + postcode_formats = ('0###', '1###', '2###', '3###', '4###') + secondary_address_formats = ('բն. #', 'բն. ##', 'բն. ##') + street_address_formats = ('{{street_name}} {{building_number}}',) + street_name_formats = ('{{street}}',) + + # Source: List of cities and towns in Armenia (Wikipedia) + # https://en.wikipedia.org/wiki/List_of_cities_and_towns_in_Armenia + cities = ( + 'Աբովյան', + 'Ագարակ', + 'Ալավերդի', + 'Ախթալա', + 'Այրում', + 'Աշտարակ', + 'Ապարան', + 'Արարատ', + 'Արթիկ', + 'Արմավիր', + 'Արտաշատ', + 'Բերդ', + 'Բյուրեղավան', + 'Գավառ', + 'Գյումրի', + 'Գորիս', + 'Դաստակերտ', + 'Դիլիջան', + 'Եղեգնաձոր', + 'Եղվարդ', + 'Երևան', + 'Վաղարշապատ', + 'Թալին', + 'Թումանյան', + 'Իջևան', + 'Ծաղկաձոր', + 'Կապան', + 'Հրազդան', + 'Ճամբարակ', + 'Մասիս', + 'Մարալիկ', + 'Մարտունի', + 'Մեծամոր', + 'Մեղրի', + 'Նոր Հաճն', + 'Նոյեմբերյան', + 'Շամլուղ', + 'Չարենցավան', + 'Ջերմուկ', + 'Սիսիան', + 'Սպիտակ', + 'Ստեփանավան', + 'Սևան', + 'Վայք', + 'Վանաձոր', + 'Վարդենիս', + 'Վեդի', + 'Տաշիր', + 'Քաջարան', + ) + + # Source: Wikipedia's list of sovereign states + # https://en.wikipedia.org/wiki/List_of_sovereign_states + countries = ( + 'Աֆղանստան', + 'Ալբանիա', + 'Ալժիր', + 'Ամերիկյան Սամոա', + 'Անդորրա', + 'Անգոլա', + 'Անգիլիա', + 'Անտարկտիկա', + 'Անտիգուա և Բարբուդա', + 'Արգենտինա', + 'Հայաստան', + 'Արուբա', + 'Ավստրալիա', + 'Ավստրիա', + 'Ադրբեջան', + 'Բահամներ', + 'Բահրեյն', + 'Բանգլադեշ', + 'Բարբադոս', + 'Բելառուս', + 'Բելգիա', + 'Բելիզ', + 'Բենին', + 'Բերմուդա', + 'Բութան', + 'Բոլիվիա', + 'Բոսնիա և Հերցեգովինա', + 'Բոտսվանա', + 'Բրազիլիա', + 'Բրունեյ Դարուսսալամ', + 'Բուլղարիա', + 'Բուրկինա Ֆասո', + 'Բուրունդի', + 'Կամբոջա', + 'Կամերուն', + 'Կանադա', + 'Կաբո Վերդե', + 'Կայման Կղզիներ', + 'Կենտրոնական Աֆրիկյան Հանրապետություն', + 'Չադ', + 'Չիլի', + 'Չինաստան', + 'Սուրբ Ծննդյան Կղզի', + 'Կոկոս Կղզիներ', + 'Կոլումբիա', + 'Կոմորյան Կղզիներ', + 'Կոնգո', + 'Կուկի Կղզիներ', + 'Կոստա Ռիկա', + 'Կոտ դ\'Իվուար', + 'Խորվաթիա', + 'Կուբա', + 'Կիպրոս', + 'Չեխիայի Հանրապետություն', + 'Դանիա', + 'Ջիբութի', + 'Դոմինիկա', + 'Դոմինիկյան Հանրապետություն', + 'Էկվադոր', + 'Եգիպտոս', + 'Սալվադոր', + 'Հասարակածային Գվինեա', + 'Էրիտրեա', + 'Էստոնիա', + 'Եթովպիա', + 'Ֆարերյան Կղզիներ', + 'Ֆոլկլենդյան Կղզիներ', + 'Ֆիջի', + 'Ֆինլանդիա', + 'Ֆրանսիա', + 'Ֆրանսիական Գվիանա', + 'Ֆրանսիական Պոլինեզիա', + 'Ֆրանսիական Հարավային Տարածքներ', + 'Գաբոն', + 'Գամբիա', + 'Վրաստան', + 'Գերմանիա', + 'Գանա', + 'Ջիբրալթար', + 'Հունաստան', + 'Գրենլանդիա', + 'Գրենադա', + 'Գվադելուպա', + 'Գուամ', + 'Գվատեմալա', + 'Գերնսի', + 'Գվինեա', + 'Գվինեա Բիսաու', + 'Գայանա', + 'Հաիթի', + 'Վատիկան', + 'Հոնդուրաս', + 'Հոնգ Կոնգ', + 'Հունգարիա', + 'Իսլանդիա', + 'Հնդկաստան', + 'Ինդոնեզիա', + 'Իրան', + 'Իրաք', + 'Իռլանիա', + 'Իսրայել', + 'Իտալիա', + 'Ջամայկա', + 'Ճապոնիա', + 'Հորդանան', + 'Ղազախստան', + 'Քենիա', + 'Կիրիբատի', + 'Հյուսիսային Կորեա', + 'Հարավային Կորեա', + 'Կոսովո', + 'Քուվեյթ', + 'Ղրղզստան', + 'Լաոս', + 'Լատվիա', + 'Լիբանան', + 'Լեսոտո', + 'Լիբերիա', + 'Լիբիական Արաբական Ջամահիրիա', + 'Լիխտենշտեյն', + 'Լիտվա', + 'Լյուքսեմբուրգ', + 'Մակաո', + 'Մակեդոնիա', + 'Մադագասկար', + 'Մալավի', + 'Մալազիա', + 'Մալդիվներ', + 'Մալի', + 'Մալթա', + 'Մարշալյան Կղզիներ', + 'Մարտինիկ', + 'Մավրիտանիա', + 'Մավրիկիոս', + 'Մայոտտե', + 'Մեքսիկա', + 'Միկրոնեզիա', + 'Մոլդովա', + 'Մոնակո', + 'Մոնղոլիա', + 'Չեռնոգորիա', + 'Մոնսերատ', + 'Մարոկկո', + 'Մոզամբիկ', + 'Մյանմա', + 'Նամիբիա', + 'Նաուրու', + 'Նեպալ', + 'Նիդեռլանդական Անտիլներ', + 'Նիդերլանդներ', + 'Նոր Կալեդոնիա', + 'Նոր Զելանդիա', + 'Նիկարագուա', + 'Նիգեր', + 'Նիգերիա', + 'Նիուե', + 'Նորֆոլկ Կղզի', + 'Հյուսիսային Մարիանյան Կղզիներ', + 'Նորվեգիա', + 'Օման', + 'Պակիստան', + 'Պալաու', + 'Պաղեստին', + 'Պանամա', + 'Պապուա Նոր Գվինեա', + 'Պարագվայ', + 'Պերու', + 'Ֆիլիպիններ', + 'Պիտկիրնյան Կղզիներ', + 'Լեհաստան', + 'Պորտուգալիա', + 'Պուերտո Ռիկո', + 'Կատար', + 'Ռումինիա', + 'Ռուսաստանի Դաշնություն', + 'Ռուանդա', + 'Սուրբ Բարդուղիմեոս', + 'Սուրբ Հելենա', + 'Սենտ Կիտս և Նևիս', + 'Սուրբ Լուչիա', + 'Սուրբ Մարտին', + 'Սեն Պիեռ և Միկելոն', + 'Սենթ Վինսենթ և Գրենադիններ', + 'Սամոա', + 'Սան Մարինո', + 'Սաուդյան Արաբիա', + 'Սենեգալ', + 'Սերբիա', + 'Սեյշելներ', + 'Սիերա Լեոնե', + 'Սինգապուր', + 'Սլովակիա', + 'Սլովենիա', + 'Սողոմոնյան Կղզիներ', + 'Սոմալի', + 'Հարավային Աֆրիկա', + 'Իսպանիա', + 'Շրի Լանկա', + 'Սուդան', + 'Սուրինամ', + 'Սվալբարդ և Յան Մայենյան Կղզիներ', + 'Սվազիլենդ', + 'Շվեդիա', + 'Շվեյցարիա', + 'Սիրիայի Արաբական Հանրապետություն', + 'Թայվան', + 'Տաջիկստան', + 'Տանզանիա', + 'Թաիլանդ', + 'Տոգո', + 'Տոկելաու', + 'Տոնգա', + 'Տրինիդադ և Տոբագո', + 'Թունիս', + 'Թուրքիա', + 'Թուրքմենստան', + 'Տուվալու', + 'Ուգանդա', + 'Ուկրաինա', + 'Արաբական Միացյալ Էմիրություններ', + 'Մեծ Բրիտանիա', + 'Ամերիկայի Միացյալ Նահանգներ', + 'Ուրուգվայ', + 'Ուզբեկստան', + 'Վենեսուելա', + 'Վիետնամ', + 'Ուոլիս և Ֆուտունա', + 'Արևմտյան Սահարա', + 'Եմեն', + 'Զամբիա', + 'Զիմբաբվե', + ) + + # Source: Administrative divisions of Armenia (Wikipedia) + # https://en.wikipedia.org/wiki/Administrative_divisions_of_Armenia + states = ( + 'Արագածոտն', + 'Արարատ', + 'Արմավիր', + 'Գեղարքունիք', + 'Լոռի', + 'Կոտայք', + 'Շիրակ', + 'Սյունիք', + 'Տավուշ', + 'Վայոց Ձոր', + ) + + states_abbr = ( + 'ԱԳ', + 'ԱՐ', + 'ԱՄ', + 'ԳՂ', + 'ԼՌ', + 'ԿՏ', + 'ՇԿ', + 'ՍՅ', + 'ՎՁ', + 'ՏՎ', + ) + + # Source: Postal codes in Armenia (Wikipedia) + # https://en.wikipedia.org/wiki/Postal_codes_in_Armenia + states_postcode = { + 'ԱԳ': (200, 599), + 'ԱՐ': (600, 899), + 'ԱՄ': (900, 1199), + 'ԳՂ': (1200, 1699), + 'ԼՌ': (1700, 2199), + 'ԿՏ': (2200, 2599), + 'ՇԿ': (2600, 3199), + 'ՍՅ': (3200, 3599), + 'ՎՁ': (3600, 3899), + 'ՏՎ': (3900, 4299), + } + + streets = ( + 'Ազատության', + 'Արշակունյաց', + 'Արցախի', + 'Գայի', + 'Ծովակալ Իսակովի', + 'Կոմիտասի', + 'Հյուսիսային', + 'Մաշտոցի', + 'Մարշալ Բաղրամյան', + 'Մյասնիկյան', + 'Սայաթ-Նովայի', + 'Տիգրան Մեծի', + 'Աբելյան', + 'Աբովյան', + 'Ագաթանգեղոսի', + 'Ազատամարտիկների', + 'Աթենքի', + 'Աթոյան', + 'Ալեք Մանուկյան', + 'Ալիխանյան', + 'Աղայան', + 'Աղյուսագործների', + 'Ամիրյան', + 'Այասի', + 'Անտառային', + 'Անրի Վեռնոյի', + 'Ավագ Պետրոսյան', + 'Արամ Խաչատրյան', + 'Արամի', + 'Արգիշտիի', + 'Արմենակյան', + 'Բայրոնի', + 'Բարձրաբերդի', + 'Բելինսկու', + 'Բեյրութի', + 'Բուդապեշտի', + 'Բուռնազյան', + 'Բրյուսովի', + 'Գալոյան Եղբայրների', + 'Գարեգին Նժդեհի', + 'Գետառի', + 'Գլինկայի', + 'Գյուլբենկյան', + 'Գրիգոր Լուսավորչի', + 'Գրիգոր Հարությունյան', + 'Գրիգոր Տեր-Գրիգորյան', + 'Գևորգ Էմինի', + 'Գևորգ Հովսեփյան', + 'Գևորգ Քոչարի', + 'Դեղատան', + 'Դերենիկ Դեմիրճյան', + 'Եզնիկ Կողբացու', + 'Եկմալյան', + 'Երվանդ Քոչարի', + 'Զավարյան', + 'Զարոբյան', + 'Զաքյան', + 'Էրեբունու', + 'Թաիրովի', + 'Թամանյան', + 'Թորամանյան', + 'Թումանյան', + 'Իսահակյան', + 'Իսրայելյան', + 'Իտալիայի', + 'Լամբրոնի', + 'Լենինգրադյան', + 'Լեոյի', + 'Լեոնիդ Ազգալդյան', + 'Լեռ Կամսարի', + 'Լիսինյան', + 'Լոմոնոսովի', + 'Լոռիս-Մելիքովի', + 'Լուսինյանց', + 'Խանզադյան', + 'Խանջյան', + 'Ծատուրյան', + 'Ծխախոտագործների', + 'Կալենցի', + 'Կասյան', + 'Կարեն Դեմիրճյան', + 'Կիևյան', + 'Կոնդի', + 'Կորի', + 'Կորյունի', + 'Կուստոյի', + 'Կռիլովի', + 'Հալաբյան', + 'Հակոբ Հակոբյան', + 'Հայրիկ Մուրադյան', + 'Հանրապետության', + 'Հերացու', + 'Հին Երևանցու', + 'Հնդկաստանի', + 'Հովհաննես Կոզեռնի', + 'Հրանտ Շահինյան', + 'Հրաչյա Քոչարի', + 'Ձորափի', + 'Ղազար Փարպեցու', + 'Մայիսյան', + 'Մարկ Գրիգորյան', + 'Մարտի 8-ի', + 'Մելիք-Ադամյան', + 'Միչուրինի', + 'Մհեր Մկրտչյան', + 'Մոնթե Մելքոնյան', + 'Մոսկովյան', + 'Մովսես Խորենացու', + 'Մուրացանի', + 'Նալբանդյան', + 'Նար-Դոսի', + 'Նորքի', + 'Շարա Տալյան', + 'Շարիմանյան', + 'Շուկայի', + 'Ոսկերիչների', + 'Չայկովսկու', + 'Չարենցի', + 'Չեռնիշևսկու', + 'Պարոնյան', + 'Պետրոս Ադամյան', + 'Պուշկինի', + 'Պռոշյան', + 'Պրահայի', + 'Ռոստոմի', + 'Ռոստովյան', + 'Ռուսթավելու', + 'Սասունցի Դավթի', + 'Սարալանջի', + 'Սարմենի', + 'Սարյան', + 'Սեբաստիայի', + 'Սերգեյ Փարաջանովի', + 'Սիլվա Կապուտիկյան', + 'Սիմեոն Երևանցու', + 'Սիսվանի', + 'Սոսեի', + 'Սուվորովի', + 'Սուրբ Հովհաննեսի', + 'Սպենդիարյան', + 'Ստեփան Զորյան', + 'Սևանի', + 'Վազգեն Սարգսյան', + 'Վահրամ Փափազյան', + 'Վաղարշյան', + 'Վարդան Աճեմյան', + 'Վարդանանց', + 'Վերֆելի', + 'Վրացյան', + 'Տարսոնի', + 'Տերյան', + 'Տոլստոյի', + 'Տպագրիչների', + 'Ցախի', + 'Փավստոս Բուզանդի', + 'Քաջազնունու', + 'Քոչինյան', + 'Քրիստափորի', + 'Օստրովսկու', + 'Օրբելի Եղբայրների', + 'Ֆիզկուլտուրնիկների', + 'Ֆիրդուսու', + 'Ֆրիկի', + ) + + # Source: Villages in Armenia (Wikipedia) + # http://www.armeniapedia.org/wiki/Armenian_Towns_and_Villages + villages = ( + 'Ագարակ', + 'Անտառուտ', + 'Բերքառատ', + 'Գեղաձոր', + 'Գետափ', + 'Զովասար', + 'Լեռնապար', + 'Լուսագյուղ', + 'Կաթնաղբյուր', + 'Կաքավաձոր', + 'Հացաշեն', + 'Նորաշեն', + 'Շենավան', + 'Ոսկեվազ', + 'Ցամաքասար', + 'Այգեզարդ', + 'Բարձրաշեն', + 'Բերքանուշ', + 'Լանջանիստ', + 'Լուսաշող', + 'Ջրաշեն', + 'Քաղցրաշեն', + 'Այգեկ', + 'Առատաշեն', + 'Բամբակաշատ', + 'Գեղակերտ', + 'Լեռնամերձ', + 'Ծաղկալանջ', + 'Հացիկ', + 'Մերձավան', + 'Քարակերտ', + 'Անտառամեջ', + 'Արծվաշեն', + 'Գեղաքար', + 'Զովաբեր', + 'Լանջաղբյուր', + 'Շատջրեք', + 'Այգեհատ', + 'Դարպաս', + 'Լեռնահովիտ', + 'Հարթագյուղ', + 'Պաղաղբյուր', + 'Սարամեջ', + 'Քարաձոր', + 'Զովք', + 'Լեռնանիստ', + 'Մեղրաձոր', + 'Այգաբաց', + 'Թավշուտ', + 'Լանջիկ', + 'Կարմրավան', + 'Հայկասար', + 'Նահապետավան', + 'Վարդաղբյուր', + 'Քարաբերդ', + 'Արծվանիկ', + 'Բարձրավան', + 'Կաղնուտ', + 'Հացավան', + 'Նռնաձոր', + 'Սառնակունք', + 'Աղավնաձոր', + 'Սևաժայռ', + 'Վերնաշեն', + 'Այգեհովիտ', + 'Արծվաբերդ', + 'Բերքաբեր', + 'Գետահովիտ', + 'Ծաղկավան', + 'Հաղթանակ', + 'Ոսկեպար', + 'Սարիգյուղ', + ) + + def city(self): + """ + :example 'Բյուրեղավան' + """ + return self.random_element(self.cities) + + def city_prefix(self): + """ + :example 'ք.' + """ + return self.random_element(self.city_prefixes) + + def postcode(self): + """ + :example '3159' + """ + return "%04d" % self.generator.random.randint(200, 4299) + + def postcode_in_state(self, state_abbr=None): + """ + :example '4703' + """ + if state_abbr is None: + state_abbr = self.random_element(self.states_abbr) + + if state_abbr in self.states_abbr: + postcode = "%d" % (self.generator.random.randint( + self.states_postcode[state_abbr][0], + self.states_postcode[state_abbr][1])) + + if len(postcode) == 3: + postcode = "0%s" % postcode + + return postcode + + else: + raise Exception('State Abbreviation not found in list') + + def secondary_address(self): + """ + :example 'բն. 49' + """ + return self.numerify(self.random_element(self.secondary_address_formats)) + + def state(self): + """ + :example 'Կոտայք' + """ + return self.random_element(self.states) + + def state_abbr(self): + """ + :example 'ՎՁ' + """ + return self.random_element(self.states_abbr) + + def street(self): + """ + :example 'Ոսկերիչների' + """ + return self.random_element(self.streets) + + def street_prefix(self): + """ + :example 'փողոց' + """ + return self.random_element(self.street_prefixes) + + def village(self): + """ + :example 'Ոսկեվազ' + """ + return self.random_element(self.villages) + + def village_prefix(self): + """ + :example 'գ.' + """ + return self.random_element(self.village_prefixes) diff --git a/testbed/joke2k__faker/faker/providers/address/id_ID/__init__.py b/testbed/joke2k__faker/faker/providers/address/id_ID/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3447f921f8846a4fef7ef68db259e6ed805a8e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/id_ID/__init__.py @@ -0,0 +1,169 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + building_number_formats = ('###', '##', '#') + + city_formats = ('{{city_name}}',) + + postcode_formats = ('#####',) + + street_name_formats = ( + '{{street_prefix_short}} {{street}}', + '{{street_prefix_long}} {{street}}', + ) + + street_address_formats = ( + '{{street_name}} No. {{building_number}}', + ) + + address_formats = ( + '{{street_address}}\n{{city}}, {{state}} {{postcode}}', + '{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}', + ) + + # From + # http://elibrary.dephub.go.id/elibrary/media/catalog/0010-021500000000135/swf/618/Lampiran%20E%20Data%20Bandung.pdf + # https://www.surabaya.go.id/id/info-penting/47601/daftar-nama-jalan-dan-status-ja + # https://www.streetdirectory.com/indonesia/jakarta/asia_travel/street/popular/ + streets = ( + 'Abdul Muis', 'Antapani Lama', 'Asia Afrika', 'Astana Anyar', 'BKR', + 'Cihampelas', 'Cikapayang', 'Cikutra Barat', 'Cikutra Timur', + 'Ciumbuleuit', 'Ciwastra', 'Dipatiukur', 'Dipenogoro', 'Dr. Djunjunan', + 'Gardujati', 'Gedebage Selatan', 'Gegerkalong Hilir', + 'HOS. Cokroaminoto', 'Ir. H. Djuanda', 'Jakarta', 'Jamika', + 'Jend. A. Yani', 'Jend. Sudirman', 'K.H. Wahid Hasyim', 'Kebonjati', + 'Kiaracondong', 'Laswi', 'Lembong', 'Merdeka', 'Moch. Ramdan', + 'Moch. Toha', 'Pacuan Kuda', 'Pasir Koja', 'Pasirkoja', 'Pasteur', + 'Pelajar Pejuang', 'Peta', 'PHH. Mustofa', 'Rajawali Barat', + 'Rajawali Timur', 'Raya Setiabudhi', 'Raya Ujungberung', 'Rumah Sakit', + 'Sadang Serang', 'Sentot Alibasa', 'Setiabudhi', 'Siliwangi', + 'Soekarno Hatta', 'Sukabumi', 'Sukajadi', 'Suniaraja', 'Surapati', + 'Tubagus Ismail', 'Veteran', 'W.R. Supratman', 'Bangka Raya', 'Cempaka', + 'Cihampelas', 'Erlangga', 'Rawamangun', 'Waringin', 'Ronggowarsito', + 'Rajiman', 'Yos Sudarso', 'S. Parman', 'Monginsidi', 'M.T Haryono', + 'Ahmad Dahlan', 'Jayawijaya', 'R.E Martadinata', 'M.H Thamrin', + 'Stasiun Wonokromo', 'Ahmad Yani', 'Joyoboyo', 'Indragiri', 'Kutai', + 'Kutisari Selatan', 'Rungkut Industri', 'Kendalsari', 'Wonoayu', + 'Medokan Ayu', 'KH Amin Jasuta', 'H.J Maemunah', 'Suryakencana', + 'Kapten Muslihat', 'Otto Iskandardinata', 'Tebet Barat Dalam', + ) + + street_prefixes_long = ( + 'Jalan', 'Gang', + ) + + street_prefixes_short = ( + 'Jl.', 'Gg.', + ) + + # From + # https://id.wikipedia.org/wiki/Daftar_kabupaten_dan_kota_di_Indonesia#Daftar_kota + cities = ( + 'Ambon', 'Balikpapan', 'Banda Aceh', 'Bandar Lampung', 'Bandung', + 'Banjar', 'Banjarbaru', 'Banjarmasin', 'Batam', 'Batu', 'Bau-Bau', + 'Bekasi', 'Bengkulu', 'Bima', 'Binjai', 'Bitung', 'Blitar', 'Bogor', + 'Bontang', 'Bukittinggi', 'Cilegon', 'Cimahi', 'Cirebon', 'Denpasar', + 'Depok', 'Dumai', 'Gorontalo', 'Jambi', 'Jayapura', 'Kediri', 'Kendari', + 'Kota Administrasi Jakarta Barat', 'Kota Administrasi Jakarta Pusat', + 'Kota Administrasi Jakarta Selatan', 'Kota Administrasi Jakarta Timur', + 'Kota Administrasi Jakarta Utara', 'Kotamobagu', 'Kupang', 'Langsa', + 'Lhokseumawe', 'Lubuklinggau', 'Madiun', 'Magelang', 'Makassar', + 'Malang', 'Manado', 'Mataram', 'Medan', 'Metro', 'Meulaboh', + 'Mojokerto', 'Padang', 'Padang Sidempuan', 'Padangpanjang', 'Pagaralam', + 'Palangkaraya', 'Palembang', 'Palopo', 'Palu', 'Pangkalpinang', + 'Parepare', 'Pariaman', 'Pasuruan', 'Payakumbuh', 'Pekalongan', + 'Pekanbaru', 'Pematangsiantar', 'Pontianak', 'Prabumulih', + 'Probolinggo', 'Purwokerto', 'Sabang', 'Salatiga', 'Samarinda', + 'Sawahlunto', 'Semarang', 'Serang', 'Sibolga', 'Singkawang', 'Solok', + 'Sorong', 'Subulussalam', 'Sukabumi', 'Sungai Penuh', 'Surabaya', + 'Surakarta', 'Tangerang', 'Tangerang Selatan', 'Tanjungbalai', + 'Tanjungpinang', 'Tarakan', 'Tasikmalaya', 'Tebingtinggi', 'Tegal', + 'Ternate', 'Tidore Kepulauan', 'Tomohon', 'Tual', 'Yogyakarta', + ) + + # From https://id.wikipedia.org/wiki/Daftar_provinsi_di_Indonesia + states = ( + 'Aceh', 'Bali', 'Banten', 'Bengkulu', 'DI Yogyakarta', 'DKI Jakarta', + 'Gorontalo', 'Jambi', 'Jawa Barat', 'Jawa Tengah', 'Jawa Timur', + 'Kalimantan Barat', 'Kalimantan Selatan', 'Kalimantan Tengah', + 'Kalimantan Timur', 'Kalimantan Utara', 'Kepulauan Bangka Belitung', + 'Kepulauan Riau', 'Lampung', 'Maluku', 'Maluku Utara', + 'Nusa Tenggara Barat', 'Nusa Tenggara Timur', 'Papua', 'Papua Barat', + 'Riau', 'Sulawesi Barat', 'Sulawesi Selatan', 'Sulawesi Tengah', + 'Sulawesi Tenggara', 'Sulawesi Utara', 'Sumatera Barat', + 'Sumatera Selatan', 'Sumatera Utara', + ) + + # https://id.wikipedia.org/wiki/Daftar_provinsi_di_Indonesia + states_abbr = ( + 'AC', 'BA', 'BT', 'BE', 'YO', 'JK', 'GO', + 'JA', 'JB', 'JT', 'JI', 'KB', 'KS', 'KT', + 'KI', 'KU', 'BB', 'KR', 'LA', 'MA', 'MU', + 'NB', 'NT', 'PA', 'PB', 'RI', 'SR', 'SN', 'ST', + 'SG', 'SU', 'SB', 'SS', 'SU', + ) + + # From https://id.wikipedia.org/wiki/Daftar_negara-negara_di_dunia + countries = ( + 'Afganistan', 'Afrika Selatan', 'Afrika Tengah', 'Albania', 'Aljazair', + 'Amerika Serikat', 'Andorra', 'Angola', 'Antigua dan Barbuda', + 'Arab Saudi', 'Argentina', 'Armenia', 'Australia', 'Austria', + 'Azerbaijan', 'Bahama', 'Bahrain', 'Bangladesh', 'Barbados', 'Belanda', + 'Belarus', 'Belgia', 'Belize', 'Benin', 'Bhutan', 'Bolivia', + 'Bosnia dan Herzegovina', 'Botswana', 'Brasil', 'Britania Raya', + 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Ceko', 'Chad', + 'Chili', 'Denmark', 'Djibouti', 'Dominika', 'Ekuador', 'El Salvador', + 'Eritrea', 'Estonia', 'Ethiopia', 'Federasi Mikronesia', 'Fiji', + 'Filipina', 'Finlandia', 'Gabon', 'Gambia', 'Georgia', 'Ghana', + 'Grenada', 'Guatemala', 'Guinea', 'Guinea Khatulistiwa', + 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hongaria', 'India', + 'Indonesia', 'Irak', 'Iran', 'Islandia', 'Israel', 'Italia', 'Jamaika', + 'Jepang', 'Jerman', 'Kamboja', 'Kamerun', 'Kanada', 'Kazakhstan', + 'Kenya', 'Kepulauan Marshall', 'Kepulauan Solomon', 'Kirgizstan', + 'Kiribati', 'Kolombia', 'Komoro', 'Korea Selatan', 'Korea Utara', + 'Kosta Rika', 'Kroasia', 'Kuba', 'Kuwait', 'Laos', 'Latvia', 'Lebanon', + 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lituania', + 'Luksemburg', 'Madagaskar', 'Maladewa', 'Malawi', 'Malaysia', 'Mali', + 'Malta', 'Maroko', 'Mauritania', 'Mauritius', 'Meksiko', 'Mesir', + 'Moldova', 'Monako', 'Mongolia', 'Montenegro', 'Mozambik', 'Myanmar', + 'Namibia', 'Nauru', 'Nepal', 'Niger', 'Nigeria', 'Nikaragua', + 'Norwegia', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Pantai Gading', + 'Papua Nugini', 'Paraguay', 'Perancis', 'Peru', 'Polandia', 'Portugal', + 'Qatar', 'Republik Demokratik Kongo', 'Republik Dominika', + 'Republik Irlandia', 'Republik Kongo', 'Republik Makedonia', + 'Republik Rakyat Tiongkok', 'Rumania', 'Rusia', 'Rwanda', + 'Saint Kitts dan Nevis', 'Saint Lucia', 'Saint Vincent dan Grenadine', + 'Samoa', 'San Marino', 'São Tomé dan Príncipe', 'Selandia Baru', + 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapura', + 'Siprus', 'Slovenia', 'Slowakia', 'Somalia', 'Spanyol', 'Sri Lanka', + 'Sudan', 'Sudan Selatan', 'Suriah', 'Suriname', 'Swaziland', 'Swedia', + 'Swiss', 'Tajikistan', 'Tanjung Verde', 'Tanzania', 'Thailand', + 'Timor Leste', 'Togo', 'Tonga', 'Trinidad dan Tobago', 'Tunisia', + 'Turki', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraina', + 'Uni Emirat Arab', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatikan', + 'Venezuela', 'Vietnam', 'Yaman', 'Yordania', 'Yunani', 'Zambia', + 'Zimbabwe', + ) + + def street(self): + return self.random_element(self.streets) + + def street_prefix_short(self): + return self.random_element(self.street_prefixes_short) + + def street_prefix_long(self): + return self.random_element(self.street_prefixes_long) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) + + def state_abbr(self): + return self.random_element(self.states_abbr) + + def country(self): + return self.random_element(self.countries) diff --git a/testbed/joke2k__faker/faker/providers/address/it_IT/__init__.py b/testbed/joke2k__faker/faker/providers/address/it_IT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8020c9397e51c1b08fb20a998908c4a058c75853 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/it_IT/__init__.py @@ -0,0 +1,128 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_prefixes = ('San', 'Borgo', 'Sesto', 'Quarto', 'Settimo') + city_suffixes = ('a mare', 'lido', 'ligure', 'del friuli', 'salentino', + 'calabro', 'veneto', 'nell\'emilia', 'umbro', 'laziale', + 'terme', 'sardo') + building_number_formats = ('###', '##', '#') + street_suffixes = ('Piazza', 'Strada', 'Via', 'Borgo', 'Contrada', + 'Rotonda', 'Incrocio', 'Viale', 'Stretto', 'Vicolo', + 'Canale') + postcode_formats = ('#####', ) + states = ('Agrigento', 'Alessandria', 'Ancona', 'Aosta', 'Arezzo', + 'Ascoli Piceno', 'Asti', 'Avellino', 'Bari', + 'Barletta-Andria-Trani', 'Belluno', 'Benevento', 'Bergamo', + 'Biella', 'Bologna', 'Bolzano', 'Brescia', 'Brindisi', + 'Cagliari', 'Caltanissetta', 'Campobasso', 'Carbonia-Iglesias', + 'Caserta', 'Catania', 'Catanzaro', 'Chieti', 'Como', 'Cosenza', + 'Cremona', 'Crotone', 'Cuneo', 'Enna', 'Fermo', 'Ferrara', + 'Firenze', 'Foggia', 'Forlì-Cesena', 'Frosinone', 'Genova', + 'Gorizia', 'Grosseto', 'Imperia', 'Isernia', 'La Spezia', + 'L\'Aquila', 'Latina', 'Lecce', 'Lecco', 'Livorno', 'Lodi', + 'Lucca', 'Macerata', 'Mantova', 'Massa-Carrara', 'Matera', + 'Messina', 'Milano', 'Modena', 'Monza e della Brianza', 'Napoli', + 'Novara', 'Nuoro', 'Olbia-Tempio', 'Oristano', 'Padova', + 'Palermo', 'Parma', 'Pavia', 'Perugia', 'Pesaro e Urbino', + 'Pescara', 'Piacenza', 'Pisa', 'Pistoia', 'Pordenone', 'Potenza', + 'Prato', 'Ragusa', 'Ravenna', 'Reggio Calabria', 'Reggio Emilia', + 'Rieti', 'Rimini', 'Roma', 'Rovigo', 'Salerno', + 'Medio Campidano', 'Sassari', 'Savona', 'Siena', 'Siracusa', + 'Sondrio', 'Taranto', 'Teramo', 'Terni', 'Torino', 'Ogliastra', + 'Trapani', 'Trento', 'Treviso', 'Trieste', 'Udine', 'Varese', + 'Venezia', 'Verbano-Cusio-Ossola', 'Vercelli', 'Verona', + 'Vibo Valentia', 'Vicenza', 'Viterbo') + states_abbr = ('AG', 'AL', 'AN', 'AO', 'AR', 'AP', 'AT', 'AV', 'BA', 'BT', + 'BL', 'BN', 'BG', 'BI', 'BO', 'BZ', 'BS', 'BR', 'CA', 'CL', + 'CB', 'CI', 'CE', 'CT', 'CZ', 'CH', 'CO', 'CS', 'CR', 'KR', + 'CN', 'EN', 'FM', 'FE', 'FI', 'FG', 'FC', 'FR', 'GE', 'GO', + 'GR', 'IM', 'IS', 'SP', 'AQ', 'LT', 'LE', 'LC', 'LI', 'LO', + 'LU', 'MC', 'MN', 'MS', 'MT', 'ME', 'MI', 'MO', 'MB', 'NA', + 'NO', 'NU', 'OT', 'OR', 'PD', 'PA', 'PR', 'PV', 'PG', 'PU', + 'PE', 'PC', 'PI', 'PT', 'PN', 'PZ', 'PO', 'RG', 'RA', 'RC', + 'RE', 'RI', 'RN', 'RM', 'RO', 'SA', 'VS', 'SS', 'SV', 'SI', + 'SR', 'SO', 'TA', 'TE', 'TR', 'TO', 'OG', 'TP', 'TN', 'TV', + 'TS', 'UD', 'VA', 'VE', 'VB', 'VC', 'VR', 'VV', 'VI', 'VT') + countries = ( + 'Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra', + 'Angola', 'Anguilla', 'Antartide (territori a sud del 60° parallelo)', + 'Antigua e Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', + 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', + 'Barbados', 'Bielorussia', 'Belgio', 'Belize', 'Benin', 'Bermuda', + 'Bhutan', 'Bolivia', 'Bosnia e Herzegovina', 'Botswana', + 'Bouvet Island (Bouvetoya)', 'Brasile', + 'Territorio dell\'arcipelago indiano', 'Isole Vergini Britanniche', + 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambogia', + 'Cameroon', 'Canada', 'Capo Verde', 'Isole Cayman', + 'Repubblica Centrale Africana', 'Chad', 'Cile', 'Cina', + 'Isola di Pasqua', 'Isola di Cocos (Keeling)', 'Colombia', 'Comoros', + 'Congo', 'Isole Cook', 'Costa Rica', 'Costa d\'Avorio', 'Croazia', + 'Cuba', 'Cipro', 'Repubblica Ceca', 'Danimarca', 'Gibuti', + 'Repubblica Dominicana', 'Equador', 'Egitto', 'El Salvador', + 'Guinea Equatoriale', 'Eritrea', 'Estonia', 'Etiopia', 'Isole Faroe', + 'Isole Falkland (Malvinas)', 'Fiji', 'Finlandia', 'Francia', + 'Guyana Francese', 'Polinesia Francese', 'Territori Francesi del sud', + 'Gabon', 'Gambia', 'Georgia', 'Germania', 'Ghana', 'Gibilterra', + 'Grecia', 'Groenlandia', 'Grenada', 'Guadalupa', 'Guam', 'Guatemala', + 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', + 'Heard Island and McDonald Islands', 'Città del Vaticano', 'Honduras', + 'Hong Kong', 'Ungheria', 'Islanda', 'India', 'Indonesia', 'Iran', + 'Iraq', 'Irlanda', 'Isola di Man', 'Israele', 'Italia', 'Giamaica', + 'Giappone', 'Jersey', 'Giordania', 'Kazakhstan', 'Kenya', 'Kiribati', + 'Korea', 'Kuwait', 'Republicca Kirgiza', 'Repubblica del Laos', + 'Latvia', 'Libano', 'Lesotho', 'Liberia', 'Libyan Arab Jamahiriya', + 'Liechtenstein', 'Lituania', 'Lussemburgo', 'Macao', 'Macedonia', + 'Madagascar', 'Malawi', 'Malesia', 'Maldive', 'Mali', 'Malta', + 'Isole Marshall', 'Martinica', 'Mauritania', 'Mauritius', 'Mayotte', + 'Messico', 'Micronesia', 'Moldova', 'Principato di Monaco', 'Mongolia', + 'Montenegro', 'Montserrat', 'Marocco', 'Mozambico', 'Myanmar', + 'Namibia', 'Nauru', 'Nepal', 'Antille Olandesi', 'Olanda', + 'Nuova Caledonia', 'Nuova Zelanda', 'Nicaragua', 'Niger', 'Nigeria', + 'Niue', 'Isole Norfolk', 'Northern Mariana Islands', 'Norvegia', + 'Oman', 'Pakistan', 'Palau', 'Palestina', 'Panama', + 'Papua Nuova Guinea', 'Paraguay', 'Peru', 'Filippine', + 'Pitcairn Islands', 'Polonia', 'Portogallo', 'Porto Rico', 'Qatar', + 'Reunion', 'Romania', 'Russia', 'Rwanda', 'San Bartolomeo', + 'Sant\'Elena', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin', + 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', + 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Arabia Saudita', + 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', + 'Slovenia', 'Isole Solomon', 'Somalia', 'Sud Africa', + 'Georgia del sud e South Sandwich Islands', 'Spagna', 'Sri Lanka', + 'Sudan', 'Suriname', 'Svalbard & Jan Mayen Islands', 'Swaziland', + 'Svezia', 'Svizzera', 'Siria', 'Taiwan', 'Tajikistan', 'Tanzania', + 'Tailandia', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', + 'Trinidad e Tobago', 'Tunisia', 'Turchia', 'Turkmenistan', + 'Isole di Turks and Caicos', 'Tuvalu', 'Uganda', 'Ucraina', + 'Emirati Arabi Uniti', 'Regno Unito', 'Stati Uniti d\'America', + 'United States Minor Outlying Islands', 'Isole Vergini Statunitensi', + 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam', + 'Wallis and Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe') + + city_formats = ('{{city_prefix}} {{first_name}} {{city_suffix}}', + '{{city_prefix}} {{first_name}}', + '{{first_name}} {{city_suffix}}', + '{{last_name}} {{city_suffix}}') + street_name_formats = ('{{street_suffix}} {{first_name}}', + '{{street_suffix}} {{last_name}}') + street_address_formats = ( + '{{street_name}} {{building_number}}', + '{{street_name}} {{building_number}} {{secondary_address}}') + address_formats = ( + "{{street_address}}\n{{city}}, {{postcode}} {{state}} ({{state_abbr}})", + ) + secondary_address_formats = ('Appartamento ##', 'Piano #') + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def secondary_address(self): + return self.numerify( + self.random_element(self.secondary_address_formats)) + + def state(self): + return self.random_element(self.states) + + def state_abbr(self): + return self.random_element(self.states_abbr) diff --git a/testbed/joke2k__faker/faker/providers/address/ja_JP/__init__.py b/testbed/joke2k__faker/faker/providers/address/ja_JP/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17638affa7673624d6f9513cbce14f66dc3d7e4a --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/ja_JP/__init__.py @@ -0,0 +1,355 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + address_formats = ( + '{{prefecture}}{{city}}{{town}}{{chome}}{{ban}}{{gou}}', + '{{prefecture}}{{city}}{{town}}{{chome}}{{ban}}{{gou}} {{town}}{{building_name}}{{building_number}}', + '{{prefecture}}{{city}}{{town}}{{chome}}{{ban}}{{gou}} {{building_name}}{{town}}{{building_number}}') + + building_number_formats = ('###', ) + + countries = ( + 'アフガニスタン', + 'アルバニア', + 'アルジェリア', + 'アメリカ領サモア', + 'アンドラ', + 'アンゴラ', + 'アンギラ', + '南極大陸', + 'アンティグアバーブーダ', + 'アルゼンチン', + 'アルメニア', + 'アルバ', + 'オーストラリア', + 'オーストリア', + 'アゼルバイジャン', + 'バハマ', + 'バーレーン', + 'バングラデシュ', + 'バルバドス', + 'ベラルーシ', + 'ベルギー', + 'ベリーズ', + 'ベナン', + 'バミューダ島', + 'ブータン', + 'ボリビア', + 'ボスニア・ヘルツェゴビナ', + 'ボツワナ', + 'ブーベ島', + 'ブラジル', + 'イギリス領インド洋地域', + 'イギリス領ヴァージン諸島', + 'ブルネイ', + 'ブルガリア', + 'ブルキナファソ', + 'ブルンジ', + 'カンボジア', + 'カメルーン', + 'カナダ', + 'カーボベルデ', + 'ケイマン諸島', + '中央アフリカ共和国', + 'チャド', + 'チリ', + '中国', + 'クリスマス島', + 'ココス諸島', + 'コロンビア', + 'コモロ', + 'コンゴ共和国', + 'クック諸島', + 'コスタリカ', + 'コートジボワール', + 'クロアチア', + 'キューバ', + 'キプロス共和国', + 'チェコ共和国', + 'デンマーク', + 'ジブチ共和国', + 'ドミニカ国', + 'ドミニカ共和国', + 'エクアドル', + 'エジプト', + 'エルサルバドル', + '赤道ギニア共和国', + 'エリトリア', + 'エストニア', + 'エチオピア', + 'フェロー諸島', + 'フォークランド諸島', + 'フィジー共和国', + 'フィンランド', + 'フランス', + 'フランス領ギアナ', + 'フランス領ポリネシア', + 'フランス領極南諸島', + 'ガボン', + 'ガンビア', + 'グルジア', + 'ドイツ', + 'ガーナ', + 'ジブラルタル', + 'ギリシャ', + 'グリーンランド', + 'グレナダ', + 'グアドループ', + 'グアム', + 'グアテマラ', + 'ガーンジー', + 'ギニア', + 'ギニアビサウ', + 'ガイアナ', + 'ハイチ', + 'ハード島とマクドナルド諸島', + 'バチカン市国', + 'ホンジュラス', + '香港', + 'ハンガリー', + 'アイスランド', + 'インド', + 'インドネシア', + 'イラン', + 'イラク', + 'アイルランド共和国', + 'マン島', + 'イスラエル', + 'イタリア', + 'ジャマイカ', + '日本', + 'ジャージー島', + 'ヨルダン', + 'カザフスタン', + 'ケニア', + 'キリバス', + '朝鮮', + '韓国', + 'クウェート', + 'キルギス共和国', + 'ラオス人民民主共和国', + 'ラトビア', + 'レバノン', + 'レソト', + 'リベリア', + 'リビア国', + 'リヒテンシュタイン', + 'リトアニア', + 'ルクセンブルク', + 'マカオ', + 'マケドニア共和国', + 'マダガスカル', + 'マラウィ', + 'マレーシア', + 'モルディブ', + 'マリ', + 'マルタ共和国', + 'マーシャル諸島', + 'マルティニーク', + 'モーリタニア・イスラム共和国', + 'モーリシャス', + 'マヨット', + 'メキシコ', + 'ミクロネシア連邦', + 'モルドバ共和国', + 'モナコ公国', + 'モンゴル', + 'モンテネグロ共和国', + 'モントセラト', + 'モロッコ', + 'モザンビーク', + 'ミャンマー', + 'ナミビア', + 'ナウル', + 'ネパール', + 'オランダ領アンティル', + 'オランダ', + 'ニューカレドニア', + 'ニュージーランド', + 'ニカラグア', + 'ニジェール', + 'ナイジェリア', + 'ニース', + 'ノーフォーク島', + '北マリアナ諸島', + 'ノルウェー', + 'オマーン', + 'パキスタン', + 'パラオ', + 'パレスチナ自治区', + 'パナマ', + 'パプアニューギニア', + 'パラグアイ', + 'ペルー', + 'フィリピン', + 'ピトケアン諸島', + 'ポーランド', + 'ポルトガル', + 'プエルトリコ', + 'カタール', + 'レユニオン', + 'ルーマニア', + 'ロシア', + 'ルワンダ', + 'サン・バルテルミー島', + 'セントヘレナ', + 'セントクリストファー・ネイビス連邦', + 'セントルシア', + 'セント・マーチン島', + 'サンピエール島・ミクロン島', + 'セントビンセント・グレナディーン', + 'サモア', + 'サンマリノ', + 'サントメプリンシペ', + 'サウジアラビア', + 'セネガル', + 'セルビア', + 'セイシェル', + 'シエラレオネ', + 'シンガポール', + 'スロバキア', + 'スロベニア', + 'ソロモン諸島', + 'ソマリア', + '南アフリカ共和国', + 'サウスジョージア・サウスサンドウィッチ諸島', + 'スペイン', + 'スリランカ', + 'スーダン', + 'スリナム', + 'スヴァールバル諸島およびヤンマイエン島', + 'スワジランド王国', + 'スウェーデン', + 'スイス', + 'シリア', + '台湾', + 'タジキスタン共和国', + 'タンザニア', + 'タイ', + '東ティモール', + 'トーゴ', + 'トケラウ', + 'トンガ', + 'トリニダード・トバゴ', + 'チュニジア', + 'トルコ', + 'トルクメニスタン', + 'タークス・カイコス諸島', + 'ツバル', + 'ウガンダ', + 'ウクライナ', + 'アラブ首長国連邦', + 'イギリス', + 'アメリカ合衆国', + '合衆国領有小離島', + 'アメリカ領ヴァージン諸島', + 'ウルグアイ', + 'ウズベキスタン', + 'バヌアツ', + 'ベネズエラ', + 'ベトナム', + 'ウォリス・フツナ', + '西サハラ', + 'イエメン', + 'ザンビア', + 'ジンバブエ', + ) + + prefectures = ( + '北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県', '茨城県', '栃木県', '群馬県', + '埼玉県', '千葉県', '東京都', '神奈川県', '新潟県', '富山県', '石川県', '福井県', '山梨県', '長野県', + '岐阜県', '静岡県', '愛知県', '三重県', '滋賀県', '京都府', '大阪府', '兵庫県', '奈良県', '和歌山県', + '鳥取県', '島根県', '岡山県', '広島県', '山口県', '徳島県', '香川県', '愛媛県', '高知県', '福岡県', + '佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県', + ) + + cities = ( + '八千代市', '我孫子市', '鴨川市', '鎌ケ谷市', '君津市', '富津市', '浦安市', '四街道市', '袖ケ浦市', + '八街市', '印西市', '白井市', '富里市', '南房総市', '匝瑳市', '香取市', '山武市', 'いすみ市', '大網白里市', + '印旛郡酒々井町', '印旛郡印旛村', '印旛郡本埜村', '印旛郡栄町', '香取郡神崎町', '香取郡多古町', '香取郡東庄町', + '山武郡九十九里町', '山武郡芝山町', '山武郡横芝光町', '長生郡一宮町', '長生郡睦沢町', '長生郡長生村', + '長生郡白子町', '長生郡長柄町', '長生郡長南町', '夷隅郡大多喜町', '夷隅郡御宿町', '安房郡鋸南町', '千代田区', + '中央区', '港区', '新宿区', '文京区', '台東区', '墨田区', '江東区', '品川区', '目黒区', '大田区', + '世田谷区', '渋谷区', '中野区', '杉並区', '豊島区', '北区', '荒川区', '板橋区', '練馬区', '足立区', + '葛飾区', '江戸川区', '八王子市', '立川市', '武蔵野市', '三鷹市', '青梅市', '府中市', '昭島市', '調布市', + '町田市', '小金井市', '小平市', '日野市', '東村山市', '国分寺市', '国立市', '福生市', '狛江市', '東大和市', + '清瀬市', '東久留米市', '武蔵村山市', '多摩市', '稲城市', '羽村市', 'あきる野市', '西東京市', '西多摩郡瑞穂町', + '西多摩郡日の出町', '西多摩郡檜原村', '西多摩郡奥多摩町', '大島町', '利島村', '新島村', '神津島村', '三宅島三宅村', + '御蔵島村', '八丈島八丈町', '青ヶ島村', '小笠原村', '横浜市鶴見区', '横浜市神奈川区', '横浜市西区', '横浜市中区', + '横浜市南区', '横浜市保土ケ谷区', '横浜市磯子区', '横浜市金沢区', '横浜市港北区', '横浜市戸塚区', '横浜市港南区', + '横浜市旭区', '横浜市緑区', '横浜市瀬谷区', '横浜市栄区', '横浜市泉区', '横浜市青葉区', '横浜市都筑区', + '川崎市川崎区', '川崎市幸区', '川崎市中原区', '川崎市高津区', '川崎市多摩区', '川崎市宮前区', + ) + + towns = ( + '丹勢', '中宮祠', '手岡', '東和町', '所野', '土沢', '独鈷沢', '轟', '土呂部', '中小来川', '長畑', '中鉢石町', + '中三依', '西小来川', '西川', '日光', '東三島', '東大和町', '蟇沼', '二つ室', '方京', '細竹', '前弥六', + '前弥六南町', '松浦町', '南赤田', '南郷屋', '美原町', '無栗屋', '睦', '百村', '箭坪', '山中新田', '油井', + '湯宮', '豊町', '湯本塩原', '横林', '四区町', '渡辺', '氏家', '氏家新田', '卯の里', '小入', '大中', '押上', + '柿木沢', '柿木沢新田', '鍛冶ケ沢', '上高野', '上吉羽', '木立', '権現堂', '幸手', '下宇和田', '下吉羽', '神明内', + '外国府間', '千塚', '天神島', '戸島', '中川崎', '長間', '西関宿', '花島', '平須賀', '細野', '松石', '太田ヶ谷', + '上広谷', '五味ヶ谷', '脚折', '脚折町', '鶴ヶ丘', '羽折町', '藤金', '九段南', '皇居外苑', '麹町', '猿楽町', + '外神田', '西神田', '隼町', '東神田', '一ツ橋', '日比谷公園', '平河町', '丸の内', '丸の内JPタワー', '四番町', + '六番町', '明石町', '勝どき', '京橋', '月島', '北青山', '港南', '芝浦', '芝公園', '芝大門', '白金', '白金台', + '台場', '高輪', '虎ノ門', '虎ノ門虎ノ門ヒルズ森タワー', '大京町', '高田馬場', '箪笥町', '津久戸町', '筑土八幡町', + '戸塚町', '富久町', '戸山', '秋葉原', '浅草', '浅草橋', '池之端', '今戸', '入谷', '上野公園', '上野桜木', + '雷門', '北上野', '蔵前', '千束', '台東', '鳥越', '西浅草', '日本堤', '橋場', '花川戸', '東浅草', '東上野', + '松が谷', '三筋', '三ノ輪', '元浅草', '竜泉', '吾妻橋', + ) + + building_names = ( + 'パレス', 'ハイツ', 'コーポ', 'アーバン', 'クレスト', 'パーク', 'シティ', 'シャルム', 'コート', + ) + + def prefecture(self): + """ + :example '東京都' + """ + return self.random_element(self.prefectures) + + def city(self): + """ + :example '台東区' + """ + return self.random_element(self.cities) + + def town(self): + """ + :example '浅草' + """ + return self.random_element(self.towns) + + def chome(self): + """ + :example '1丁目' + """ + return "%d丁目" % self.generator.random.randint(1, 42) + + def ban(self): + """ + :example '3番' + """ + return "%d番" % self.generator.random.randint(1, 27) + + def gou(self): + """ + :example '10号' + """ + return "%d号" % self.generator.random.randint(1, 20) + + def building_name(self): + """ + :example 'コーポ芝浦' + """ + return self.random_element(self.building_names) + + def postcode(self): + """ + :example '101-1212' + """ + return "%03d-%04d" % (self.generator.random.randint(0, 999), + self.generator.random.randint(0, 9999)) + + def zipcode(self): + return self.postcode() diff --git a/testbed/joke2k__faker/faker/providers/address/ka_GE/__init__.py b/testbed/joke2k__faker/faker/providers/address/ka_GE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..271516a8782442175b3195e4ff440419bbab9d47 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/ka_GE/__init__.py @@ -0,0 +1,304 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_formats = ['{{city_name}}'] + street_name_formats = ['{{street_title}} {{street_suffix}}'] + street_address_formats = ['{{street_name}} {{building_number}}'] + address_formats = ['{{street_address}}, {{city}}'] + building_number_formats = ['##'] + street_suffixes = ['ქ.'] + + # Source: Wikipedia's list of sovereign states + # https://en.wikipedia.org/wiki/List_of_sovereign_states + countries = ( + 'ავსტრალია', 'ავსტრია', 'ავღანეთი', 'აზერბაიჯანი', 'ალბანეთი', 'ალჟირი', + 'ამერიკის სამოა', 'ამერიკის ვირჯინიის კუნძულები', + 'ამერიკის შეერთებული შტატები', 'ანგილია', 'ანგოლა', 'ანდორა', + 'ანტიგუა და ბარბუდა', 'არაბთა გაერთიანებული საამიროები', 'არგენტინა', + 'არუბა', 'აღმოსავლეთი ტიმორი', 'ახალი ზელანდია', 'ახალი კალედონია', + 'ბანგლადეში', 'ბარბადოსი', 'ბასას-და-ინდია', 'ბაჰამის კუნძულები', + 'ბაჰრეინი', 'ბელარუსი', 'ბელგია', 'ბელიზი', 'ბენინი', 'ბერმუდა', + 'ბოლივია', 'ბოსნია და ჰერცეგოვინა', 'ბოტსვანა', 'ბრაზილია', + 'ბრიტანეთის ვირჯინიის კუნძულები', + 'ბრიტანეთის ინდოეთის ოკეანის ტერიტორია', 'ბრუნეი', 'ბულგარეთი', + 'ბურკინა ფასო', 'ბურუნდი', 'ბუვე', 'ბჰუტანი', 'გაბონი', 'გაიანა', + 'გამბია', 'განა', 'გერმანია', 'გვადელუპა', 'გვატემალა', 'გვინეა', + 'გვინეა-ბისაუ', 'გიბრალტარი', 'გრენადა', 'გრენლანდია', 'გუამი', 'დანია', + 'დიდი ბრიტანეთი', 'დომინიკელთა რესპუბლიკა', 'დომინიკა', 'ეგვიპტე', + 'ევროპა (კუნძული)', 'ეთიოპია', 'ეკვადორი', 'ეკვატორული გვინეა', 'ერაყი', + 'ერიტრეა', 'ესპანეთი', 'ესტონეთი', 'ეშმორის და კარტიეს კუნძულები', + 'უოლისი და ფუტუნა', 'ვანუატუ', 'ვატიკანი', 'ვენესუელა', 'ვიეტნამი', + 'ზამბია', 'ზიმბაბვე', 'თურქეთი', 'თურქმენეთი', 'იამაიკა', 'იან მაიენი', + 'იაპონია', 'იემენი', 'ინდოეთი', 'ინდონეზია', 'იორდანია', 'ირანი', + 'ირლანდია', 'ისლანდია', 'ისრაელი', 'იტალია', 'კაბო-ვერდე', + 'კაიმანის კუნძულები', 'კამბოჯა', 'კამერუნი', 'კანადა', 'კატარი', + 'კენია', 'კვიპროსი', 'კინგმენის რიფი', 'კირიბატი', 'ქოქოსის კუნძულები', + 'კოლუმბია', 'კომორის კუნძულები', 'კონგოს დემოკრატიული რესპუბლიკა', + 'კონგოს რესპუბლიკა', 'კორეის რესპუბლიკა', 'ჩრდილოეთი კორეა', + 'კოსტა-რიკა', 'კოტ-დ’ივუარი', 'კუბა', 'კუკის კუნძულები', 'ლაოსი', + 'ლატვია', 'ლესოთო', 'ლიბანი', 'ლიბერია', 'ლიბია', 'ლიტვა', + 'ლიხტენშტაინი', 'ლუქსემბურგი', 'მადაგასკარი', 'მავრიკი', 'მავრიტანია', + 'მაიოტა', 'მაკაო', 'მაკედონია', 'მალავი', 'მალაიზია', 'მალდივი', 'მალი', + 'მალტა', 'მაროკო', 'მარშალის კუნძულები', 'მარჯნის ზღვის კუნძულები', + 'მექსიკა', 'მიანმარი', 'მიკრონეზია', 'მოზამბიკი', 'მოლდოვა', 'მონაკო', + 'მონსერატი', 'მონღოლეთი', 'ნამიბია', 'ნაურუ', 'ნეპალი', 'ნიგერი', + 'ნიგერია', 'ნიდერლანდი', 'ნიდერლანდის ანტილები', 'ნიკარაგუა', 'ნიუე', + 'ნორვეგია', 'ნორფოლკის კუნძული', 'ომანი', 'პაკისტანი', 'პალაუ', + 'პალმირა (ატოლი)', 'პანამა', 'პაპუა-ახალი გვინეა', 'პარაგვაი', 'პერუ', + 'პიტკერნის კუნძულები', 'პოლონეთი', 'პორტუგალია', + 'პრინც-ედუარდის კუნძული', 'პუერტო-რიკო', 'ჟუან-დი-ნოვა', 'რეიუნიონი', + 'რუანდა', 'რუმინეთი', 'რუსეთი', 'საბერძნეთი', 'სალვადორი', 'სამოა', + 'სამხრეთ აფრიკის რესპუბლიკა', + 'სამხრეთი გეორგია და სამხრეთ სენდვიჩის კუნძულები', 'სამხრეთი სუდანი', + 'სან-მარინო', 'სან-ტომე და პრინსიპი', 'საუდის არაბეთი', 'საფრანგეთი', + 'საფრანგეთის გვიანა', 'საფრანგეთის პოლინეზია', + 'საფრანგეთის სამხრეთული და ანტარქტიდული ტერიტორია', 'საქართველო', + 'სეიშელის კუნძულები', 'სენეგალი', 'სენ-პიერი და მიკელონი', + 'სენტ-ვინსენტი და გრენადინები', 'სენტ-კიტსი და ნევისი', 'სენტ-ლუსია', + 'სერბეთი', 'სეუტა', 'სვაზილენდი', 'სვალბარდი', 'სიერა-ლეონე', + 'სინგაპური', 'სირია', 'სლოვაკეთი', 'სლოვენია', 'სოლომონის კუნძულები', + 'სომალი', 'სომხეთი', 'სუდანი', 'სურინამი', 'ტაივანი', 'ტაილანდი', + 'ტანზანია', 'ტაჯიკეთი', 'ტერქსისა და კაიკოსის კუნძულები', 'ტოგო', + 'ტოკელაუ', 'ტონგა', 'ტრინიდადი და ტობაგო', 'ტუვალუ', 'ტუნისი', 'უგანდა', + 'უზბეკეთი', 'უკრაინა', 'უნგრეთი', 'ურუგვაი', 'ფარერის კუნძულები', + 'ფილიპინები', 'ფინეთი', 'ფიჯი', 'ფოლკლენდის კუნძულები', 'ქუვეითი', + 'ღაზის სექტორი', 'ყაზახეთი', 'ყირგიზეთი', 'შვეიცარია', 'შვედეთი', + 'შობის კუნძული', 'შრი-ლანკა', 'ჩადი', 'ჩერნოგორია', 'ჩეხეთი', + 'ჩეჩნეთის რესპუბლიკა იჩქერია', 'ჩილე', 'ჩინეთი', + 'ჩრდილოეთი მარიანას კუნძულები', 'ცენტრალური აფრიკის რესპუბლიკა', + 'წმინდა ელენე, ამაღლება და ტრისტანი-და-კუნია', + 'წყნარი ოკეანის კუნძულები', 'ხორვატია', 'ჯერსი', 'ჯიბუტი', 'ჰაიტი', + 'ჰონდურასი', 'ჰონკონგი', 'ჰერდი და მაკდონალდის კუნძულები', + ) + + # Source: Tbilisi city directory + # http://directory.ge/map/index.php?lang=eng + street_titles = ( + '300 არაგველის', '8 მარტის', 'აბაკელიას', 'აბანოს', 'აბასთუმანის', + 'აბაშელის', 'აბაშის', 'აბაშიძე გრიგოლის', 'აბაშიძე დოდოს', + 'აბაშიძე ირაკლის', 'აბაშიძე ჰეიდარის', 'აბაშიძის', + 'აბდუშელიშვილი მალხაზის', 'აბესაძე გიას', 'აბზიანიძის', 'აბო ტბილელის', + 'აბოვიანის', 'აბუსერიძე-ტბელის', 'აგარის', 'აგლაძე რაფიელის', + 'ადიგენის', 'ავთანდილის', 'ავლაბრის', 'ავლევის', 'ათონელის', 'აკეთის', + 'აკოფიანის', 'აკურის', 'ალადაშვილის', 'ალაზნის', 'ალგეთის', + 'ალექსიძე მერაბის', 'ალვანის', 'ალიხანიანის', 'ალმასიანის', 'ამაღლების', + 'ამბროლაურის', 'ამირანაშვილი პეტრეს', 'ამირეჯიბის', 'ანაკლიის', + 'ანანურის', 'ანდრონიკაშვილის', 'ანდღულაძის', 'ანტონ კატალიკოსის', + 'ანტონოვსკაიას', 'ანჯაფარიძე ვერიკოს', 'არაგვის', 'არაგვისპირელი შიოს', + 'არალეთის', 'არარატის', 'არაყიშვილი დიმიტრის', 'არბოს', 'არბოშიკის', + 'არგვეთის', 'არდაზიანის', 'არდონის', 'არეშიძის', 'არველაძის', + 'ართვინის', 'არმაზის', 'არსენალის', 'ასათიანი ლადოს', 'ასკანის', + 'ასურეთის', 'ასხინის', 'ატენის', 'აფანასიევის', 'აფხაზეთის', 'აწყურის', + 'აჭარის', 'ახალარსენალის', 'ახალდაბის', 'ახალუბნის', 'ახალქალაქის', + 'ახვლედიანი ელენეს', 'ახვლედიანი გიორგის', 'ახვლედიანის', 'ახმეტელის', + 'ახმეტის', 'ახოსპირელის', 'ახტალის', 'ახუთის', 'ახუნდოვის', 'აჯამეთის', + 'ბააზოვის', 'ბაგინეთის', 'ბადიაურის', 'ბაზალეთის', 'ბათუმის', + 'ბაკურიანის', 'ბაკურციხის', 'ბალადინის', 'ბალანჩივაძე მელიტონის', + 'ბარათაშვილი ნოკოლოზის', 'ბარათაშვილის', 'ბარალეთის', + 'ბარამიძე ალექსანდრეს', 'ბარისახოს', 'ბარნოვის', 'ბაქოს', + 'ბაქრაძე დავითის', 'ბაქრაძე დიმიტრის', 'ბაღდათის', 'ბაღნარის', + 'ბახმაროს', 'ბახტრიონის', 'ბედიის', 'ბევრეთის', 'ბეთანიის', 'ბეთლემის', + 'ბელიაშვილი აკაკის', 'ბენაშვილის', 'ბენდელიანი ჭიჭიკოს', + 'ბეჟანიშვილი ეკას', 'ბერბუქის', 'ბერიაშვილის', 'ბერიკაშვილის', + 'ბერიტაშვილის', 'ბერიძე ვუკოლის', 'ბერძენიშვილის', 'ბესიკის', + 'ბექა ოპიზარის', 'ბეღლეთის', 'ბზიფის', 'ბიჭვინთის', 'ბოგვის', 'ბოდავის', + 'ბოდბის', 'ბოლნისის', 'ბორბალოს', 'ბოროდინოს', 'მ. ლებანიძის', + 'ბოტანიკურის', 'ბოცვაძის', 'ბოჭორიშვილის', 'ბოჭორმის', 'ბჟოლეთის', + 'ბროლოსანის', 'ბროსეს', 'ბუაჩიძე თენგიზის', 'ბუდაპეშტის', 'ბულაჩაურის', + 'ბურკიაშვილის', 'ბურძგლას', 'ბუღეულის', 'ბუხაიძის', + 'გაბაშვილი ეკატერინეს', 'გაგარინი იურის', 'გალავნის', + 'გალაქტიონ ტაბიძის', 'გალის', 'გამრეკელის', 'გამყრელიძის', + 'გამცემლიძე შოთას', 'განთიადის', 'გარე კახეთის', 'გარეჯელი დავითის', + 'გარიყული მარიამის', 'გაფრინდაულის', 'გახოკიძე აკაკის', 'გახოკიძის', + 'გეგუთის', 'გედევანიშვილის', 'გეზათის', 'გელათის', 'გერგეტის', + 'გვაზაურის', 'გვეტაძე რაჟდენის', 'გივიშვილის', 'გიორგაძის', + 'გიორგი ბრწყინვალის', 'გიორგი მერჩულეს', 'გლინკას', 'გოგაშენის', + 'გოგებაშვილის იაკობის', 'გოგიბერიძის', 'გოგოლაურის', 'გოგოლის', + 'გოგჩის', 'გოთუას', 'გოკიელის', 'გომარეთის', 'გომბორის', 'გომის', + 'გონაშვილი ჰამლეტის', 'გორგასლის', 'გორდის', 'გორის', 'გორკის', + 'გოცირიძის', 'გოძიაშვილის', 'გრანელი ტერენტის', 'გრიბოედოვის', + 'გრიშაშვილის', 'გროზნოს', 'გრუზინსკი პეტრეს', 'გუდამაყრის', 'გუდარეხის', + 'გუდარის', 'გუდაუთის', 'გუდიაშვილი ლადოს', 'გუთნის', 'გულიას', + 'გულისაშვილის', 'გულუა გიას', 'გუმათის', 'გუმათჰესის', 'გუმბრის', + 'გუნიას', 'გურგენიძის', 'გურიელის', 'გურიის', 'გურჯაანის', 'დაბახანას', + 'დადიანი შალვას', 'დადიანი ცოტნეს', 'დაისის', 'ლ. ელიავას', 'დარკვეთის', + 'დგებუაძის', 'დედოფლისწყაროს', 'დეკაბრისტების', 'დელისის', 'დეპოს', + 'დვალის', 'დვირის', 'დიდგორის', 'დიდხევის', 'დიდი ხეივნის', + 'დიდი ჯიხაიშის', 'დ. ყიფიანის', 'დიმიტრი თავდადებულის', 'დირსიჭალას', + 'დიუმა ალექსანდრეს', 'დმანისის', 'დობროლიუბოვის', 'დოდაშვილი სოლომონის', + 'დოესის', 'დოლიძე გოგის', 'დოლიძის', 'დოქის', 'დოღუმბარის', + 'დუტუ მეგრელის', 'დუშეთის', 'ედისის', 'ევდოშვილის', 'ეკალაძის', + 'ელდარის', 'ენგურის', 'ენგურჰესის', 'ენისელის', 'ენუქიძის', 'ერევნის', + 'ერისთავი თორნიკეს', 'ერისთავი კონსტანტინეს', 'ერისთავ-ხოშტარიას', + 'ერწოს', 'ესენინის', 'სანდრო ეულის', 'ეფრემ მცირის', 'ექიმის', + 'ვაზიანის', 'ვაზისუბნის', 'ვაკელი იონას', 'ვანის', 'ვარდევანის', + 'ვარდისუბნის', 'ვართაგავას', 'რომის', 'ვასაძის', 'ვაშლოვანის', + 'ვახტანგ VI–ის', 'ვეზიროვის', 'ვეკუა ვოვას', 'ვერცხლის', 'ვერჰარნის', + 'ვეძათხევის', 'ვეძინის', 'ვირსალაძის', 'ვორონინის', 'საარბრჯუკენის', + 'ზაზიშვილი გიგოს', 'ზალდასტანიშვილის', 'ზანდუკელი მიხეილის', 'ზარზმის', + 'ზაქარიაძე სერგოს', 'ზედაზნის', 'ზედამზის', 'ზედაუბნის', 'ზეინკლის', + 'ზეკარის', 'ზემო ვაკის', 'ზემო ვეძისის', 'ზესტაფონის', 'ზვარეთის', + 'ზიარის', 'ზიგზაგის', 'ზინდისის', 'ზიჩი მიხაის', 'ზოვრეთის', + 'ზუბალაშვილების', 'ზუგდიდის', 'ზურაბიშვილი ავლიპის', + 'თაბუკაშვილი რეზოს', 'თავაძე ფერდინანდის', 'თამარაშენის', + 'თამარაშვილი მიხეილის', 'გ. სვანიძის', 'თარხნიშვილის', 'თაქთაქიშვილის', + 'თაყაიშვილი სესილიას', 'თევდორე მღვდლის', 'თეთნულდის', 'თეთრიწყაროს', + 'თეკლათის', 'თელავის', 'ხახანაშვილის', 'თელეთის', 'თერგის', 'თეძმის', + 'თვალჭრელიძის', 'თიანეთის', 'თმოგველის', 'თმოგვის', 'თოდრიას', 'თოიძის', + 'თონეს', 'თორაძის', 'თოფურიას', 'თრიალეთის', 'თუმანიანის', 'თხინვალის', + 'იალბუზის', 'იამანიძე შოთას', 'იაშვილი პაოლოს', 'იბრაჰიმ ისპაჰანელის', + 'იდუმალას', 'იეთიმ გურჯის', 'იერუსალიმის', 'ივერიის', 'ივლეთის', + 'იზაშვილის', 'ილორის', 'ილურიძე კონსტანტინეს', 'იმედაშვილი გაიოზის', + 'იმერეთის', 'ინანიშვილი რამაზის', 'ინაშვილის', 'ინგოროყვა პავლეს', + 'ინტერნატის', 'იორის', 'იოსებიძის', 'იოსელიანის', 'იპოლიტე-ივანოვის', + 'ირბაქი ნიკიფორეს', 'ირგვლივის', 'ისაკიანის', 'ისნის', 'იფნის', + 'იყალთოს', 'კავთისხევის', 'კავსაძის', 'კაიშაურის', + 'კაკაბაძე პოლიკარპეს', 'კაკაბაძეების', 'კაკლიანის', 'კოტე ხიმშიაშვილის', + 'კალატოზის', 'კალიუჟნის', 'კალოუბნის', 'კანდელაკის', 'კანდელაკის', + 'კანკავას', 'კაპანაძის', 'კარალეთის', 'კარგარეთელის', 'კასპის', + 'კაჭრეთის', 'კახიანის', 'კედია სპირიდონის', 'კეკელიძე კორნელის', + 'კელაპტრიშვილი ომარის', 'კერესელიძე არჩილის', 'კერესელიძის', + 'კეცხოველი ნიკოს', 'კვალეთის', 'კვალის', 'კვანტალიანის', 'კვერნაულის', + 'კვესეთის', 'კიევის', 'კიკეთის', 'კიკვიძის', 'კისისხევის', 'კიშინიოვის', + 'კლდეკარის', 'კლდიაშვილის', 'კნოლევის', 'კობახიძის', 'კობერიძის', + 'კოდალოს', 'კოდორის', 'კოკინაკის', 'კოლმეურნეობის ველის', 'კოლხეთის', + 'კომუნის', 'კონდოლის', 'კონსტიტუციის', 'კოფცოვის', 'კოსტავას', + 'კოტეტიშვილი ვახტანგის', 'კოშკოვანის', 'კოხრეიძის', 'კოჯრის', + 'ჯ. კახიძის', 'კრწანისის', 'კუმისის', 'კუპრაძის', 'კურნატოვსკის', + 'კურსების', 'კურსკის', 'კუფტინის', 'ლაგოდეხის', 'ლაზოს', 'ლაითურის', + 'ლაილაშის', 'ლალიონის', 'ლამის', 'ლამისყანის', 'ლანჩხუთის', 'ლარეხის', + 'ლარსის', 'ლაღიძე მიტროფანეს', 'ლაღიძე რევაზის', 'ლებარდეს', + 'ლეკიშვილის', 'ლენტეხის', 'ლეონიძე გიორგის', 'ლეჟავას', 'ლერმონტოვის', + 'ლერწმის', 'ლესელიძის', 'ლესია უკრაინკას', 'ლეჩხუმის', 'ლიახვის', + 'ლიბანის', 'ლიკანის', 'ლისაშვილის', 'ლიუბოვსკის', 'ლიხაურის', 'ლიხის', + 'ლომაურის', 'ლომთათიძის', 'ლომონოსოვის', 'ლორთქიფანიძე გრიგოლის', + 'ლორთქიფანიძის', 'ლოჭინის', 'ლუბლიანას', 'ლუსიანინის', 'მაზნიაშვილის', + 'მათიაშვილის', 'მაიაკოვსკის', 'მამასახლისოვის', 'მამკოდის', 'მამკოდის', + 'მამრაძის', 'მანაგაძე ალეხსანდეს', 'მანავის', 'მანგლისის', + 'მანიჯაშვილი კახას', 'მანჯგალაძე ეროსის', 'მარაბდის', + 'მარგიანი რევაზის', 'მარელისის', 'მარი ნიკოს', 'მარიჯანის', 'მარტვილის', + 'მარტყოფის', 'მარუაშვილი გიორგის', 'მარუხის გმირების', + 'მარჯანიშვილი კოტეს', 'მარჯანიშვილი კოტეს', 'მაღალაშვილის', 'მაღაროს', + 'მაჩაბელი ივანეს', 'მაჩხაანის', 'მაცესტის', 'მაჭრის', 'მახათას', + 'მახინჯაურის', 'მგალობლიშვილის', 'მებაღიშვილის', 'მეგობრობის', + 'მეგრელაძის', 'მეველეს', 'მელაანის', 'მელიქიშვილის', 'მესხეთის', + 'მესხიას', 'მესხიშვილი ალექსის', 'მესხიშვილის', 'მეტეხის', 'მეუნარგიას', + 'მექანიზაციის', 'მეჯვრისხევის', 'მთავარანგელოზის', 'მთაწმინდის', + 'მთისძირის', 'მიმინოშვილი რომანის', 'მინდელაურის', 'მინდელის', + 'მირზა მეფის', 'მირზაანის', 'მიროტაძის', 'მიტინგის', 'მიქატაძის', + 'მიქატაძის', 'მიქელაძე ევგენის', 'მიქელაძის', 'მიშველაძე არჩილის', + 'მიჩურინის', 'მიცკევიჩის', 'მნათობის', 'მოლითის', 'მოლოკოვის', + 'მორეტის', 'მოსაშვილის', 'მოსე ხონელის', 'მოსიძე ვახტანგის', + 'მოსტკოვის', 'მოსულიშვილის', 'მრევლიშვილის', 'მტკვრის', 'მუკუზანის', + 'მუსხელიშვილის', 'მუხაძის', 'მუხაძის', 'მუხრანის', 'მშველიძის', + 'მცხეთის', 'ნაბახტაურის', 'ნაგომარის', 'ნადიკვარის', 'ნადირაძე კოლაუს', + 'ნავთლუღის', 'ნათაძის', 'ნაკადულის', 'ნიშნიანიძის', + 'ნანეიშვილი ვიქტორის', 'ნანეიშვილი ვლადიმერის', 'ნარგიზის', + 'ნასაკირალის', 'ნასიძე სულხანის', 'ნაქალაქევის', 'ნაქერალას', 'ნიაბის', + 'ნიაღვრის', 'ნიზამის', 'ნიკოლაძე ნიკოს', 'ნინიძის', 'ნიორაძის', + 'ნოვოროსისკის', 'ნონეშვილი იოსების', 'ნოსირის', 'ნოსტეს', 'ნუცუბიძის', + 'ობსერვატორიის', 'ოდესის', 'ონიაშვილის', 'ონის', 'ოჟიოს', 'ორბეთის', + 'ორბელების', 'ორთაჭალის', 'ორპირის', 'ორხევის', 'ოსეთის', 'ოსიაურის', + 'ოფრეთის', 'ოქრომჭედლების', 'ოქროყანის', 'ოჩამჩირის', 'ოცხელების', + 'ოძელაშვილის', 'ოძისის', 'პაიჭაძის', 'პალიასტომის', 'პანკისის', + 'პასტერის', 'პატარიძის', 'პატარძეულის', 'პეტეფი შანდორის', + 'პეტრე იბერის', 'პეტრიაშვილის', 'პეტრიწის', 'პიატიგორსკის', 'პიონერის', + 'პისარევის', 'პლატონის', 'პუშკინი ალექსანდრეს', 'ჟველაურის', 'ჟინვალის', + 'ჟონეთის', 'ჟორესის', 'ჟღენტის', 'რადიანი შალვას', 'რაზიკაშვილის', + 'რაზმაძის', 'რატევანის', 'რატილის', 'რაჭის', 'რევოლუცის', 'რთველაძის', + 'რიონის', 'რიონჰესის', 'რიწის', 'რკინიგზის', 'რკინის', 'როდენის', + 'როსტოვის', 'როსტომაშვილის', 'რუისპირის', 'რუსთაველის', 'რჩეულიშვილის', + 'საადის', 'სააკაძე პაატას', 'სააკაძის', 'საბადურის', 'საბანისძის', + 'საბაშვილის', 'საგარეჯოს', 'საგურამოს', 'სადმელის', 'სავანელის', + 'სათემოს', 'საიათნოვას', 'საირმის', 'სალამის', 'სალხინოს', + 'სამამულო ომის გმირების', 'სამგორის', 'სამტრედიის', 'სამურზაყანოს', + 'სამურის', 'სამღებროს', 'სამღერეთის', 'სამშვილდეს', 'სანავარდოს', + 'სანკტ-პეტერბურგის', 'სარაჯიშვილი დავითის', 'სარაჯიშვილი პეტრეს', + 'სართანიას', 'სართიჭალის', 'სარკინეთის', 'საქანელას', 'საქარის', + 'საყვირის', 'საჩხერის', 'საცხენისის', 'საჭილაოს', 'სახოკიას', 'სევანის', + 'სენაკის', 'სვანეთის', 'გუდაურის', 'სვირის', 'სიონის', 'სიღნაღის', + 'სიხარულიძის', 'სკოლის', 'სომხეთის', 'სოხუმის', 'სოღანლუღის', + 'სპანდარიანის', 'სპარტაკის', 'სტამბის', 'სტანისლავსკის', 'სტურუას', + 'სუვოროვის', 'სულიაშვილის', 'სულხანიშვილის', 'სულხან-საბას', + 'სუმბატაშვილ-იუჟინსკის', 'სუნდუკიანის', 'სურამის', 'სურგულაძის', + 'სხვიტორის', 'სხირტლაძის', 'სხულუხიას', 'ტაბახმელას', 'ტაბიძე ტიციანის', + 'ტანძიის', 'ტარიელის', 'ტატიშვილი ერეკლეს', 'ტატიშვილის', 'ტაშირის', + 'ტაშკენტის', 'ტელეგრაფის', 'ტეტელაშვილის', 'ტეხურის', 'ტვიშის', + 'ტიბაანის', 'ტირიფონის', 'ტიულენევის', 'ტიხონოვის', 'ტოლენჯის', + 'ტოლსტოის', 'ტოლსტონოგოვის', 'ტრანსპორტის', 'ტრაქტორის', 'ტრიკოტაჟის', + 'ტურგენევის', 'ტუსკიას', 'ტყავის', 'ტყეკულტურის', 'ტყვარჩელის', + 'ტყვიავის', 'ტყიბულის', 'ტყის', 'უბილავას', 'უზნაძე დიმიტრის', + 'უზნაძის', 'უიარაღოს', 'უკლება კირილეს', 'უმიკაშვილის', 'უნივერსიტეტის', + 'ურბნისის', 'ურეკის', 'ურიდიას', 'ურიცკის', 'უფლისციხის', 'უშაკოვის', + 'უჩანეიშვილი ირაკლის', 'უწერის', 'უჯარმის', 'ფაბრიკის', 'ფალიაშვილის', + 'ფანასკერტელ-ციციშვილის', 'ფანჯიკიძის', 'ფარავნის', 'ფასანაურის', + 'ფაღავა ირაკლის', 'ფერისცვალების', 'ფიზკულტურის', 'ფილიას', 'ფირდოუსის', + 'ფიროსმანის', 'ფიფიას', 'ფოთის', 'ფოსტის', 'ფოცხვერაშვილის', + 'ფოცხიაშვილი მორისის', 'ფურცელაძის', 'ფშავის', 'ქავთარაძის', 'ქარელის', + 'ქართველიშვილი ლევანის', 'ქართლის', 'ქებურიას', 'ქედის', 'ქერჩის', + 'ქვალონის', 'ქვიშხეთის', 'ქიაჩელის', 'ქიზიყის', 'ქინქლაძე ოთარის', + 'ქინძმარაულის', 'ქიქოძე გერონტის', 'ქობულაძის', 'ქობულეთის', 'ქსნის', + 'ქსოვრელის', 'ქუთათელაძის', 'ქუთათელაძე აპოლონის', 'ქუთაისის', + 'ქუმსიაშვილის', 'ქურდიანი არჩილის', 'ქურდიანი ზაქარიას', 'ქურხულის', + 'ქუჩიშვილის', 'ღამბაშიძის', 'ღრმაღელეს', 'ღუდუშაური ოთარის', + 'ყავლაშვილი შოთას', 'ყარყარაშვილის', 'ყვარელის', 'ყირიმის', 'ყიფიანის', + 'ყიფშიძის', 'ყუშიტაშვილის', 'შავგულიძის', 'შავთელის', 'შავი ზღვის', + 'შავიშვილის', 'შავნაბადას', 'შავსოფელის', 'შანიძე აკაკის', + 'შანშიაშვილის', 'შარაშიძის', 'შარდენის', 'შარტავა ჟიულის', + 'შატბერაშვილის', 'შატილის', 'შაქრიანის', 'შევჩენკო ტარასის', + 'შენგელაიას', 'შერვაშიძის', 'შილდის', 'შინდისის', 'შიო მღვიმელის', + 'შირაქის', 'შოვის', 'შორაპნის', 'შროშის', 'შუამთის', 'შურდულის', + 'შხეფის', 'ჩაიკოვსკის', 'ჩაილურის', 'ჩაისუბნის', 'ჩანჩიბაძის', + 'ჩარგლის', 'ჩარხის', 'ჩაქვის', 'ჩაჩავას', 'ჩახრუხაძის', 'ჩერნიშევსკის', + 'ჩერქეზიშვილის', 'ჩეჩელაშვილის', 'ჩეხოვის', 'ჩიკვანიას', 'ჩიტაიას', + 'ჩიტაძის', 'ჩიქობავა არნოლდის', 'ჩიქოვანის', 'ჩკალოვის', + 'ჩოლოყაშვილი ქაიხოსროს', 'ჩოჩუას', 'ჩოხატაურის', 'ჩოხელის', + 'ჩუბინაშვილი გიორგის', 'ჩუბინიძის', 'ჩხიკვაძის', 'ცაბაძე გიორგის', + 'ცაგარელი არჩილის', 'ცაგერის', 'ცაიშის', 'ცემის', 'ციმაკურიძის', + 'ცინცაძე კალისტრატეს', 'ცისარტკელას', 'ცისკრის', 'ციხისძირის', + 'ცოდნისკარის', 'ცურტაველი იაკობის', 'ცუცქირიძის', 'ცხემის', 'ცხვედაძის', + 'ცხრა აპრილის', 'ცხრა ძმის', 'ძეგამის', 'ძევერის', 'ძმობის', + 'ძოწენიძის', 'წავკისის', 'წალენჯიხის', 'წალკის', 'წაღვერის', 'წერეთლის', + 'წერნაკის', 'წერონისის', 'წიკლაურის', 'წინამძღვრიშვილის', + 'წინამძღვრიშვილის', 'წინანაურის', 'წინანდლის', 'წინაუბნის', + 'წიწამურის', 'წმ. ნიკოლოზის', 'წნორისწყლის', 'წრომის', 'წულაძის', + 'წულუკიძის', 'წურწუმიას', 'წუწუნავას', 'წუწხვატის', 'წყალსადენის', + 'წყალტუბოს', 'წყაროს', 'ჭაბუკიანი ვახტანგის', 'ჭავჭავაძე ზურაბის', + 'ჭავჭავაძე ალექსანდრეს', 'ჭალადიდის', 'ჭანტურია გიას', 'ჭიათურის', + 'ჭიაურელი მიხეილის', 'ჭიჭინაძე ზაქარიას', 'ჭოველიძე თამარის', + 'ჭონქაძე დანიელის', 'ჭოპორტის', 'ჭოროხის', 'ჭრებალოს', 'ჭრელაშვილის', + 'ხაბეიშვილის', 'ხაზინის', 'ხანძთელი გრიგოლის', 'ხარაბაძის', + 'ხარაგაულის', 'ხარფუხის', 'ხაჩატურიანის', 'ხევის', 'ხევისუბნის', + 'ხევსურეთის', 'ხევძმარის', 'ხეთაგუროვის', 'ხერგიანის', 'ხერთვისის', + 'ხერხეულიძეების', 'ხეჩუაშვილის', 'ხვამლის', 'ხვანჭკარის', 'ხვედელიანის', + 'ხვინგიას', 'ხვიჩია იპოლიტეს', 'ხიდის', 'ხიდისთავის', 'ხივინის', + 'ხიმშიაშვილის', 'ხმელნიცკის', 'ხოდაშენის', 'ხომლელის', 'ხონის', + 'ხორავა აკაკის', 'ხორნაბუჯის', 'ხოშარაულის', 'ხრამჰესის', 'ხრესილის', + 'ხუდადოვის', 'ჯაბაურის', 'ჯაბიძის', 'ჯავახეთის', 'ჯავახიშვილი ივანეს', + 'ჯავახიშვილი მიხეილის', 'ჯავის', 'ჯამბულის', 'ჯანაშვილის', 'ჯანაშიას', + 'ჯანჯღავას', 'ჯვარედინის', 'პოლიტკოვსკაიას', 'ჯიქიას', 'ჯორბენაძის', + 'ჯორჯაძის', 'ჰოსპიტალის', + ) + + # Source: List of cities and towns in Georgia (Wikipedia) + # https://en.wikipedia.org/wiki/List_of_cities_and_towns_in_Georgia_(country) + city_names = ( + 'აბაშა', 'ამბროლაური', 'ახალი ათონი', 'ახალქალაქი', 'ახალციხე', + 'ახმეტა', 'ბათუმი', 'ბაღდათი', 'ბოლნისი', 'ბორჯომი', 'გაგრა', 'გალი', + 'გარდაბანი', 'გორი', 'გუდაუთა', 'გურჯაანი', 'დედოფლისწყარო', 'დმანისი', + 'დუშეთი', 'ვალე', 'ვანი', 'ზესტაფონი', 'ზუგდიდი', 'თბილისი', + 'თეთრიწყარო', 'თელავი', 'თერჯოლა', 'კასპი', 'ლაგოდეხი', 'ლანჩხუთი', + 'მარნეული', 'მარტვილი', 'მცხეთა', 'ნინოწმინდა', 'ოზურგეთი', 'ონი', + 'ოჩამჩირე', 'რუსთავი', 'საგარეჯო', 'სამტრედია', 'საჩხერე', 'სენაკი', + 'სიღნაღი', 'სოხუმი', 'ტყვარჩელი', 'ტყიბული', 'ფოთი', 'ქარელი', + 'ქობულეთი', 'ქუთაისი', 'ყვარელი', 'ცაგერი', 'ცხინვალი', 'წალენჯიხა', + 'წალკა', 'წნორი', 'წყალტუბო', 'ჭიათურა', 'ხაშური', 'ხობი', 'ხონი', + 'ჯვარი', + ) + + def street_title(self): + return self.random_element(self.street_titles) + + def city_name(self): + return self.random_element(self.city_names) diff --git a/testbed/joke2k__faker/faker/providers/address/ko_KR/__init__.py b/testbed/joke2k__faker/faker/providers/address/ko_KR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cafde5a02ffd869422d48b4bad4ec9600f98c6d8 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/ko_KR/__init__.py @@ -0,0 +1,392 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + """ + Korean Address Provider + ======================= + + Korea has two address and postal code system. + + Address + ------- + + - Address based on land parcel numbers + (지번 주소, OLD, but someone use consistently) + - Address based on road names and building numbers (도로명 주소, NEW) + + :meth:`land_address` generate Address based on land parcel numbers and + :meth:`road_address` generate Address based on road names and building + numbers. + + Postal code + ----------- + + - Old postal code (6-digit, OLD and dead) + - New postal code (5-digit, New) + + :meth:`old_postal_code` and :meth:`postcode` generate old 6-digit code + and :meth:`postal_code` generate newer 5-digit code. + + Reference + --------- + + - `Official Confirmation Prividing that Old and New Addresses are Identical`__ + (warn: cert error) + + __ https://www.juso.go.kr/addridentity/AddrIdentityHelp.htm + + """ + + building_suffixes = ( + '빌라', + '아파트', + '연립', + '마을', + '타운', + '타워', + ) + road_suffixes = ('로', '길', '거리', '가') + town_suffixes = ('동', '리', '마을') + postcode_formats = ('###-###',) + new_postal_code_formats = ('#####',) + metropolitan_cities = ( + '서울특별시', + '부산광역시', + '대구광역시', + '인천광역시', + '광주광역시', + '대전광역시', + '울산광역시', + '세종특별자치시', + ) + provinces = ( + '경기도', + '강원도', + '충청북도', + '충청남도', + '전라북도', + '전라남도', + '경상북도', + '경상남도', + '제주특별자치도', + ) + cities = ( + '파주시', + '수원시', + '수원시 권선구', + '수원시 팔달구', + '수원시 영통구', + '성남시', + '성남시 수정구', + '성남시 중원구', + '화성시', + '성남시 분당구', + '안양시', + '안양시 만안구', + '안양시 동안구', + '부천시', + '부천시 원미구', + '부천시 소사구', + '부천시 오정구', + '광명시', + '평택시', + '이천시', + '동두천시', + '안산시', + '안산시 상록구', + '안산시 단원구', + '안성시', + '고양시', + '고양시 덕양구', + '고양시 일산동구', + '고양시 일산서구', + '과천시', + '구리시', + '남양주시', + '오산시', + '시흥시', + '군포시', + '의왕시', + '하남시', + '김포시', + '용인시', + '용인시 처인구', + '용인시 기흥구', + '용인시 수지구', + '연천군', + '가평군', + '양평군', + '광주시', + '포천시', + '양주시', + '수원시 장안구', + '의정부시', + '여주시', + ) + road_names = ( + '압구정', + '도산대', + '학동', + '봉은사', + '테헤란', + '역삼', + '논현', + '언주', + '강남대', + '양재천', + '삼성', + '영동대', + '개포', + '선릉', + '반포대', + '서초중앙', + '서초대', + '잠실', + '석촌호수', + '백제고분', + '가락', + '오금', + ) + boroughs = ( + '종로구', + '중구', + '용산구', + '성동구', + '광진구', + '동대문구', + '중랑구', + '성북구', + '강북구', + '도봉구', + '노원구', + '은평구', + '서대문구', + '마포구', + '양천구', + '강서구', + '구로구', + '금천구', + '영등포구', + '동작구', + '관악구', + '서초구', + '강남구', + '송파구', + '강동구', + '동구', + '서구', + '남구', + '북구', + ) + countries = ('가나', '가봉', '가이아나', '감비아', '과테말라', '그레나다', '그리스', '기니', '기니비사우', + '나미비아', '나우루', '나이지리아', '남수단', '남아프리카 공화국', '네덜란드 왕국', '네팔', + '노르웨이', '뉴질랜드', '니제르', '니카라과', '대한민국', '덴마크', '도미니카 공화국', + '도미니카 연방', '독일', '동티모르', '라오스', '라이베리아', '라트비아', '러시아', '레바논', + '레소토', '루마니아', '룩셈부르크', '르완다', '리비아', '리투아니아', '리히텐슈타인', + '마다가스카르', '마셜 제도', '마케도니아 공화국', '말라위', '말레이시아', '말리', '멕시코', + '모나코', '모로코', '모리셔스', '모리타니', '모잠비크', '몬테네그로', '몰도바', '몰디브', + '몰타', '몽골', '미국', '미얀마', '미크로네시아 연방', '바누아투', '바레인', '바베이도스', + '바하마', '방글라데시', '베냉', '베네수엘라', '베트남', '벨기에', '벨라루스', '벨리즈', + '보스니아 헤르체고비나', '보츠와나', '볼리비아', '부룬디', '부르키나파소', '부탄', '불가리아', + '브라질', '브루나이', '사모아', '사우디아라비아', '산마리노', '상투메 프린시페', '세네갈', + '세르비아', '세이셸', '세인트루시아', '세인트빈센트 그레나딘', '세인트키츠 네비스', + '소말리아', '솔로몬 제도', '수단', '수리남', '스리랑카', '스와질란드', '스웨덴', '스위스', + '스페인', '슬로바키아', '슬로베니아', '시리아', '시에라리온 공화국', '싱가포르', + '아랍에미리트', '아르메니아', '아르헨티나', '아이슬란드', '아이티', '아일랜드', + '아제르바이잔', '아프가니스탄', '안도라', '알바니아', '알제리', '앙골라', '앤티가 바부다', + '에리트레아', '에스토니아', '에콰도르', '에티오피아', '엘살바도르', '영국', '예멘', '오만', + '오스트레일리아', '오스트리아', '온두라스', '요르단', '우간다', '우루과이', '우즈베키스탄', + '우크라이나', '이라크', '이란', '이스라엘', '이집트', '이탈리아', '인도네시아', '일본', + '자메이카', '잠비아', '적도 기니', '조선민주주의인민공화국', '조지아', '중앙아프리카 공화국', + '중화인민공화국', '지부티', '짐바브웨', '차드', '체코', '칠레', '카메룬', '카보베르데', + '카자흐스탄', '카타르', '캄보디아', '캐나다', '케냐', '코모로', '코스타리카', '코트디부아르', + '콜롬비아', '콩고 공화국', '콩고 민주 공화국', '쿠바', '쿠웨이트', '크로아티아', + '키르기스스탄', '키리바시', '키프로스', '타이', '타지키스탄', '탄자니아', '터키', + '토고', '통가', '투르크메니스탄', '투발루', '튀니지', '트리니다드 토바고', '파나마', + '파라과이', '파키스탄', '파푸아 뉴기니', '팔라우', '페루', '포르투갈', '폴란드', '프랑스', + '피지', '핀란드', '필리핀', '헝가리', + ) + building_dongs = ( + '가', + '나', + '다', + '라', + '마', + '바', + '##', + '###', + ) + land_numbers = ( + '###', + '###-#', + '###-##', + ) + road_numbers = ( + '#', + '##', + '###', + ) + + town_formats = ( + '{{first_name}}{{last_name}}{{town_suffix}}', + '{{first_name}}{{last_name}}{{last_name}}{{town_suffix}}', + ) + building_name_formats = ( + '{{first_name}}{{last_name}}{{building_suffix}}', + '{{first_name}}{{last_name}}{{last_name}}{{building_suffix}}', + ) + address_detail_formats = ( + '{{building_name}}', + '{{building_name}} ###호', + '{{building_name}} {{building_dong}}동 ###호', + ) + road_formats = ( + '{{road_name}}{{road_suffix}}', + '{{road_name}}{{road_number}}{{road_suffix}}', + ) + road_address_formats = ( + '{{metropolitan_city}} {{borough}} {{road}}', + '{{province}} {{city}} {{road}}', + '{{metropolitan_city}} {{borough}} {{road}} ({{town}})', + '{{province}} {{city}} {{road}} ({{town}})', + ) + land_address_formats = ( + '{{metropolitan_city}} {{borough}} {{town}} {{land_number}}', + '{{province}} {{city}} {{town}} {{land_number}}', + ) + + # Keep backward compatibility + city_suffixes = ('시',) + street_suffixes = road_suffixes + street_name_formats = ('{{road_name}}',) + street_address_formats = road_address_formats + address_formats = road_address_formats + + def land_number(self): + """ + :example 507 + """ + return self.bothify(self.random_element(self.land_numbers)) + + def land_address(self): + """ + :example 세종특별자치시 어진동 507 + """ + pattern = self.random_element(self.land_address_formats) + return self.generator.parse(pattern) + + def road_number(self): + """ + :example 24 + """ + return self.bothify(self.random_element(self.road_numbers)) + + def road_address(self): + """ + :example 세종특별자치시 도움5로 19 (어진동) + """ + pattern = self.random_element(self.road_address_formats) + return self.generator.parse(pattern) + + def address_detail(self): + """ + :example 가나아파트 가동 102호 + """ + pattern = self.bothify(self.random_element( + self.address_detail_formats)) + return self.generator.parse(pattern) + + def road(self): + """ + :example 도움5로 + """ + pattern = self.random_element(self.road_formats) + return self.generator.parse(pattern) + + def road_name(self): + """ + :example 압구정 + """ + return self.random_element(self.road_names) + + def road_suffix(self): + """ + :example 길 + """ + return self.random_element(self.road_suffixes) + + def metropolitan_city(self): + """ + :example 서울특별시 + """ + return self.random_element(self.metropolitan_cities) + + def province(self): + """ + :example 경기도 + """ + return self.random_element(self.provinces) + + def city(self): + """ + :example 고양시 + """ + pattern = self.random_element(self.cities) + return self.generator.parse(pattern) + + def borough(self): + """ + :example 중구 + """ + return self.random_element(self.boroughs) + + def town(self): + """ + :example 가나동 + """ + pattern = self.random_element(self.town_formats) + return self.generator.parse(pattern) + + def town_suffix(self): + """ + :example 동 + """ + return self.random_element(self.town_suffixes) + + def building_name(self): + """ + :example 김구아파트 + """ + pattern = self.random_element(self.building_name_formats) + return self.generator.parse(pattern) + + def building_suffix(self): + """ + :example 아파트 + """ + return self.random_element(self.building_suffixes) + + def building_dong(self): + """ + :example 가 + """ + return self.bothify(self.random_element(self.building_dongs)) + + def old_postal_code(self): + """ + :example 123-456 + """ + return self.bothify(self.random_element(self.postcode_formats)) + + def postcode(self): + """ + :example 12345 + """ + return self.bothify(self.random_element(self.new_postal_code_formats)) + + def postal_code(self): + """ + :example 12345 + """ + return self.postcode() diff --git a/testbed/joke2k__faker/faker/providers/address/ne_NP/__init__.py b/testbed/joke2k__faker/faker/providers/address/ne_NP/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..acff4d35134a2b25dc213926a13cc5318682e00a --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/ne_NP/__init__.py @@ -0,0 +1,599 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + building_number_formats = ('#', '##', '###') + street_name_formats = ('{{last_name}} {{street_suffix}}',) + street_address_formats = ('{{street_name}}',) + city_formats = ('{{city}}',) + # http://www.nepalpost.gov.np/index.php/postal-codes-of-nepal + postcode_formats = ('#####',) + + address_formats = ( + "{{street_name}} {{building_prefix}} {{building_number}} \n{{city}}\n{{district}} {{postcode}}", + ) + + street_suffixes = ( + 'मार्ग', + 'आश्रम', + 'बाटो', + 'पथ', + 'गल्ली', + 'गेट', + 'हाईट', + 'टार', + 'रोड', + 'कुना', + 'चौर', + 'निवास', + ) + + building_prefixes = ('वडा', 'घर') + # https://en.wikipedia.org/wiki/List_of_sovereign_states + countries = ( + 'अंगोला', + 'अक्रोटिरी र धेकेलिया', + 'अजरबैजान', + 'अफगानिस्तान', + 'अमेरिकी सामोआ', + 'अरुबा', + 'अर्जेन्टिना', + 'अर्मेनिया', + 'अलडेर्नी', + 'अल्जेरिया', + 'अल्बानिया', + 'अस्ट्रिया', + 'अस्ट्रेलिया', + 'आइजल अफ म्यान', + 'आइभोरी कोस्ट', + 'आइसल्याण्ड', + 'आजाद कश्मीर', + 'आयरल्याण्ड', + 'इक्वेटोरियल गिनी', + 'इक्वेडर', + 'इजरायल', + 'इटाली', + 'इण्डोनेशिया', + 'इथियोपिया', + 'इराक', + 'इरान', + 'इस्टोनिया', + 'उज्बेकिस्तान', + 'उत्तर कोरिया', + 'उत्तरी मारिआना टापु', + 'उत्तरी साइप्रस', + 'उरुग्वे', + 'एङगुइला', + 'एण्डोरा', + 'एन्टिगुआ र बर्बुडा', + 'एरिट्रिया', + 'एल साल्भादोर', + 'एशमोर र कर्टियर टापु', + 'ओमान', + 'कजाख्स्तान', + 'कतार', + 'कम्बोडिया', + 'किरिबाटी', + 'किर्गिजस्तान', + 'कुक द्वीप', + 'कुराकाओ', + 'कुवैत', + 'केन्या', + 'केप भर्ड', + 'केम्यान टापु', + 'कोकोस टापु', + 'कोटे डी आइभोरी', + 'कोमोरोस', + 'कोरल सी टापु क्षेत्र', + 'कोलम्बिया', + 'कोसोभो', + 'कोस्टारिका', + 'क्यानडा', + 'क्यामेरून', + 'क्युबा', + 'क्रिसमस टापु', + 'क्रोएसिया', + 'क्लिप्परटन द्वीप', + 'क्वीन माउड ल्याण्ड', + 'गणतन्त्र कङ्गो', + 'गणतन्त्र कोरिया', + 'गणतन्त्र स्पर्स्का', + 'गाबोन', + 'गिनी', + 'गिब्राल्टार', + 'गिलगीत', + 'गुयना', + 'गुर्न्जी', + 'ग्रिनाडा', + 'ग्रीनल्याण्ड', + 'ग्रीस', + 'ग्वाटेमाला', + 'ग्वाम', + 'घाना', + 'चाड', + 'चिली', + 'चीन', + 'चेक गणतन्त्र', + 'जमैका', + 'जर्मनी', + 'जर्सी', + 'जापान', + 'जाम्बिया', + 'जिबुटी', + 'जोर्डन', + 'टर्की', + 'टिमोर', + 'टुभालु', + 'टुर्क्स तथा काइकोस टापु', + 'टोंगा', + 'टोकेलाउ', + 'टोगो', + 'ट्युनिसिया', + 'ट्रान्सनिसट्रिया', + 'ट्रिनिडाड र टोबागो', + 'डेनमार्क', + 'डोमिनिकन गणतन्त्र', + 'डोमिनिका', + 'तन्जानिया', + 'ताइवान', + 'ताजिकिस्तान', + 'तुर्कमेनिस्तान', + 'थाइल्याण्ड', + 'दक्षिण अफ्रिका', + 'दक्षिण ओसेटिया', + 'दक्षिण कोरिया', + 'दक्षिण जर्जिया तथा दक्षिण स्याण्डवीच टापु', + 'दक्षिणी सुडान', + 'नर्वे', + 'नर्वेको', + 'नाइजर', + 'नाइजेरिया', + 'नाउरु', + 'नागोर्नो', + 'नामिबिया', + 'निकाराग्वा', + 'नियु', + 'नेदरल्याण्ड', + 'नेपाल', + 'नोर्फोक टापु', + 'न्यु क्यालोडेनिया', + 'न्युजिल्यान्ड', + 'पपुवा न्युगिनी', + 'पलाउ', + 'पाकिस्तान', + 'पानामा', + 'पाराग्वे', + 'पिटकेर्न टापु', + 'पिटर द्वीप', + 'पूर्वी टिमोर', + 'पेरु', + 'पोर्चुगल', + 'पोल्याण्ड', + 'प्यालेस्टाइन', + 'प्युर्तो रिको', + 'प्रजातान्त्रिक गणतन्त्र कंगो', + 'प्रजातान्त्रिक गणतन्त्र कोरिया', + 'प्रिडेनेस्ट्रोभी', + 'फकल्याण्ड टापु', + 'फरोइ टापु', + 'फिजी', + 'फिनल्याण्ड', + 'फिलिपिन्स', + 'फ्रान्स', + 'फ्रेन्च दक्षिणी र अन्टार्कटिक द्वीप', + 'फ्रेन्च पोलिनेसिया', + 'बंगलादेश', + 'बर्मा', + 'बर्मुडा', + 'बहराइन', + 'बहामस', + 'बार्बाडोस', + 'बुरुन्डी', + 'बुर्किना फासो', + 'बुल्गेरिया', + 'बेनिन', + 'बेलारूस', + 'बेलिज', + 'बेल्जियम', + 'बोत्स्वाना', + 'बोलिभिया', + 'बोस्निया र हर्जगोभिना', + 'बोस्निया र हर्जगोभिना संघ', + 'बौभेट द्वीप', + 'ब्राजिल', + 'ब्रिटिस भर्जिन टापु', + 'ब्रुनेई', + 'भानुअटु', + 'भारत', + 'भियतनाम', + 'भुटान', + 'भेनेजुएला', + 'भ्याटिकन', + 'भ्याटिकन सिटी', + 'मकाउ', + 'मङ्गोलिया', + 'मध्य अफ्रिकी गणतन्त्र', + 'मलावी', + 'मलेशिया', + 'माइक्रोनेसियाको संघीय राज्य', + 'माडागास्कर', + 'मार्शल द्वीप', + 'माली', + 'माल्टा', + 'माल्दिभ्स', + 'मिश्र', + 'मेक्सिको', + 'मोजाम्बिक', + 'मोनाको', + 'मोन्टसेराट', + 'मोन्टेनेग्रो', + 'मोरक्को', + 'मोल्डोभा', + 'मौरिसनिया', + 'मौरिसस', + 'म्यानमार', + 'म्यासेडोनिया', + 'यमन', + 'युक्रेन', + 'युगान्डा', + 'रसिया', + 'रुवाण्डा', + 'रोमानिया', + 'रोस डिपेन्डेन्सी', + 'लक्जेम्बर्ग', + 'लाईबेरिया', + 'लाओस', + 'लात्भिया', + 'लिचटेन्स्टाइन', + 'लिथुआनिया', + 'लिबिया', + 'लेबनान', + 'लेसोथो', + 'वाल्लिस र फुटुना', + 'श्रीलंका', + 'संघीय राज्य माइक्रोनेसिया', + 'संयुक्त अधिराज्य', + 'संयुक्त अरब इमिरेट्स', + 'संयुक्त राज्य अमेरिका', + 'संयुक्त राज्य भर्जिन टापु', + 'सर्बिया', + 'साइप्रस', + 'साउदी अरब', + 'साओ टोमे र प्रिन्सिपे', + 'सान मारिनो', + 'साबा', + 'सामोआ', + 'साहरवी अरब लोकतान्त्रिक गणतन्त्र', + 'सिंगापुर', + 'सिन्ट मार्टिन', + 'सीरियन कुर्दिस्तान', + 'सीरिया', + 'सुडान', + 'सुरिनेम', + 'सेनेगल', + 'सेन्ट किट्स र नेभिस', + 'सेन्ट पियेर्रे र मिकुएलन', + 'सेन्ट बार्थेलेमी', + 'सेन्ट भिन्सेन्ट र ग्रेनाडाइन्स', + 'सेन्ट मार्टिन', + 'सेन्ट लुसिया', + 'सेन्ट हेलेना', + 'सेरा लियोन', + 'सेसेल्स', + 'सोमालिया', + 'सोमालील्याण्ड', + 'सोलोमन द्वीप', + 'स्पेन', + 'स्लोभाकिया', + 'स्लोभेनिया', + 'स्वाजिल्याण्ड', + 'स्विजरल्याण्ड', + 'स्वीडेन', + 'हंगेरी', + 'हङकङ', + 'हर्म', + 'हाइटी', + 'हेयर्ड द्वीप र म्याकडोनाल्ड टापु', + 'होन्डुरस', + 'अबखाजिया', + 'जर्जिया', + ) + + # cities are taken from + # https://en.wikipedia.org/wiki/List_of_cities_in_Nepal + cities = ( + 'मिर्चैया', + 'प्युठान', + 'कञ्चनपुर', + 'लुम्बिनी सांस्कृतिक', + 'बागलुङ', + 'इलाम', + 'भक्तपुर', + 'भद्रपुर', + 'घोराही', + 'स्याङ्जा', + 'खैरहानी नगरपालिका', + 'म्याग्दी', + 'रंगेली', + 'काठमाडौं', + 'शनि-अर्जुन', + 'पर्वत', + 'सप्तरी', + 'पनौती', + 'जयपृथ्वी', + 'लहान', + 'वालिङ', + 'बर्दघाट', + 'डोटी', + 'धरान', + 'पथरी शनिश्चरे', + 'चन्दननाथ', + 'नवलपरासी', + 'किर्तिपुर', + 'दैलेख', + 'सुनसरी', + 'बेलौरी', + 'कुस्मा', + 'मकवानपुर', + 'कञ्चनरूप', + 'गुलरिया', + 'टीकापुर', + 'राजापुर', + 'फिदिम', + 'खोटाङ', + 'धनुषाधाम', + 'झापा', + 'पुनर्वास', + 'भक्तपुर', + 'बर्दिया', + 'बागलुङ', + 'दमक', + 'तेह्रथुम', + 'नारायण', + 'ताप्लेजुङ', + 'तानसेन', + 'पाँचखाल', + 'बनेपा', + 'म्याङ्लुङ', + 'ललितपुर', + 'दिपायल', + 'अपी', + 'दाङ', + 'सन्धिखर्क', + 'धनकुटा', + 'बिरेन्द्रनगर', + 'गौर', + 'मोरङ', + 'सङ्खुवासभा', + 'लम्की-चुहा', + 'बारा', + 'हरिवन नगरपालिका', + 'मलङ्वा', + 'सिराहा', + 'जनकपुर', + 'सल्यान', + 'सिन्धुपाल्चोक', + 'दुल्लु', + 'ओखलढुङ्गा', + 'पाल्पा', + 'इटहरी', + 'रेसुङगा', + 'कृष्णनगर', + 'शुक्लगण्डकी', + 'नुवाकोट', + 'साँफेबगर', + 'राजविराज', + 'नेपालगंज', + 'भिमेश्वर', + 'ताप्लेजुङ', + 'धुलिखेल', + 'व्यास', + 'भोजपुर', + 'धादिङ', + 'बेनी', + 'अर्घाखाँची', + 'भीमदत्त', + 'रौतहट', + 'जलेश्वर', + 'देवदह', + 'बेलवारी', + 'बुटवल', + 'सुर्खेत', + 'मङ्गलसेन', + 'कैलाली', + 'धनकुटा', + 'रुपन्देही', + 'सल्यान', + 'रामपुर', + 'बिराटनगर', + 'चौतारा', + 'देवचुली', + 'कपिलवस्तु', + 'सुनवल', + 'शिवराज', + 'चम्पापुर (चापागाउँ)', + 'भरतपुर', + 'गढिमाई', + 'उर्लावारी', + 'लेखनाथ', + 'सिद्धिचरण', + 'मेचीनगर', + 'चित्रवन', + 'कास्की', + 'गौशाला', + 'पुतलीबजार', + 'बिदुर', + 'शम्भुनाथ', + 'पर्सा', + 'प्युठान', + 'निजगढ', + 'डडेलधुरा', + 'कन्काई', + 'गैंडाकोट', + 'पाल्पा', + 'कार्यविनायक*', + 'तिलोत्तमा', + 'तुलसीपुर', + 'वीरगञ्ज', + 'शंखरपुर*', + 'अत्तरिया', + 'बझाङ', + 'मन्थली*', + 'कपिलवस्तु', + 'कटारी', + 'हेटौडा', + 'कलैया', + 'सुन्दर दुलारी', + 'सिन्धुली', + 'थाहा', + 'बाँके', + 'ललितपुर', + 'दार्चुला', + 'पोखरा', + 'बन्दीपुर', + 'सर्लाही', + 'कोहलपुर', + 'सैनामैना', + 'अमरागढी', + 'उदयपुर', + 'काठमाडौं', + 'सुर्योदय', + 'सिराहा', + 'महोत्तरी', + 'धनगढी', + 'शारदा', + 'काभ्रेपलाञ्चोक', + 'त्रियुगा', + 'रामेछाप', + 'पाँचथर', + 'इलाम', + 'भोजपुर', + 'मध्यपुर ठिमी', + 'दुहवी-भलुवा', + 'दशरथचन्द', + 'बैतडी', + 'कोशी हरैंचा', + 'चापाकोट', + 'दिक्तेल', + 'चन्द्रपुर', + 'लालबन्दी', + 'चितवन', + 'रत्ननगर', + 'पृथ्वीनारायण', + 'धनुषा', + 'गुल्मी', + 'बेंसीशहर', + 'लमजुङ', + 'अछाम', + 'तनहुँ', + 'खाँदबारी', + 'बिर्तामोड', + 'कमलामाई', + 'छिरेश्वरनाथ', + 'सिद्धार्थनगर', + 'निलकण्ठ', + 'गोर्खा', + 'दोलखा', + 'रामग्राम', + 'इनरूवा', + 'कावासोती', + 'बेल्टार बसाहा', + 'जुम्ला', + 'ईश्वरपुर', + ) + + districts = ( + 'अछाम', + 'अर्घाखाँची', + 'इलाम', + 'उदयपुर', + 'ओखलढुङ्गा', + 'कञ्चनपुर', + 'कपिलवस्तु', + 'काठमाडौं', + 'काभ्रेपलाञ्चोक', + 'कालीकोट', + 'कास्की', + 'कैलाली', + 'खोटाङ', + 'गुल्मी', + 'गोर्खा', + 'चितवन', + 'जाजरकोट', + 'जुम्ला', + 'झापा', + 'डडेल्धुरा', + 'डोटी', + 'डोल्पा', + 'तनहुँ', + 'ताप्लेजुङ', + 'तेह्रथुम', + 'दाङ', + 'दार्चुला', + 'दैलेख', + 'दोलखा', + 'धनकुटा', + 'धनुषा', + 'धादिङ', + 'नवलपरासी', + 'नुवाकोट', + 'पर्वत', + 'पर्सा', + 'पाँचथर', + 'पाल्पा', + 'प्युठान', + 'बझाङ', + 'बर्दिया', + 'बाँके', + 'बाग्लुङ', + 'बाजुरा', + 'बारा', + 'भक्तपुर', + 'भोजपुर', + 'मकवानपुर', + 'मनाङ', + 'महोत्तरी', + 'मुगु', + 'मुस्ताङ', + 'मोरङ', + 'म्याग्दी', + 'रसुवा', + 'रामेछाप', + 'रुकुम', + 'रूपन्देही', + 'रोल्पा', + 'रौतहट', + 'लमजुङ्', + 'ललितपुर', + 'वैतडी', + 'संखुवासभा', + 'सप्तरी', + 'सर्लाही', + 'सल्यान', + 'सिन्धुपलाञ्चोक', + 'सिन्धुली', + 'सिराहा', + 'सुनसरी', + 'सुर्खेत', + 'सोलुखुम्बु', + 'स्याङ्जा', + 'हुम्ला', + ) + + def district(self): + """ + :example अछाम + """ + return self.random_element(self.districts) + + def city(self): + """ + :example कावासोत + """ + return self.random_element(self.cities) + + def building_prefix(self): + """ + :example वडा + """ + return self.random_element(self.building_prefixes) diff --git a/testbed/joke2k__faker/faker/providers/address/nl_BE/__init__.py b/testbed/joke2k__faker/faker/providers/address/nl_BE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d814af3f5e827f9c89c62819d6c816b8901a08 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/nl_BE/__init__.py @@ -0,0 +1,577 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + building_number_formats = ('#', '##', '###', '#', '##', '###') + + street_suffixes = ( + 'baan', 'boulevard', 'dreef', 'hof', 'laan', 'lei', 'pad', + 'ring', 'singel', 'steeg', 'straat', 'weg', + ) + + # the 4 digit numerical part of Belgium postal codes is between 1000 and 9999; + # see https://nl.wikipedia.org/wiki/Postcode#Postnummers_in_België + postcode_formats = ('%###',) + + city_formats = ('{{city}}',) + + # countries are from http://nl.wikipedia.org/wiki/ISO_3166-1 + countries = ( + 'Afghanistan', 'Albanië', 'Algerije', 'Amerikaans-Samoa', + 'Amerikaanse Maagdeneilanden', 'Andorra', 'Angola', 'Anguilla', + 'Antarctica', 'Antigua en Barbuda', 'Argentinië', 'Armenië', 'Aruba', + 'Australië', 'Azerbeidzjan', "Bahama's", 'Bahrein', 'Bangladesh', + 'Barbados', 'België', 'Belize', 'Benin', 'Bermuda', 'Bhutan', + 'Bolivia', 'Bonaire, Sint Eustatius en Saba', 'Bosnië en Herzegovina', + 'Botswana', 'Bouveteiland', 'Brazilië', + 'Brits Indische Oceaanterritorium', 'Britse Maagdeneilanden', 'Brunei', + 'Bulgarije', 'Burkina Faso', 'Burundi', 'Cambodja', 'Canada', + 'Centraal-Afrikaanse Republiek', 'Chili', 'China', 'Christmaseiland', + 'Cocoseilanden', 'Colombia', 'Comoren', 'Congo-Brazzaville', + 'Congo-Kinshasa', 'Cookeilanden', 'Costa Rica', 'Cuba', 'Curaçao', + 'Cyprus', 'Denemarken', 'Djibouti', 'Dominica', + 'Dominicaanse Republiek', 'Duitsland', 'Ecuador', 'Egypte', + 'El Salvador', 'Equatoriaal-Guinea', 'Eritrea', 'Estland', 'Ethiopië', + 'Faeröer', 'Falklandeilanden', 'Fiji', 'Filipijnen', 'Finland', + 'Frankrijk', 'Frans-Guyana', 'Frans-Polynesië', + 'Franse Zuidelijke en Antarctische Gebieden', 'Gabon', 'Gambia', + 'Georgië', 'Ghana', 'Gibraltar', 'Grenada', 'Griekenland', 'Groenland', + 'Guadeloupe', 'Guam', 'Guatemala', 'Guernsey', 'Guinee', + 'Guinee-Bissau', 'Guyana', 'Haïti', 'Heard en McDonaldeilanden', + 'Honduras', 'Hongarije', 'Hongkong', 'IJsland', 'Ierland', 'India', + 'Indonesië', 'Irak', 'Iran', 'Israël', 'Italië', 'Ivoorkust', + 'Jamaica', 'Japan', 'Jemen', 'Jersey', 'Jordanië', 'Kaaimaneilanden', + 'Kaapverdië', 'Kameroen', 'Kazachstan', 'Kenia', 'Kirgizië', + 'Kiribati', 'Kleine Pacifische eilanden van de Verenigde Staten', + 'Koeweit', 'Kroatië', 'Laos', 'Lesotho', 'Letland', 'Libanon', + 'Liberia', 'Libië', 'Liechtenstein', 'Litouwen', 'Luxemburg', 'Macau', + 'Macedonië', 'Madagaskar', 'Malawi', 'Maldiven', 'Maleisië', 'Mali', + 'Malta', 'Man', 'Marokko', 'Marshalleilanden', 'Martinique', + 'Mauritanië', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia', + 'Moldavië', 'Monaco', 'Mongolië', 'Montenegro', 'Montserrat', + 'Mozambique', 'Myanmar', 'Namibië', 'Nauru', 'Nederland', 'Nepal', + 'Nicaragua', 'Nieuw-Caledonië', 'Nieuw-Zeeland', 'Niger', 'Nigeria', + 'Niue', 'Noord-Korea', 'Noordelijke Marianen', 'Noorwegen', 'Norfolk', + 'Oeganda', 'Oekraïne', 'Oezbekistan', 'Oman', 'Oost-Timor', + 'Oostenrijk', 'Pakistan', 'Palau', 'Palestina', 'Panama', + 'Papoea-Nieuw-Guinea', 'Paraguay', 'Peru', 'Pitcairneilanden', 'Polen', + 'Portugal', 'Puerto Rico', 'Qatar', 'Roemenië', 'Rusland', 'Rwanda', + 'Réunion', 'Saint Kitts en Nevis', 'Saint Lucia', + 'Saint Vincent en de Grenadines', 'Saint-Barthélemy', + 'Saint-Pierre en Miquelon', 'Salomonseilanden', 'Samoa', 'San Marino', + 'Sao Tomé en Principe', 'Saoedi-Arabië', 'Senegal', 'Servië', + 'Seychellen', 'Sierra Leone', 'Singapore', 'Sint Maarten', + 'Sint-Helena, Ascension en Tristan da Cunha', 'Sint-Maarten', + 'Slovenië', 'Slowakije', 'Soedan', 'Somalië', 'Spanje', + 'Spitsbergen en Jan Mayen', 'Sri Lanka', 'Suriname', 'Swaziland', + 'Syrië', 'Tadzjikistan', 'Taiwan', 'Tanzania', 'Thailand', 'Togo', + 'Tokelau', 'Tonga', 'Trinidad en Tobago', 'Tsjaad', 'Tsjechië', + 'Tunesië', 'Turkije', 'Turkmenistan', 'Turks- en Caicoseilanden', + 'Tuvalu', 'Uruguay', 'Vanuatu', 'Vaticaanstad', 'Venezuela', + 'Verenigd Koninkrijk', 'Verenigde Arabische Emiraten', + 'Verenigde Staten', 'Vietnam', 'Wallis en Futuna', 'Westelijke Sahara', + 'Wit-Rusland', 'Zambia', 'Zimbabwe', 'Zuid-Afrika', + 'Zuid-Georgia en de Zuidelijke Sandwicheilanden', 'Zuid-Korea', + 'Zuid-Soedan', 'Zweden', 'Zwitserland', 'Åland', + ) + + # cities as listed on "postcodezoeker" + # http://www.postcodes-maps.be/postcodelijst.php + cities = ( + "'s Herenelderen", "'s-Gravenvoeren", "'s-Gravenwezel", "Aaigem", "Aalbeke", + "Aalst", "Aalter", "Aarschot", "Aarsele", "Aartrijke", "Aartselaar", "Abolens", + "Abée", "Achel", "Achet", "Achêne", "Acosse", "Acoz", "Adegem", "Adinkerke", + "Affligem", "Afsnee", "Agimont", "Aineffe", "Aische-en-Refail", "Aiseau", + "Aiseau-Presles", "Aisemont", "Alken", "Alle", "Alleur", "Alsemberg", + "Alveringem", "Amay", "Amberloup", "Ambly", "Ambresin", "Amel", "Amonines", + "Amougies", "Ampsin", "Andenne", "Anderlecht", "Anderlues", "Andrimont", + "Angleur", "Angre", "Angreau", "Anhée", "Anlier", "Anloy", "Annevoie-Rouillon", + "Ans", "Anseremme", "Anseroeul", "Antheit", "Anthisnes", "Anthée", "Antoing", + "Antwerpen", "Anvaing", "Anzegem", "Appels", "Appelterre-Eichem", "Arbre", + "Arbrefontaine", "Arc-Ainières", "Arc-Wattripont", "Archennes", "Ardooie", + "Arendonk", "Argenteau", "Arlon", "Arquennes", "Arsimont", "Arville", "As", + "Aspelare", "Asper", "Asquillies", "Asse", "Assebroek", "Assenede", "Assenois", + "Assent", "Assesse", "Astene", "Ath", "Athis", "Athus", "Attenhoven", "Attenrode", + "Attert", "Attre", "Aubange", "Aubechies", "Aubel", "Aublain", "Auby-sur-Semois", + "Audregnies", "Aulnois", "Autelbas", "Autre-Eglise", "Autreppe", "Auvelais", + "Ave-et-Auffe", "Avekapelle", "Avelgem", "Avennes", "Averbode", + "Avernas-le-Bauduin", "Avin", "Awans", "Awenne", "Awirs", "Aye", "Ayeneux", + "Aywaille", "Baaigem", "Baal", "Baardegem", "Baarle-Hertog", "Baasrode", + "Bachte-Maria-Leerne", "Baelen", "Bagimont", "Baileux", "Bailièvre", "Baillamont", + "Bailleul", "Baillonville", "Baisieux", "Baisy-Thy", "Balegem", "Balen", + "Balâtre", "Bambrugge", "Bande", "Barbençon", "Barchon", "Baronville", "Barry", + "Barvaux-Condroz", "Barvaux-sur-Ourthe", "Bas-Oha", "Basse-Bodeux", "Bassenge", + "Bassevelde", "Bassilly", "Bastogne", "Basècles", "Batsheers", "Battice", + "Battignies", "Baudour", "Bauffe", "Baugnies", "Baulers", "Bavegem", "Bavikhove", + "Bazel", "Beaufays", "Beaumont", "Beauraing", "Beausaint", "Beauvoorde", + "Beauwelz", "Beclers", "Beek", "Beerlegem", "Beernem", "Beerse", "Beersel", + "Beerst", "Beert", "Beervelde", "Beerzel", "Beez", "Beffe", "Begijnendijk", + "Beho", "Beigem", "Bekegem", "Bekkerzeel", "Bekkevoort", "Belgrade", "Bellaire", + "Bellecourt", "Bellefontaine", "Bellegem", "Bellem", "Bellevaux", + "Bellevaux-Ligneuville", "Bellingen", "Beloeil", "Belsele", "Ben-Ahin", "Bende", + "Berbroek", "Berchem", "Berendrecht", "Berg", "Bergilers", "Beringen", "Berlaar", + "Berlare", "Berlingen", "Berloz", "Berneau", "Bernissart", "Bersillies-l'Abbaye", + "Bertem", "Bertogne", "Bertrix", "Bertrée", "Berzée", "Beselare", "Betekom", + "Bettincourt", "Beuzet", "Bevekom", "Bevel", "Bever", "Bevercé", "Bevere", + "Beveren-Leie", "Beveren-Roeselare", "Beveren-Waas", "Beveren-aan-den-Ijzer", + "Beverlo", "Beverst", "Beyne-Heusay", "Bienne-lez-Happart", "Bierbeek", "Biercée", + "Bierges", "Bierghes", "Bierset", "Bierwart", "Biesme", "Biesme-sous-Thuin", + "Biesmerée", "Biez", "Bihain", "Bikschote", "Bilstain", "Bilzen", "Binche", + "Binderveld", "Binkom", "Bioul", "Bissegem", "Bizet", "Bièvre", "Blaasveld", + "Blaimont", "Blandain", "Blanden", "Blankenberge", "Blaregnies", "Blaton", + "Blaugies", "Blehen", "Bleid", "Bleret", "Blicquy", "Blégny", "Bléharies", + "Bocholt", "Boechout", "Boekhout", "Boekhoute", "Boezinge", "Bogaarden", "Bohan", + "Boignée", "Boirs", "Bois-d'Haine", "Bois-de-Lessines", "Bois-de-Villers", + "Bois-et-Borsu", "Bolinne", "Bolland", "Bomal", "Bomal-sur-Ourthe", "Bombaye", + "Bommershoven", "Bon-Secours", "Boncelles", "Boneffe", "Bonheiden", "Boninne", + "Bonlez", "Bonnert", "Bonneville", "Bonsin", "Booischot", "Booitshoeke", "Boom", + "Boorsem", "Boortmeerbeek", "Borchtlombeek", "Borgerhout", "Borgloon", "Borlez", + "Borlo", "Borlon", "Bornem", "Bornival", "Borsbeek", "Borsbeke", "Bossière", + "Bossuit", "Bossut-Gottechain", "Bost", "Bothey", "Bottelare", "Bouffioulx", + "Bouge", "Bougnies", "Bouillon", "Bourlers", "Bourseigne-Neuve", + "Bourseigne-Vieille", "Boussoit", "Boussu", "Boussu-en-Fagne", + "Boussu-lez-Walcourt", "Bousval", "Boutersem", "Bouvignes-sur-Meuse", + "Bouvignies", "Bouwel", "Bovekerke", "Bovelingen", "Bovenistier", "Bovesse", + "Bovigny", "Boëlhe", "Bra", "Braffe", "Braibant", "Braine-l'Alleud", + "Braine-le-Château", "Braine-le-Comte", "Braives", "Brakel", "Branchon", "Bras", + "Brasmenil", "Brasschaat", "Bray", "Brecht", "Bredene", "Bree", "Breendonk", + "Bressoux", "Briegden", "Brielen", "Broechem", "Broekom", "Brugelette", "Brugge", + "Brunehaut", "Brussegem", "Brussel", "Brustem", "Bruyelle", "Brye", "Brûly", + "Brûly-de-Pesche", "Budingen", "Buggenhout", "Buissenal", "Buissonville", + "Buizingen", "Buken", "Bulskamp", "Bunsbeek", "Burcht", "Burdinne", "Bure", + "Burg-Reuland", "Burst", "Bury", "Buvingen", "Buvrinnes", "Buzenol", "Buzet", + "Büllingen", "Bütgenbach", "Callenelle", "Calonne", "Cambron-Casteau", + "Cambron-Saint-Vincent", "Carlsbourg", "Carnières", "Casteau", "Castillon", + "Celles", "Cerfontaine", "Chaineux", "Chairière", "Champion", "Champlon", + "Chanly", "Chantemelle", "Chapelle-lez-Herlaimont", "Chapelle-à-Oie", + "Chapelle-à-Wattines", "Chapon-Seraing", "Charleroi", "Charneux", "Chassepierre", + "Chastre", "Chastre-Villeroux-Blanmont", "Chastrès", "Chaudfontaine", + "Chaumont-Gistoux", "Chaussée-Notre-Dame-Louvignies", "Cherain", "Cheratte", + "Chercq", "Chevetogne", "Chevron", "Chimay", "Chiny", "Chièvres", "Chokier", + "Châtelet", "Châtelineau", "Châtillon", "Chênée", "Ciergnon", "Ciney", "Ciplet", + "Ciply", "Clabecq", "Clavier", "Clermont", "Clermont-sous-Huy", "Cognelée", + "Colfontaine", "Comblain-Fairon", "Comblain-au-Pont", "Comblain-la-Tour", + "Conneux", "Corbais", "Corbion", "Cordes", "Corenne", "Cornesse", "Cornimont", + "Corroy-le-Château", "Corroy-le-Grand", "Corswarem", "Cortil-Noirmont", + "Cortil-Wodon", "Couillet", "Cour-sur-Heure", "Courcelles", "Courrière", + "Court-Saint-Etienne", "Couthuin", "Coutisse", "Couture-Saint-Germain", "Couvin", + "Cras-Avernas", "Crehen", "Crisnée", "Croix-lez-Rouveroy", "Crombach", "Crupet", + "Cuesmes", "Cugnon", "Cul-des-Sarts", "Custinne", "Cérexhe-Heuseux", + "Céroux-Mousty", "Dadizele", "Dailly", "Daknam", "Dalhem", "Damme", "Dampicourt", + "Dampremy", "Darion", "Daussois", "Daussoulx", "Dave", "Daverdisse", "De Haan", + "De Klinge", "De Moeren", "De Panne", "De Pinte", "Deerlijk", "Deftinge", + "Deinze", "Denderbelle", "Denderhoutem", "Denderleeuw", "Dendermonde", + "Denderwindeke", "Dentergem", "Denée", "Dergneau", "Dessel", "Desselgem", + "Destelbergen", "Desteldonk", "Deurle", "Deurne", "Deux-Acren", "Dhuy", + "Diepenbeek", "Diest", "Diets-Heur", "Dikkebus", "Dikkele", "Dikkelvenne", + "Diksmuide", "Dilbeek", "Dilsen-Stokkem", "Dinant", "Dion", "Dion-Valmont", + "Dison", "Dochamps", "Doel", "Dohan", "Doische", "Dolembreux", "Donceel", + "Dongelberg", "Donk", "Donstiennes", "Dorinne", "Dormaal", "Dottenijs", "Dour", + "Dourbes", "Dranouter", "Driekapellen", "Drieslinter", "Drogenbos", "Drongen", + "Dréhance", "Dudzele", "Duffel", "Duisburg", "Duras", "Durbuy", "Durnal", "Dworp", + "Eben-Emael", "Ebly", "Ecaussinnes", "Ecaussinnes-Lalaing", + "Ecaussinnes-d'Enghien", "Edegem", "Edelare", "Edingen", "Eeklo", "Eernegem", + "Egem", "Eggewaartskapelle", "Eghezée", "Ehein", "Eigenbilzen", "Eindhout", + "Eine", "Eisden", "Eke", "Ekeren", "Eksaarde", "Eksel", "Elen", "Elene", + "Elewijt", "Eliksem", "Elingen", "Ellemelle", "Ellezelles", + "Ellignies-Sainte-Anne", "Ellignies-lez-Frasnes", "Ellikom", "Elouges", "Elsegem", + "Elsenborn", "Elsene", "Elst", "Elverdinge", "Elversele", "Emblem", "Embourg", + "Emelgem", "Emines", "Emptinne", "Ename", "Engelmanshoven", "Engis", "Enines", + "Ensival", "Epinois", "Eppegem", "Eprave", "Erbaut", "Erbisoeul", "Ere", + "Erembodegem", "Erezée", "Ermeton-sur-Biert", "Ernage", "Erneuville", "Ernonheid", + "Erondegem", "Erpe", "Erpe-Mere", "Erpent", "Erpion", "Erps-Kwerps", + "Erquelinnes", "Erquennes", "Ertvelde", "Erwetegem", "Escanaffles", "Esen", + "Esneux", "Esplechin", "Esquelmes", "Essen", "Essene", "Estaimbourg", + "Estaimpuis", "Estinnes", "Estinnes-au-Mont", "Estinnes-au-Val", "Etalle", "Ethe", + "Etikhove", "Ettelgem", "Etterbeek", "Eugies", "Eupen", "Evegnée", "Evelette", + "Everbeek", "Everberg", "Evere", "Evergem", "Evregnies", "Evrehailles", + "Eynatten", "Ezemaal", "Fagnolle", "Faimes", "Falaën", "Falisolle", "Fallais", + "Falmagne", "Falmignoul", "Familleureux", "Farciennes", "Faulx-les-Tombes", + "Fauroeulx", "Fauvillers", "Faymonville", "Fays-les-Veneurs", "Fayt-le-Franc", + "Fayt-lez-Manage", "Felenne", "Feluy", "Feneur", "Fernelmont", "Ferrières", + "Feschaux", "Fexhe-Slins", "Fexhe-le-Haut-Clocher", "Filot", "Finnevaux", + "Fize-Fontaine", "Fize-le-Marsal", "Flamierge", "Flavion", "Flawinne", "Fleurus", + "Floreffe", "Florennes", "Florenville", "Floriffoux", "Florée", "Flostoy", + "Flémalle", "Flémalle-Grande", "Flémalle-Haute", "Flénu", "Fléron", "Flône", + "Focant", "Folx-les-Caves", "Fontaine-Valmont", "Fontaine-l'Evêque", "Fontenelle", + "Fontenoille", "Fontenoy", "Fooz", "Forchies-la-Marche", "Forest", "Forges", + "Forges-Philippe", "Forrières", "Forville", "Forêt", "Fosse", "Fosses-la-Ville", + "Fouleng", "Fourbechies", "Foy-Notre-Dame", "Fraipont", "Fraire", "Fraiture", + "Frameries", "Framont", "Franc-Waret", "Franchimont", "Francorchamps", "Franière", + "Frasnes", "Frasnes-lez-Anvaing", "Frasnes-lez-Buissenal", + "Frasnes-lez-Gosselies", "Freloux", "Freux", "Froidchapelle", "Froidfontaine", + "Froidmont", "Fronville", "Froyennes", "Fumal", "Furfooz", "Furnaux", "Gaasbeek", + "Gages", "Gallaix", "Galmaarden", "Ganshoren", "Gaurain-Ramecroix", "Gavere", + "Gedinne", "Geel", "Geer", "Geest-Gérompont-Petit-Rosière", "Geetbets", + "Gelbressée", "Gelinden", "Gellik", "Gelrode", "Geluveld", "Geluwe", "Gembes", + "Gembloux", "Gemmenich", "Genappe", "Genk", "Genly", "Genoelselderen", "Gent", + "Gentbrugge", "Gentinnes", "Genval", "Geraardsbergen", "Gerdingen", "Gerin", + "Gerpinnes", "Gestel", "Gesves", "Ghislenghien", "Ghlin", "Ghoy", "Gibecq", + "Gierle", "Gijverinkhove", "Gijzegem", "Gijzelbrechtegem", "Gijzenzele", "Gilly", + "Gimnée", "Gingelom", "Gistel", "Gits", "Givry", "Glabais", "Glabbeek-Zuurbemde", + "Glain", "Gleixhe", "Glimes", "Glons", "Gochenée", "Godarville", "Godinne", + "Godveerdegem", "Goeferdinge", "Goegnies-Chaussée", "Goesnes", "Goetsenhoven", + "Gomzé-Andoumont", "Gondregnies", "Gonrieux", "Gontrode", "Gooik", "Gors-Opleeuw", + "Gorsem", "Gosselies", "Gotem", "Gottem", "Gottignies", "Gougnies", "Gourdinne", + "Goutroux", "Gouvy", "Gouy-lez-Piéton", "Gozée", "Goé", "Graide", "Grammene", + "Grand-Axhe", "Grand-Hallet", "Grand-Halleux", "Grand-Leez", "Grand-Manil", + "Grand-Rechain", "Grand-Reng", "Grand-Rosière-Hottomont", "Grandglise", + "Grandhan", "Grandmenil", "Grandmetz", "Grandrieu", "Grandville", "Grandvoir", + "Grapfontaine", "Graty", "Graux", "Grazen", "Grembergen", "Grez-Doiceau", + "Grimbergen", "Grimminge", "Grivegnée", "Grobbendonk", "Groot-Bijgaarden", + "Groot-Gelmen", "Groot-Loon", "Gros-Fays", "Grosage", "Grote-Brogel", + "Grote-Spouwen", "Grotenberge", "Gruitrode", "Grune", "Grupont", "Grâce-Berleur", + "Grâce-Hollogne", "Guignies", "Guigoven", "Guirsch", "Gullegem", "Gutschoven", + "Gérompont", "Gérouville", "Haacht", "Haaltert", "Haasdonk", "Haasrode", "Habay", + "Habay-la-Neuve", "Habay-la-Vieille", "Habergy", "Haccourt", "Hachy", + "Hacquegnies", "Haillot", "Haine-Saint-Paul", "Haine-Saint-Pierre", "Hainin", + "Hakendover", "Halanzy", "Halen", "Hallaar", "Halle", "Halle-Booienhoven", + "Halleux", "Halma", "Halmaal", "Haltinne", "Ham", "Ham-sur-Heure", + "Ham-sur-Heure-Nalinnes", "Ham-sur-Sambre", "Hamipré", "Hamme", "Hamme-Mille", + "Hamoir", "Hamois", "Hamont", "Hamont-Achel", "Hampteau", "Han-sur-Lesse", + "Handzame", "Haneffe", "Hannut", "Hannêche", "Hanret", "Hansbeke", + "Hantes-Wihéries", "Hanzinelle", "Hanzinne", "Harchies", "Harelbeke", "Haren", + "Haren-Borgloon", "Haren-Tongeren", "Hargimont", "Harmignies", "Harnoncourt", + "Harre", "Harsin", "Harveng", "Harzé", "Hasselt", "Hastière", "Hastière-Lavaux", + "Hastière-par-Delà", "Hatrival", "Haulchin", "Hauset", "Haut-Fays", "Haut-Ittre", + "Haut-le-Wastia", "Hautrage", "Havay", "Havelange", "Haversin", "Havinnes", + "Havré", "Hechtel", "Hechtel-Eksel", "Heer", "Heers", "Hees", "Heestert", + "Heffen", "Heikruis", "Heindonk", "Heinsch", "Heist-aan-Zee", "Heist-op-den-Berg", + "Hekelgem", "Heks", "Helchteren", "Heldergem", "Helen-Bos", "Helkijn", + "Hellebecq", "Hemelveerdegem", "Hemiksem", "Hemptinne", "Hemptinne-lez-Florennes", + "Hendrieken", "Henis", "Hennuyères", "Henri-Chapelle", "Henripont", "Hensies", + "Heppen", "Heppenbach", "Heppignies", "Herbeumont", "Herchies", "Herderen", + "Herdersem", "Herent", "Herentals", "Herenthout", "Herfelingen", "Hergenrath", + "Herk-de-Stad", "Hermalle-sous-Argenteau", "Hermalle-sous-Huy", + "Hermeton-sur-Meuse", "Hermée", "Herne", "Herquegies", "Herseaux", "Herselt", + "Herstal", "Herstappe", "Hertain", "Herten", "Hertsberge", "Herve", "Herzele", + "Heule", "Heure", "Heure-le-Romain", "Heurne", "Heusden", "Heusden-Zolder", + "Heusy", "Heuvelland", "Hever", "Heverlee", "Heyd", "Hillegem", "Hingene", + "Hingeon", "Hives", "Hoboken", "Hodeige", "Hodister", "Hody", "Hoegaarden", + "Hoeilaart", "Hoeke", "Hoelbeek", "Hoeleden", "Hoepertingen", "Hoeselt", + "Hoevenen", "Hofstade", "Hogne", "Hognoul", "Hollain", "Hollange", "Hollebeke", + "Hollogne-aux-Pierres", "Hollogne-sur-Geer", "Holsbeek", "Hombeek", "Hombourg", + "Hompré", "Hondelange", "Honnay", "Honnelles", "Hooglede", "Hoogstade", + "Hoogstraten", "Horebeke", "Horion-Hozémont", "Hornu", "Horpmaal", "Horrues", + "Hotton", "Houdemont", "Houdeng-Aimeries", "Houdeng-Goegnies", "Houdremont", + "Houffalize", "Hour", "Housse", "Houtain-Saint-Siméon", "Houtain-le-Val", + "Houtaing", "Houtave", "Houtem", "Houthalen", "Houthalen-Helchteren", "Houthem", + "Houthulst", "Houtvenne", "Houwaart", "Houx", "Houyet", "Hove", "Hoves", + "Howardries", "Huccorgne", "Huise", "Huissignies", "Huizingen", "Huldenberg", + "Hulshout", "Hulsonniaux", "Hulste", "Humain", "Humbeek", "Hundelgem", "Huppaye", + "Huy", "Hyon", "Hélécine", "Hérinnes-lez-Pecq", "Héron", "Hévillers", "Ichtegem", + "Iddergem", "Idegem", "Ieper", "Impe", "Incourt", "Ingelmunster", "Ingooigem", + "Irchonwelz", "Isières", "Isnes", "Itegem", "Itterbeek", "Ittre", "Ivoz-Ramet", + "Izegem", "Izel", "Izenberge", "Izier", "Jabbeke", "Jalhay", "Jallet", "Jamagne", + "Jambes", "Jamiolle", "Jamioulx", "Jamoigne", "Jandrain-Jandrenouille", "Jauche", + "Jauchelette", "Javingue", "Jehay", "Jehonville", "Jemappes", "Jemelle", + "Jemeppe-sur-Meuse", "Jemeppe-sur-Sambre", "Jeneffe", "Jesseren", "Jette", "Jeuk", + "Jodoigne", "Jodoigne-Souveraine", "Jollain-Merlin", "Joncret", "Julémont", + "Jumet", "Jupille-sur-Meuse", "Juprelle", "Jurbise", "Juseret", "Kaaskerke", + "Kachtem", "Kaggevinne", "Kain", "Kalken", "Kallo", "Kallo-Kieldrecht", + "Kalmthout", "Kampenhout", "Kanegem", "Kanne", "Kapelle-op-den-Bos", "Kapellen", + "Kaprijke", "Kaster", "Kasterlee", "Kaulille", "Keerbergen", "Keiem", "Kelmis", + "Kemexhe", "Kemmel", "Kemzeke", "Kerkhove", "Kerkom", "Kerkom-bij-Sint-Truiden", + "Kerksken", "Kermt", "Kerniel", "Kersbeek-Miskom", "Kessel", "Kessel-Lo", + "Kessenich", "Kester", "Kettenis", "Keumiée", "Kieldrecht", "Kinrooi", + "Klein-Gelmen", "Kleine-Brogel", "Kleine-Spouwen", "Klemskerke", "Klerken", + "Kluisbergen", "Kluizen", "Knesselare", "Knokke", "Knokke-Heist", "Kobbegem", + "Koekelare", "Koekelberg", "Koersel", "Koksijde", "Kolmont-Borgloon", + "Kolmont-Tongeren", "Komen", "Komen-Waasten", "Koningshooikt", "Koninksem", + "Kontich", "Kooigem", "Koolkerke", "Koolskamp", "Korbeek-Dijle", "Korbeek-Lo", + "Kortemark", "Kortenaken", "Kortenberg", "Kortessem", "Kortijs", "Kortrijk", + "Kortrijk-Dutsel", "Kozen", "Kraainem", "Krombeke", "Kruibeke", "Kruishoutem", + "Kumtich", "Kuringen", "Kuttekoven", "Kuurne", "Kwaadmechelen", "Kwaremont", "La", + "La Bruyère", "La Glanerie", "La Gleize", "La Hestre", "La Hulpe", "La Louvière", + "La bouverie", "La-Roche-en-Ardenne", "Laakdal", "Laar", "Laarne", "Labuissière", + "Lacuisine", "Ladeuze", "Laforêt", "Lahamaide", "Laken", "Lamain", "Lambermont", + "Lambusart", "Lamine", "Lamontzée", "Lamorteau", "Lampernisse", "Lanaken", + "Lanaye", "Landegem", "Landelies", "Landen", "Landenne", "Landskouter", "Laneffe", + "Langdorp", "Langemark", "Langemark-Poelkapelle", "Lanklaar", "Lanquesaint", + "Lantin", "Lantremange", "Laplaigne", "Lapscheure", "Lasne", + "Lasne-Chapelle-Saint-Lambert", "Lathuy", "Latinne", "Latour", "Lauw", "Lauwe", + "Lavacherie", "Lavaux-Sainte-Anne", "Lavoir", "Le Mesniel", "Le Roeulx", + "Le Roux", "Lebbeke", "Lede", "Ledeberg", "Ledegem", "Leefdaal", "Leerbeek", + "Leernes", "Leers-Nord", "Leers-et-Fosteau", "Leest", "Leeuwergem", "Leffinge", + "Leignon", "Leisele", "Leke", "Lembeek", "Lembeke", "Lemberge", "Lendelede", + "Lennik", "Lens", "Lens-Saint-Remy", "Lens-Saint-Servais", "Lens-sur-Geer", + "Leopoldsburg", "Les Avins", "Les Bons", "Les Bulles", "Les Hayons", + "Les Waleffes", "Lesdain", "Lessines", "Lessive", "Lesterny", "Lesve", + "Lettelingen", "Letterhoutem", "Leugnies", "Leupegem", "Leut", "Leuven", "Leuze", + "Leuze-en-Hainaut", "Leval-Chaudeville", "Leval-Trahegnies", "Liberchies", + "Libin", "Libramont", "Libramont-Chevigny", "Lichtaart", "Lichtervelde", + "Liedekerke", "Lieferinge", "Lier", "Lierde", "Lierneux", "Liernu", "Liers", + "Liezele", "Ligne", "Ligney", "Ligny", "Lille", "Lillo", "Lillois-Witterzée", + "Limal", "Limbourg", "Limelette", "Limerlé", "Limont", "Lincent", "Linden", + "Linkebeek", "Linkhout", "Linsmeau", "Lint", "Linter", "Lippelo", "Lisogne", + "Lissewege", "Lives-sur-Meuse", "Lixhe", "Liège", "Lo", "Lo-Reninge", "Lobbes", + "Lochristi", "Lodelinsart", "Loenhout", "Loker", "Lokeren", "Loksbergen", + "Lombardsijde", "Lombise", "Lommel", "Lommersweiler", "Lompret", "Lomprez", + "Loncin", "Londerzeel", "Longchamps", "Longlier", "Longueville", "Longvilly", + "Lontzen", "Lonzée", "Loonbeek", "Loppem", "Lorcé", "Lot", "Lotenhulle", + "Louette-Saint-Denis", "Louette-Saint-Pierre", "Loupoigne", "Louvain-la-Neuve", + "Louveigné", "Lovendegem", "Lovenjoel", "Loverval", "Loyers", "Lubbeek", + "Luingne", "Lummen", "Lustin", "Luttre", "Léglise", "Maarke-Kerkem", "Maarkedal", + "Maaseik", "Maasmechelen", "Mabompré", "Machelen", "Macon", "Macquenoise", + "Maffe", "Maffle", "Magnée", "Maillen", "Mainvault", "Maisières", "Maissin", + "Maizeret", "Mal", "Maldegem", "Malderen", "Malempré", "Malle", "Malmedy", + "Malonne", "Malvoisin", "Malèves-Sainte-Marie-Wastines", "Manage", "Manderfeld", + "Manhay", "Mannekensvere", "Maransart", "Marbais", "Marbaix", "Marbehan", + "Marche-en-Famenne", "Marche-les-Dames", "Marche-lez-Ecaussinnes", + "Marchienne-au-Pont", "Marchin", "Marchipont", "Marchovelette", "Marcinelle", + "Marcourt", "Marenne", "Mariakerke", "Mariekerke", "Mariembourg", "Marilles", + "Mark", "Marke", "Markegem", "Marneffe", "Marquain", "Martelange", "Martenslinde", + "Martouzin-Neuville", "Masbourg", "Masnuy-Saint-Jean", "Masnuy-Saint-Pierre", + "Massemen", "Massenhoven", "Matagne-la-Grande", "Matagne-la-Petite", "Mater", + "Maubray", "Maulde", "Maurage", "Mazenzele", "Mazy", "Mazée", "Mechelen", + "Mechelen-Bovelingen", "Mechelen-aan-de-Maas", "Meeffe", "Meensel-Kiezegem", + "Meer", "Meerbeek", "Meerbeke", "Meerdonk", "Meerhout", "Meerle", "Meeswijk", + "Meetkerke", "Meeuwen", "Meeuwen-Gruitrode", "Mehaigne", "Meigem", "Meilegem", + "Meise", "Meix-devant-Virton", "Meix-le-Tige", "Melden", "Meldert", "Melen", + "Melkwezer", "Melle", "Mellery", "Melles", "Mellet", "Mellier", "Melsbroek", + "Melsele", "Melsen", "Membach", "Membre", "Membruggen", "Mendonk", "Menen", + "Merbes-Sainte-Marie", "Merbes-le-Château", "Merchtem", "Merdorp", "Mere", + "Merelbeke", "Merendree", "Merkem", "Merksem", "Merksplas", "Merlemont", "Mesen", + "Meslin-l'Evêque", "Mesnil-Eglise", "Mesnil-Saint-Blaise", "Mespelare", + "Messancy", "Messelbroek", "Mesvin", "Mettekoven", "Mettet", "Meulebeke", "Meux", + "Meyerode", "Michelbeke", "Micheroux", "Middelburg", "Middelkerke", + "Mielen-boven-Aalst", "Mignault", "Millen", "Milmort", "Minderhout", "Mirwart", + "Miécret", "Modave", "Moelingen", "Moen", "Moerbeke", "Moerbeke-Waas", "Moere", + "Moerkerke", "Moerzeke", "Moeskroen", "Moha", "Mohiville", "Moignelée", "Moircy", + "Mol", "Molenbaix", "Molenbeek-Wersbeek", "Molenbeersel", "Molenstede", "Mollem", + "Momalle", "Momignies", "Monceau-Imbrechies", "Monceau-en-Ardenne", + "Monceau-sur-Sambre", "Mons", "Mons-lez-Liège", "Monstreux", "Mont", + "Mont-Gauthier", "Mont-Saint-André", "Mont-Saint-Aubert", "Mont-Saint-Guibert", + "Mont-Sainte-Aldegonde", "Mont-Sainte-Geneviève", "Mont-de-l'Enclus", + "Mont-sur-Marchienne", "Montbliart", "Montegnée", "Montenaken", + "Montignies-Saint-Christophe", "Montignies-lez-Lens", "Montignies-sur-Roc", + "Montignies-sur-Sambre", "Montigny-le-Tilleul", "Montleban", "Montroeul-au-Bois", + "Montroeul-sur-Haine", "Montzen", "Moorsel", "Moorsele", "Moorslede", "Moortsele", + "Mopertingen", "Moregem", "Moresnet", "Morhet", "Morialmé", "Morkhoven", + "Morlanwelz", "Morlanwelz-Mariemont", "Mormont", "Mornimont", "Mortier", + "Mortroux", "Mortsel", "Morville", "Moulbaix", "Mourcourt", "Moustier", + "Moustier-sur-Sambre", "Mouzaive", "Moxhe", "Mozet", "Muizen", "Mullem", + "Munkzwalm", "Muno", "Munsterbilzen", "Munte", "Musson", "Mussy-la-Ville", "My", + "Méan", "Mélin", "Mévergnies-lez-Lens", "Naast", "Nadrin", "Nafraiture", + "Nalinnes", "Namur", "Namêche", "Nandrin", "Naninne", "Naomé", "Nassogne", + "Natoye", "Nazareth", "Neder-over-Heembeek", "Nederboelare", "Nederbrakel", + "Nederename", "Nederhasselt", "Nederokkerzeel", "Nederzwalm-Hermelgem", + "Neerglabbeek", "Neerharen", "Neerhespen", "Neerheylissem", "Neerijse", + "Neerlanden", "Neerlinter", "Neeroeteren", "Neerpelt", "Neerrepen", "Neervelp", + "Neerwaasten", "Neerwinden", "Neigem", "Nerem", "Nessonvaux", "Nethen", + "Nettinne", "Neu-Moresnet", "Neufchâteau", "Neufmaison", "Neufvilles", "Neupré", + "Neuville", "Neuville-en-Condroz", "Nevele", "Niel", "Niel-bij-As", + "Niel-bij-Sint-Truiden", "Nieuwenhove", "Nieuwenrode", "Nieuwerkerken", + "Nieuwkapelle", "Nieuwkerke", "Nieuwkerken-Waas", "Nieuwmunster", "Nieuwpoort", + "Nieuwrode", "Nijlen", "Nil-Saint-Vincent-Saint-Martin", "Nimy", "Ninove", + "Nismes", "Nivelles", "Niverlée", "Nives", "Nobressart", "Nodebais", "Noduwez", + "Noirchain", "Noirefontaine", "Noiseux", "Nokere", "Nollevaux", "Noorderwijk", + "Noordschote", "Nossegem", "Nothomb", "Nouvelles", "Noville", "Noville-les-Bois", + "Noville-sur-Méhaigne", "Nukerke", "Néchin", "Obaix", "Obigies", "Obourg", + "Ochamps", "Ocquier", "Odeigne", "Odeur", "Oedelem", "Oekene", "Oelegem", "Oeren", + "Oeselgem", "Oetingen", "Oeudeghien", "Oevel", "Offagne", "Ogy", "Ohain", "Ohey", + "Oignies-en-Thiérache", "Oisquercq", "Oizy", "Okegem", "Olen", "Oleye", + "Ollignies", "Olloy-sur-Viroin", "Olmen", "Olne", "Olsene", "Omal", "Ombret", + "Omezée", "On", "Onhaye", "Onkerzele", "Onnezies", "Onoz", + "Onze-Lieve-Vrouw-Lombeek", "Onze-Lieve-Vrouw-Waver", "Ooigem", "Ooike", + "Oombergen", "Oorbeek", "Oordegem", "Oostakker", "Oostduinkerke", "Oosteeklo", + "Oostende", "Oosterzele", "Oostham", "Oostkamp", "Oostkerke-Damme", + "Oostkerke-Diksmuide", "Oostmalle", "Oostnieuwkerke", "Oostrozebeke", + "Oostvleteren", "Oostwinkel", "Opbrakel", "Opdorp", "Opglabbeek", "Opgrimbie", + "Ophain-Bois-Seigneur-Isaac", "Ophasselt", "Opheers", "Opheylissem", "Ophoven", + "Opitter", "Oplinter", "Opoeteren", "Opont", "Opprebais", "Oppuurs", "Opvelp", + "Opwijk", "Orbais", "Orchimont", "Orcq", "Ordingen", "Oret", "Oreye", "Orgeo", + "Ormeignies", "Orp-Jauche", "Orp-le-Grand", "Orroir", "Orsmaal-Gussenhoven", + "Ortho", "Ostiches", "Otegem", "Oteppe", "Othée", "Otrange", "Ottenburg", + "Ottergem", "Ottignies", "Ottignies-Louvain-la-Neuve", "Oud-Heverlee", + "Oud-Turnhout", "Oudegem", "Oudekapelle", "Oudenaarde", "Oudenaken", "Oudenburg", + "Oudergem", "Ouffet", "Ougrée", "Oupeye", "Outer", "Outgaarden", "Outrelouxhe", + "Outrijve", "Ouwegem", "Overboelare", "Overhespen", "Overijse", "Overmere", + "Overpelt", "Overrepen", "Overwinden", "Paal", "Paifve", "Pailhe", "Paliseul", + "Pamel", "Papignies", "Parike", "Passendale", "Patignies", "Paturages", + "Paulatem", "Pecq", "Peer", "Peissant", "Pellaines", "Pellenberg", "Pepingen", + "Pepinster", "Perk", "Pervijze", "Perwez", "Perwez-Haillot", "Pesche", "Pessoux", + "Petegem-aan-de-Leie", "Petegem-aan-de-Schelde", "Petigny", "Petit-Fays", + "Petit-Hallet", "Petit-Rechain", "Petit-Roeulx-lez-Braine", + "Petit-Roeulx-lez-Nivelles", "Petit-Thier", "Petite-Chapelle", "Peutie", + "Philippeville", "Pipaix", "Piringen", "Pironchamps", "Pittem", "Piéton", + "Piétrain", "Piétrebais", "Plainevaux", "Plancenoit", "Ploegsteert", "Plombières", + "Poederlee", "Poeke", "Poelkapelle", "Poesele", "Pollare", "Polleur", + "Pollinkhove", "Pommeroeul", "Pondrôme", "Pont-de-Loup", "Pont-à-Celles", + "Pontillas", "Poperinge", "Poppel", "Popuelles", "Porcheresse", "Pottes", + "Poucet", "Poulseur", "Poupehan", "Pousset", "Presgaux", "Presles", + "Profondeville", "Proven", "Pry", "Pulderbos", "Pulle", "Purnode", "Pussemange", + "Putte", "Puurs", "Péronnes-lez-Antoing", "Péronnes-lez-Binche", "Péruwelz", + "Quaregnon", "Quartes", "Quenast", "Queue-du-Bois", "Quevaucamps", "Quiévrain", + "Quévy", "Quévy-le-Grand", "Quévy-le-Petit", "Rachecourt", "Racour", "Raeren", + "Ragnies", "Rahier", "Ramegnies", "Ramegnies-Chin", "Ramelot", "Ramillies-Offus", + "Ramsdonk", "Ramsel", "Ramskapelle-Knokke-Heist", "Ramskapelle-Nieuwpoort", + "Rance", "Ransart", "Ransberg", "Ranst", "Ravels", "Rebaix", "Rebecq", + "Rebecq-Rognon", "Recht", "Recogne", "Redu", "Reet", "Rekem", "Rekkem", "Relegem", + "Remagne", "Remersdaal", "Remicourt", "Rendeux", "Reninge", "Reningelst", + "Renlies", "Reppel", "Ressaix", "Ressegem", "Resteigne", "Retie", "Retinne", + "Reuland", "Rhisnes", "Richelle", "Riemst", "Rienne", "Rijkel", "Rijkevorsel", + "Rijkhoven", "Rijmenam", "Riksingen", "Rillaar", "Rivière", "Rixensart", "Rièzes", + "Robechies", "Robelmont", "Robertville", "Roborst", "Rochefort", "Rochehaut", + "Rocherath", "Roclenge-sur-Geer", "Rocourt", "Roesbrugge-Haringe", "Roeselare", + "Rognée", "Roisin", "Roksem", "Rollegem", "Rollegem-Kapelle", "Roloux", "Roly", + "Romedenne", "Romershoven", "Romerée", "Romsée", "Rongy", "Ronquières", "Ronse", + "Ronsele", "Roosbeek", "Roosdaal", "Roselies", "Rosières", "Rosmeer", + "Rosoux-Crenwick", "Rossignol", "Rosée", "Rotem", "Rotheux-Rimière", "Rotselaar", + "Roucourt", "Rouveroy", "Rouvreux", "Rouvroy", "Roux", "Roux-Miroir", "Roy", + "Rozebeke", "Ruddervoorde", "Ruette", "Ruien", "Ruisbroek", "Ruiselede", + "Rukkelingen-Loon", "Rulles", "Rumbeke", "Rumes", "Rumillies", "Rummen", + "Rumsdorp", "Rumst", "Runkelen", "Rupelmonde", "Russeignies", "Rutten", "Rèves", + "Saint-Amand", "Saint-André", "Saint-Aubin", "Saint-Denis", "Saint-Denis-Bovesse", + "Saint-Georges-sur-Meuse", "Saint-Germain", "Saint-Ghislain", "Saint-Gérard", + "Saint-Géry", "Saint-Hubert", "Saint-Jean-Geest", "Saint-Léger", "Saint-Marc", + "Saint-Mard", "Saint-Martin", "Saint-Maur", "Saint-Médard", "Saint-Nicolas", + "Saint-Pierre", "Saint-Remy", "Saint-Remy-Geest", "Saint-Sauveur", + "Saint-Servais", "Saint-Symphorien", "Saint-Séverin", "Saint-Vaast", + "Saint-Vincent", "Sainte-Cécile", "Sainte-Marie-Chevigny", + "Sainte-Marie-sur-Semois", "Sainte-Ode", "Saintes", "Saive", "Salles", "Samart", + "Sambreville", "Samrée", "Sankt-Vith", "Sars-la-Bruyère", "Sars-la-Buissière", + "Sart-Bernard", "Sart-Custinne", "Sart-Dames-Avelines", "Sart-Eustache", + "Sart-Saint-Laurent", "Sart-en-Fagne", "Sart-lez-Spa", "Sautin", "Sautour", + "Sauvenière", "Schaarbeek", "Schaffen", "Schalkhoven", "Schaltin", "Schelderode", + "Scheldewindeke", "Schelle", "Schellebelle", "Schendelbeke", "Schepdaal", + "Scherpenheuvel", "Scherpenheuvel-Zichem", "Schilde", "Schoonaarde", "Schore", + "Schorisse", "Schoten", "Schriek", "Schuiferskapelle", "Schulen", "Schönberg", + "Sclayn", "Scy", "Seilles", "Seloignes", "Semmerzake", "Seneffe", "Sensenruth", + "Seny", "Senzeille", "Septon", "Seraing", "Seraing-le-Château", "Serinchamps", + "Serskamp", "Serville", "Sibret", "Signeulx", "Sijsele", "Silenrieux", "Silly", + "Sinaai-Waas", "Sinsin", "Sint-Agatha-Berchem", "Sint-Agatha-Rode", "Sint-Amands", + "Sint-Amandsberg", "Sint-Andries", "Sint-Antelinks", "Sint-Baafs-Vijve", + "Sint-Blasius-Boekel", "Sint-Denijs", "Sint-Denijs-Boekel", "Sint-Denijs-Westrem", + "Sint-Eloois-Vijve", "Sint-Eloois-Winkel", "Sint-Genesius-Rode", "Sint-Gillis", + "Sint-Gillis-Waas", "Sint-Gillis-bij-Dendermonde", "Sint-Goriks-Oudenhove", + "Sint-Huibrechts-Hern", "Sint-Huibrechts-Lille", "Sint-Jacobs-Kapelle", + "Sint-Jan", "Sint-Jan-in-Eremo", "Sint-Jans-Molenbeek", "Sint-Job-in-'t-Goor", + "Sint-Joost-ten-Node", "Sint-Joris-Beernem", "Sint-Joris-Nieuwpoort", + "Sint-Joris-Weert", "Sint-Joris-Winge", "Sint-Katelijne-Waver", + "Sint-Katherina-Lombeek", "Sint-Kornelis-Horebeke", "Sint-Kruis", + "Sint-Kruis-Winkel", "Sint-Kwintens-Lennik", "Sint-Lambrechts-Herk", + "Sint-Lambrechts-Woluwe", "Sint-Laureins", "Sint-Laureins-Berchem", + "Sint-Lenaarts", "Sint-Lievens-Esse", "Sint-Lievens-Houtem", "Sint-Margriete", + "Sint-Margriete-Houtem", "Sint-Maria-Horebeke", "Sint-Maria-Latem", + "Sint-Maria-Lierde", "Sint-Maria-Oudenhove-Brakel", + "Sint-Maria-Oudenhove-Zottegem", "Sint-Martens-Bodegem", "Sint-Martens-Latem", + "Sint-Martens-Leerne", "Sint-Martens-Lennik", "Sint-Martens-Lierde", + "Sint-Martens-Voeren", "Sint-Michiels", "Sint-Niklaas", "Sint-Pauwels", + "Sint-Pieters-Kapelle", "Sint-Pieters-Leeuw", "Sint-Pieters-Rode", + "Sint-Pieters-Voeren", "Sint-Pieters-Woluwe", "Sint-Rijkers", + "Sint-Stevens-Woluwe", "Sint-Truiden", "Sint-Ulriks-Kapelle", "Sippenaeken", + "Sirault", "Sivry", "Sivry-Rance", "Sleidinge", "Slijpe", "Slins", "Sluizen", + "Smeerebbe-Vloerzegem", "Smetlede", "Smuid", "Snaaskerke", "Snellegem", + "Soheit-Tinlot", "Sohier", "Soignies", "Soiron", "Solre-Saint-Géry", + "Solre-sur-Sambre", "Sombreffe", "Somme-Leuze", "Sommethonne", "Sommière", + "Somzée", "Sorinne-la-Longue", "Sorinnes", "Sorée", "Sosoye", "Sougné-Remouchamps", + "Soulme", "Soumagne", "Soumoy", "Sourbrodt", "Souvret", "Sovet", "Soy", "Soye", + "Spa", "Spalbeek", "Spermalie", "Spiennes", "Spiere", "Spiere-Helkijn", "Spontin", + "Spouwen", "Sprimont", "Spy", "Stabroek", "Staden", "Stalhille", "Stambruges", + "Stave", "Stavele", "Stavelot", "Steendorp", "Steenhuffel", + "Steenhuize-Wijnhuize", "Steenkerke", "Steenkerque", "Steenokkerzeel", "Stekene", + "Stembert", "Stene", "Sterrebeek", "Stevoort", "Stokrooie", "Stoumont", + "Straimont", "Strijpen", "Strijtem", "Strombeek-Bever", "Strée", "Strée-lez-Huy", + "Strépy-Bracquegnies", "Stuivekenskerke", "Suarlée", "Sugny", "Surice", "Suxy", + "Sélange", "Tailles", "Taintignies", "Tamines", "Tarcienne", "Tavier", "Taviers", + "Tavigny", "Tellin", "Templeuve", "Temploux", "Temse", "Tenneville", "Teralfene", + "Terhagen", "Termes", "Ternat", "Tertre", "Tervuren", "Terwagne", "Tessenderlo", + "Testelt", "Teuven", "Theux", "Thiaumont", "Thieu", "Thieulain", "Thieusies", + "Thimister", "Thimister-Clermont", "Thimougies", "Thiméon", "Thines", "Thirimont", + "Thisnes", "Thommen", "Thon", "Thorembais-Saint-Trond", "Thorembais-les-Béguines", + "Thoricourt", "Thuillies", "Thuin", "Thulin", "Thumaide", "Thy-le-Bauduin", + "Thy-le-Château", "Thynes", "Thys", "Tiegem", "Tielen", "Tielrode", "Tielt", + "Tielt-Winge", "Tienen", "Tignée", "Tihange", "Tildonk", "Tilff", "Tillet", + "Tilleur", "Tillier", "Tilly", "Tinlot", "Tintange", "Tintigny", "Tisselt", + "Toernich", "Tohogne", "Tollembeek", "Tongeren", "Tongerlo", "Tongre-Notre-Dame", + "Tongre-Saint-Martin", "Tongrinne", "Tontelange", "Torgny", "Torhout", "Tourinne", + "Tourinnes-Saint-Lambert", "Tournai", "Tournay", "Tourpes", "Transinne", + "Trazegnies", "Treignes", "Trembleur", "Tremelo", "Trivières", "Trognée", + "Trois-Ponts", "Trooz", "Tubize", "Turnhout", "Ucimont", "Uikhoven", "Uitbergen", + "Uitkerke", "Ukkel", "Ulbeek", "Upigny", "Ursel", "Vaalbeek", "Val-Meer", "Vance", + "Varendonk", "Varsenare", "Vaucelles", "Vaulx", "Vaulx-lez-Chimay", + "Vaux-Chavanne", "Vaux-et-Borset", "Vaux-lez-Rosières", "Vaux-sous-Chèvremont", + "Vaux-sur-Sûre", "Vechmaal", "Vedrin", "Veerle", "Velaine-sur-Sambre", "Velaines", + "Veldegem", "Veldwezelt", "Vellereille-le-Sec", "Vellereille-les-Brayeux", "Velm", + "Velroux", "Veltem-Beisem", "Velzeke-Ruddershove", "Vencimont", "Vergnies", + "Verlaine", "Verlée", "Verrebroek", "Vertrijk", "Verviers", "Vesqueville", + "Veulen", "Veurne", "Vezin", "Vezon", "Viane", "Vichte", "Vielsalm", "Viemme", + "Viersel", "Vierset-Barse", "Vierves-sur-Viroin", "Viesville", "Vieux-Genappe", + "Vieux-Waleffe", "Vieuxville", "Villance", "Ville-Pommeroeul", "Ville-en-Hesbaye", + "Ville-sur-Haine", "Villerot", "Villers-Deux-Eglises", "Villers-Notre-Dame", + "Villers-Perwin", "Villers-Poterie", "Villers-Saint-Amand", + "Villers-Saint-Ghislain", "Villers-Saint-Siméon", "Villers-Sainte-Gertrude", + "Villers-aux-Tours", "Villers-devant-Orval", "Villers-en-Fagne", + "Villers-l'Evêque", "Villers-la-Bonne-Eau", "Villers-la-Loue", "Villers-la-Tour", + "Villers-la-Ville", "Villers-le-Bouillet", "Villers-le-Gambon", + "Villers-le-Peuplier", "Villers-le-Temple", "Villers-lez-Heest", + "Villers-sur-Lesse", "Villers-sur-Semois", "Vilvoorde", "Vinalmont", + "Vinderhoute", "Vinkem", "Vinkt", "Virelles", "Virginal-Samme", "Viroinval", + "Virton", "Vissenaken", "Visé", "Vitrival", "Vivegnis", "Vivy", "Vladslo", + "Vlamertinge", "Vlekkem", "Vleteren", "Vlezenbeek", "Vliermaal", "Vliermaalroot", + "Vlierzele", "Vlijtingen", "Vlimmeren", "Vlissegem", "Vloesberg", "Vodecée", + "Vodelée", "Voeren", "Vogenée", "Volkegem", "Vollezele", "Vonêche", "Voorde", + "Voormezele", "Voort", "Voroux-Goreux", "Voroux-lez-Liers", "Vorselaar", "Vorsen", + "Vorst", "Vosselaar", "Vosselare", "Vossem", "Vottem", "Vrasene", "Vremde", + "Vreren", "Vresse-sur-Semois", "Vroenhoven", "Vucht", "Vurste", "Vyle-et-Tharoul", + "Waanrode", "Waarbeke", "Waardamme", "Waarloos", "Waarmaarde", "Waarschoot", + "Waasmont", "Waasmunster", "Waasten", "Wachtebeke", "Wadelincourt", "Wagnelée", + "Waha", "Waillet", "Wakken", "Walcourt", "Walem", "Walhain", "Walhain-Saint-Paul", + "Walhorn", "Walsbets", "Walshoutem", "Waltwilder", "Wambeek", "Wancennes", + "Wandre", "Wanfercée-Baulet", "Wange", "Wangenies", "Wanlin", "Wanne", + "Wannebecq", "Wannegem-Lede", "Wansin", "Wanze", "Wanzele", "Warchin", "Warcoing", + "Wardin", "Waregem", "Waremme", "Waret-l'Evêque", "Waret-la-Chaussée", + "Warisoulx", "Warnant", "Warnant-Dreye", "Warquignies", "Warsage", "Warzée", + "Wasmes", "Wasmes-Audemez-Briffoeil", "Wasmuel", "Wasseiges", "Waterland-Oudeman", + "Waterloo", "Watermaal-Bosvoorde", "Watervliet", "Watou", "Wattripont", "Waudrez", + "Waulsort", "Wauthier-Braine", "Waver", "Wavreille", "Wayaux", "Ways", "Webbekom", + "Wechelderzande", "Weelde", "Weerde", "Weert", "Wegnez", "Weillen", "Weismes", + "Welden", "Welkenraedt", "Welle", "Wellen", "Wellin", "Wemmel", "Wenduine", + "Werbomont", "Werchter", "Werken", "Werm", "Wervik", "Wespelaar", "Westende", + "Westerlo", "Westkapelle", "Westkerke", "Westmalle", "Westmeerbeek", "Westouter", + "Westrem", "Westrozebeke", "Westvleteren", "Wetteren", "Wevelgem", "Wez-Velvain", + "Wezemaal", "Wezembeek-Oppem", "Wezeren", "Wibrin", "Wichelen", "Widooie", + "Wiekevorst", "Wielsbeke", "Wierde", "Wiers", "Wiesme", "Wieze", "Wihogne", + "Wihéries", "Wijchmaal", "Wijer", "Wijgmaal", "Wijnegem", "Wijshagen", + "Wijtschate", "Wilderen", "Willaupuis", "Willebringen", "Willebroek", "Willemeau", + "Willerzie", "Wilrijk", "Wilsele", "Wilskerke", "Wimmertingen", "Winenne", + "Wingene", "Winksele", "Wintershoven", "Witry", "Wodecq", "Woesten", "Wolkrange", + "Wolvertem", "Wommelgem", "Wommersom", "Wonck", "Wondelgem", "Wontergem", + "Wortegem", "Wortegem-Petegem", "Wortel", "Woubrechtegem", "Woumen", "Wulpen", + "Wulvergem", "Wulveringem", "Wuustwezel", "Wépion", "Wéris", "Xhendelesse", + "Xhendremael", "Xhoris", "Yernée-Fraineux", "Yves-Gomezée", "Yvoir", "Zaffelare", + "Zandbergen", "Zande", "Zandhoven", "Zandvliet", "Zandvoorde-Oostende", + "Zandvoorde-Zonnebeke", "Zarlardinge", "Zarren", "Zaventem", "Zedelgem", + "Zeebrugge", "Zegelsem", "Zele", "Zelem", "Zellik", "Zelzate", "Zemst", + "Zepperen", "Zerkegem", "Zevekote", "Zeveneken", "Zeveren", "Zevergem", "Zichem", + "Zichen-Zussen-Bolder", "Zillebeke", "Zingem", "Zoerle-Parwijs", "Zoersel", + "Zolder", "Zomergem", "Zonhoven", "Zonnebeke", "Zonnegem", "Zottegem", + "Zoutenaaie", "Zoutleeuw", "Zuidschote", "Zuienkerke", "Zulte", "Zulzeke", + "Zutendaal", "Zwalm", "Zwevegem", "Zwevezele", "Zwijnaarde", "Zwijndrecht", + "Zétrud-Lumay", "l'Escaillère", + ) + + provinces = ( + "Antwerpen", "Henegouwen", "Limburg", "Luik", "Luxemburg", "Namen", + "Oost-Vlaanderen", "Vlaams-Brabant", "Waals-Brabant", "West-Vlaanderen", + ) + + street_name_formats = ( + '{{first_name}}{{street_suffix}}', + ) + + street_address_formats = ( + '{{street_name}} {{building_number}}', + ) + + address_formats = ( + "{{street_address}}\n{{postcode}}\n{{city}}", + "{{street_address}}\n{{postcode}} {{city}}", + ) + + def province(self): + return self.random_element(self.provinces) + + def city(self): + return self.random_element(self.cities) diff --git a/testbed/joke2k__faker/faker/providers/address/nl_NL/__init__.py b/testbed/joke2k__faker/faker/providers/address/nl_NL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f8962ffb8b2caba5e033ca7749c23cae40efe0d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/nl_NL/__init__.py @@ -0,0 +1,587 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + building_number_formats = ('#', '##', '###', '#', '##', '###') + + street_suffixes = ( + 'baan', 'boulevard', 'dreef', 'hof', 'laan', 'pad', + 'ring', 'singel', 'steeg', 'straat', 'weg', + ) + + # the 4 digit numerical part of Dutch postcodes is between 1000 and 9999; + # see http://nl.wikipedia.org/wiki/Postcode#Postcodes_in_Nederland + postcode_formats = ('%###??', '%### ??') + + city_formats = ('{{city}}',) + + # countries are from http://nl.wikipedia.org/wiki/ISO_3166-1 + countries = ( + 'Afghanistan', 'Albanië', 'Algerije', 'Amerikaans-Samoa', + 'Amerikaanse Maagdeneilanden', 'Andorra', 'Angola', 'Anguilla', + 'Antarctica', 'Antigua en Barbuda', 'Argentinië', 'Armenië', 'Aruba', + 'Australië', 'Azerbeidzjan', "Bahama's", 'Bahrein', 'Bangladesh', + 'Barbados', 'België', 'Belize', 'Benin', 'Bermuda', 'Bhutan', + 'Bolivia', 'Bonaire, Sint Eustatius en Saba', 'Bosnië en Herzegovina', + 'Botswana', 'Bouveteiland', 'Brazilië', + 'Brits Indische Oceaanterritorium', 'Britse Maagdeneilanden', 'Brunei', + 'Bulgarije', 'Burkina Faso', 'Burundi', 'Cambodja', 'Canada', + 'Centraal-Afrikaanse Republiek', 'Chili', 'China', 'Christmaseiland', + 'Cocoseilanden', 'Colombia', 'Comoren', 'Congo-Brazzaville', + 'Congo-Kinshasa', 'Cookeilanden', 'Costa Rica', 'Cuba', 'Curaçao', + 'Cyprus', 'Denemarken', 'Djibouti', 'Dominica', + 'Dominicaanse Republiek', 'Duitsland', 'Ecuador', 'Egypte', + 'El Salvador', 'Equatoriaal-Guinea', 'Eritrea', 'Estland', 'Ethiopië', + 'Faeröer', 'Falklandeilanden', 'Fiji', 'Filipijnen', 'Finland', + 'Frankrijk', 'Frans-Guyana', 'Frans-Polynesië', + 'Franse Zuidelijke en Antarctische Gebieden', 'Gabon', 'Gambia', + 'Georgië', 'Ghana', 'Gibraltar', 'Grenada', 'Griekenland', 'Groenland', + 'Guadeloupe', 'Guam', 'Guatemala', 'Guernsey', 'Guinee', + 'Guinee-Bissau', 'Guyana', 'Haïti', 'Heard en McDonaldeilanden', + 'Honduras', 'Hongarije', 'Hongkong', 'IJsland', 'Ierland', 'India', + 'Indonesië', 'Irak', 'Iran', 'Israël', 'Italië', 'Ivoorkust', + 'Jamaica', 'Japan', 'Jemen', 'Jersey', 'Jordanië', 'Kaaimaneilanden', + 'Kaapverdië', 'Kameroen', 'Kazachstan', 'Kenia', 'Kirgizië', + 'Kiribati', 'Kleine Pacifische eilanden van de Verenigde Staten', + 'Koeweit', 'Kroatië', 'Laos', 'Lesotho', 'Letland', 'Libanon', + 'Liberia', 'Libië', 'Liechtenstein', 'Litouwen', 'Luxemburg', 'Macau', + 'Macedonië', 'Madagaskar', 'Malawi', 'Maldiven', 'Maleisië', 'Mali', + 'Malta', 'Man', 'Marokko', 'Marshalleilanden', 'Martinique', + 'Mauritanië', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia', + 'Moldavië', 'Monaco', 'Mongolië', 'Montenegro', 'Montserrat', + 'Mozambique', 'Myanmar', 'Namibië', 'Nauru', 'Nederland', 'Nepal', + 'Nicaragua', 'Nieuw-Caledonië', 'Nieuw-Zeeland', 'Niger', 'Nigeria', + 'Niue', 'Noord-Korea', 'Noordelijke Marianen', 'Noorwegen', 'Norfolk', + 'Oeganda', 'Oekraïne', 'Oezbekistan', 'Oman', 'Oost-Timor', + 'Oostenrijk', 'Pakistan', 'Palau', 'Palestina', 'Panama', + 'Papoea-Nieuw-Guinea', 'Paraguay', 'Peru', 'Pitcairneilanden', 'Polen', + 'Portugal', 'Puerto Rico', 'Qatar', 'Roemenië', 'Rusland', 'Rwanda', + 'Réunion', 'Saint Kitts en Nevis', 'Saint Lucia', + 'Saint Vincent en de Grenadines', 'Saint-Barthélemy', + 'Saint-Pierre en Miquelon', 'Salomonseilanden', 'Samoa', 'San Marino', + 'Sao Tomé en Principe', 'Saoedi-Arabië', 'Senegal', 'Servië', + 'Seychellen', 'Sierra Leone', 'Singapore', 'Sint Maarten', + 'Sint-Helena, Ascension en Tristan da Cunha', 'Sint-Maarten', + 'Slovenië', 'Slowakije', 'Soedan', 'Somalië', 'Spanje', + 'Spitsbergen en Jan Mayen', 'Sri Lanka', 'Suriname', 'Swaziland', + 'Syrië', 'Tadzjikistan', 'Taiwan', 'Tanzania', 'Thailand', 'Togo', + 'Tokelau', 'Tonga', 'Trinidad en Tobago', 'Tsjaad', 'Tsjechië', + 'Tunesië', 'Turkije', 'Turkmenistan', 'Turks- en Caicoseilanden', + 'Tuvalu', 'Uruguay', 'Vanuatu', 'Vaticaanstad', 'Venezuela', + 'Verenigd Koninkrijk', 'Verenigde Arabische Emiraten', + 'Verenigde Staten', 'Vietnam', 'Wallis en Futuna', 'Westelijke Sahara', + 'Wit-Rusland', 'Zambia', 'Zimbabwe', 'Zuid-Afrika', + 'Zuid-Georgia en de Zuidelijke Sandwicheilanden', 'Zuid-Korea', + 'Zuid-Soedan', 'Zweden', 'Zwitserland', 'Åland', + ) + + # cities are taken from the BAG "woonplaats"; + # in this case the 8-Mar-2014 extract; + # see http://data.nlextract.nl/bag/csv/ + cities = ( + "'s Gravenmoer", "'s-Graveland", "'s-Gravendeel", "'s-Gravenhage", + "'s-Gravenpolder", "'s-Gravenzande", "'s-Heer Abtskerke", + "'s-Heer Arendskerke", "'s-Heer Hendrikskinderen", "'s-Heerenberg", + "'s-Heerenbroek", "'s-Heerenhoek", "'s-Hertogenbosch", "'t Goy", + "'t Haantje", "'t Harde", "'t Loo Oldebroek", "'t Veld", "'t Waar", + "'t Zand", "'t Zandt", '1e Exloërmond', '2e Exloërmond', + '2e Valthermond', 'Aadorp', 'Aagtekerke', 'Aalden', 'Aalsmeer', + 'Aalsmeerderbrug', 'Aalst', 'Aalsum', 'Aalten', 'Aardenburg', + 'Aarlanderveen', 'Aarle-Rixtel', 'Aartswoud', 'Abbega', 'Abbekerk', + 'Abbenbroek', 'Abbenes', 'Abcoude', 'Achlum', 'Achterveld', + 'Achthuizen', 'Achtmaal', 'Acquoy', 'Adorp', 'Aduard', 'Aerdenhout', + 'Aerdt', 'Afferden', 'Afferden L', 'Agelo', 'Akersloot', 'Akkrum', + 'Akmarijp', 'Albergen', 'Alblasserdam', 'Alde Leie', 'Aldeboarn', + 'Aldtsjerk', 'Alem', 'Alkmaar', 'Allingawier', 'Almelo', 'Almen', + 'Almere', 'Almkerk', 'Alphen', 'Alphen aan den Rijn', 'Alteveer', + 'Alteveer gem Hoogeveen', 'Altforst', 'Ambt Delden', 'Ameide', 'Amen', + 'America', 'Amerongen', 'Amersfoort', 'Ammerstol', 'Ammerzoden', + 'Amstelhoek', 'Amstelveen', 'Amstenrade', 'Amsterdam', + 'Amsterdam-Duivendrecht', 'Andel', 'Andelst', 'Anderen', 'Andijk', + 'Ane', 'Anerveen', 'Anevelde', 'Angeren', 'Angerlo', 'Anjum', + 'Ankeveen', 'Anloo', 'Anna Paulowna', 'Annen', 'Annerveenschekanaal', + 'Ansen', 'Apeldoorn', 'Appelscha', 'Appeltern', 'Appingedam', 'Arcen', + 'Arkel', 'Arnemuiden', 'Arnhem', 'Arriën', 'Arum', 'Asch', 'Asperen', + 'Assen', 'Assendelft', 'Asten', 'Augsbuurt', 'Augustinusga', + 'Austerlitz', 'Avenhorn', 'Axel', 'Azewijn', 'Baaiduinen', 'Baaium', + 'Baak', 'Baambrugge', 'Baard', 'Baarland', 'Baarle-Nassau', 'Baarlo', + 'Baarn', 'Baars', 'Babberich', 'Babyloniënbroek', 'Bad Nieuweschans', + 'Badhoevedorp', 'Baexem', 'Baflo', 'Bakel', 'Bakhuizen', 'Bakkeveen', + 'Balgoij', 'Balinge', 'Balk', 'Balkbrug', 'Balloo', 'Balloërveld', + 'Ballum', 'Baneheide', 'Banholt', 'Bant', 'Bantega', 'Barchem', + 'Barendrecht', 'Barger-Compascuum', 'Barneveld', 'Barsingerhorn', + 'Basse', 'Batenburg', 'Bathmen', 'Bavel', 'Bavel AC', 'Bears', 'Bedum', + 'Beegden', 'Beek', 'Beek en Donk', 'Beekbergen', 'Beemte Broekland', + 'Beers NB', 'Beerta', 'Beerze', 'Beerzerveld', 'Beesd', 'Beesel', + 'Beets', 'Beetsterzwaag', 'Beilen', 'Beinsdorp', 'Belfeld', + 'Bellingwolde', 'Belt-Schutsloot', 'Beltrum', 'Bemelen', 'Bemmel', + 'Beneden-Leeuwen', 'Bennebroek', 'Bennekom', 'Benneveld', + 'Benningbroek', 'Benschop', 'Bentelo', 'Benthuizen', 'Bentveld', + 'Berg en Dal', 'Berg en Terblijt', 'Bergambacht', 'Bergeijk', + 'Bergen (NH)', 'Bergen L', 'Bergen aan Zee', 'Bergen op Zoom', + 'Bergentheim', 'Bergharen', 'Berghem', 'Bergschenhoek', 'Beringe', + 'Berkel en Rodenrijs', 'Berkel-Enschot', 'Berkenwoude', 'Berkhout', + 'Berlicum', 'Berltsum', 'Bern', 'Best', 'Beugen', 'Beuningen', + 'Beuningen Gld', 'Beusichem', 'Beutenaken', 'Beverwijk', + 'Biddinghuizen', 'Bierum', 'Biervliet', 'Biest-Houtakker', + 'Biezenmortel', 'Biggekerke', 'Bilthoven', 'Bingelrade', 'Bitgum', + 'Bitgummole', 'Bladel', 'Blankenham', 'Blaricum', 'Blauwestad', + 'Blauwhuis', 'Bleiswijk', 'Blesdijke', 'Bleskensgraaf ca', 'Blessum', + 'Blije', 'Blijham', 'Blitterswijck', 'Bloemendaal', 'Blokker', + 'Blokzijl', 'Boazum', 'Bocholtz', 'Bodegraven', 'Boekel', + 'Boelenslaan', 'Boer', 'Boerakker', 'Boesingheliede', 'Boijl', + 'Boksum', 'Bolsward', 'Bontebok', 'Boornbergum', 'Boornzwaag', + 'Borculo', 'Borger', 'Borgercompagnie', 'Borgsweer', 'Born', 'Borne', + 'Bornerbroek', 'Bornwird', 'Borssele', 'Bosch en Duin', 'Boschoord', + 'Boskoop', 'Bosschenhoofd', 'Botlek Rotterdam', 'Bourtange', + 'Boven-Leeuwen', 'Bovenkarspel', 'Bovensmilde', 'Boxmeer', 'Boxtel', + 'Braamt', 'Brakel', 'Brandwijk', 'Brantgum', 'Breda', 'Bredevoort', + 'Breedenbroek', 'Breezand', 'Breezanddijk', 'Breskens', 'Breukelen', + 'Breukeleveen', 'Brielle', 'Briltil', 'Britsum', 'Britswert', 'Broek', + 'Broek in Waterland', 'Broek op Langedijk', 'Broekhuizen', + 'Broekhuizenvorst', 'Broekland', 'Broeksterwâld', 'Bronkhorst', + 'Bronneger', 'Bronnegerveen', 'Brouwershaven', 'Bruchem', 'Brucht', + 'Bruchterveld', 'Bruinehaar', 'Bruinisse', 'Brummen', 'Brunssum', + 'Bruntinge', 'Buchten', 'Budel', 'Budel-Dorplein', 'Budel-Schoot', + 'Buggenum', 'Buinen', 'Buinerveen', 'Buitenkaag', 'Buitenpost', + 'Bunde', 'Bunne', 'Bunnik', 'Bunschoten-Spakenburg', 'Burdaard', + 'Buren', 'Burgerbrug', 'Burgerveen', 'Burgh-Haamstede', 'Burgum', + 'Burgwerd', 'Burum', 'Bussum', 'Buurmalsen', 'Cadier en Keer', + 'Cadzand', 'Callantsoog', 'Capelle aan den IJssel', 'Castelre', + 'Castenray', 'Casteren', 'Castricum', 'Chaam', 'Clinge', 'Coevorden', + 'Colijnsplaat', 'Collendoorn', 'Colmschate', 'Cornwerd', 'Cothen', + 'Creil', 'Cromvoirt', 'Cruquius', 'Cuijk', 'Culemborg', 'Daarle', + 'Daarlerveen', 'Dalem', 'Dalen', 'Dalerpeel', 'Dalerveen', 'Dalfsen', + 'Dalmsholte', 'Damwâld', 'Darp', 'De Bilt', 'De Blesse', 'De Bult', + 'De Cocksdorp', 'De Falom', 'De Glind', 'De Goorn', 'De Groeve', + 'De Heen', 'De Heurne', 'De Hoeve', 'De Kiel', 'De Klomp', 'De Knipe', + 'De Koog', 'De Krim', 'De Kwakel', 'De Lier', 'De Meern', 'De Moer', + 'De Mortel', 'De Pol', 'De Punt', 'De Rijp', 'De Rips', + 'De Schiphorst', 'De Steeg', 'De Tike', 'De Veenhoop', 'De Waal', + 'De Weere', 'De Westereen', 'De Wilgen', 'De Wilp', 'De Zilk', + 'Dearsum', 'Dedemsvaart', 'Dedgum', 'Deelen', 'Deest', 'Deil', + 'Deinum', 'Delden', 'Delfgauw', 'Delfstrahuizen', 'Delft', 'Delfzijl', + 'Delwijnen', 'Demen', 'Den Andel', 'Den Bommel', 'Den Burg', + 'Den Dolder', 'Den Dungen', 'Den Ham', 'Den Helder', 'Den Hoorn', + 'Den Horn', 'Den Hout', 'Den Ilp', 'Den Oever', 'Den Velde', + 'Denekamp', 'Deurne', 'Deurningen', 'Deursen-Dennenburg', 'Deurze', + 'Deventer', 'Didam', 'Dieden', 'Diemen', 'Diepenheim', 'Diepenveen', + 'Dieren', 'Diessen', 'Diever', 'Dieverbrug', 'Diffelen', 'Dijken', + 'Dinteloord', 'Dinxperlo', 'Diphoorn', 'Dirkshorn', 'Dirksland', + 'Dodewaard', 'Doenrade', 'Doesburg', 'Doetinchem', 'Doeveren', + 'Doezum', 'Dokkum', 'Doldersum', 'Domburg', 'Donderen', 'Dongen', + 'Dongjum', 'Doniaga', 'Donkerbroek', 'Doorn', 'Doornenburg', + 'Doornspijk', 'Doorwerth', 'Dordrecht', 'Dorst', 'Drachten', + 'Drachten-Azeven', 'Drachtstercompagnie', 'Dreischor', 'Drempt', + 'Dreumel', 'Driebergen-Rijsenburg', 'Drieborg', 'Driebruggen', + 'Driehuis NH', 'Driehuizen', 'Driel', 'Driewegen', 'Driezum', + 'Drijber', 'Drimmelen', 'Drogeham', 'Drogteropslagen', 'Drongelen', + 'Dronryp', 'Dronten', 'Drouwen', 'Drouwenermond', 'Drouwenerveen', + 'Drunen', 'Druten', 'Duiven', 'Duivendrecht', 'Duizel', 'Dussen', + 'Dwingeloo', 'Eagum', 'Earnewâld', 'Easterein', 'Easterlittens', + 'Eastermar', 'Easterwierrum', 'Echt', 'Echteld', 'Echten', + 'Echtenerbrug', 'Eck en Wiel', 'Eckelrade', 'Edam', 'Ede', 'Ederveen', + 'Ee', 'Eede', 'Eefde', 'Eelde', 'Eelderwolde', 'Eemdijk', 'Eemnes', + 'Eemshaven', 'Een', 'Een-West', 'Eenrum', 'Eenum', 'Eerbeek', 'Eersel', + 'Ees', 'Eesergroen', 'Eeserveen', 'Eesterga', 'Eesveen', 'Eethen', + 'Eext', 'Eexterveen', 'Eexterveenschekanaal', 'Eexterzandvoort', + 'Egchel', 'Egmond aan Zee', 'Egmond aan den Hoef', 'Egmond-Binnen', + 'Eibergen', 'Eijsden', 'Eindhoven', 'Einighausen', 'Ekehaar', + 'Elahuizen', 'Elburg', 'Eldersloo', 'Eleveld', 'Elim', 'Elkenrade', + 'Ell', 'Ellecom', 'Ellemeet', 'Ellertshaar', 'Ellewoutsdijk', 'Elp', + 'Elsendorp', 'Elshout', 'Elsloo', 'Elspeet', 'Elst', 'Elst Ut', + 'Emmeloord', 'Emmen', 'Emmer-Compascuum', 'Empe', 'Emst', 'Engwierum', + 'Enkhuizen', 'Ens', 'Enschede', 'Enspijk', 'Enter', 'Enumatil', 'Epe', + 'Epen', 'Eppenhuizen', 'Epse', 'Erica', 'Erichem', 'Erlecom', 'Erm', + 'Ermelo', 'Erp', 'Esbeek', 'Esch', 'Escharen', 'Espel', 'Est', 'Etten', + 'Etten-Leur', 'Europoort Rotterdam', 'Eursinge', 'Everdingen', + 'Evertsoord', 'Ewijk', 'Exloo', 'Exloërveen', 'Exmorra', 'Eygelshoven', + 'Eys', 'Ezinge', 'Farmsum', 'Feanwâlden', 'Feerwerd', 'Feinsum', + 'Ferwert', 'Ferwoude', 'Fijnaart', 'Finsterwolde', 'Firdgum', + 'Fleringen', 'Fluitenberg', 'Fochteloo', 'Follega', 'Folsgare', + 'Formerum', 'Foudgum', 'Foxhol', 'Foxwolde', 'Franeker', + 'Frederiksoord', 'Friens', 'Frieschepalen', 'Froombosch', 'Gaanderen', + 'Gaast', 'Gaastmeer', 'Galder', 'Gameren', 'Gapinge', 'Garderen', + 'Garmerwolde', 'Garminge', 'Garnwerd', 'Garrelsweer', 'Garsthuizen', + 'Garyp', 'Gassel', 'Gasselte', 'Gasselternijveen', + 'Gasselternijveenschemond', 'Gastel', 'Gasteren', 'Gauw', 'Geelbroek', + 'Geerdijk', 'Geersdijk', 'Geertruidenberg', 'Geervliet', 'Gees', + 'Geesbrug', 'Geesteren', 'Geeuwenbrug', 'Geffen', 'Geijsteren', + 'Geldermalsen', 'Gelderswoude', 'Geldrop', 'Geleen', 'Gellicum', + 'Gelselaar', 'Gemert', 'Gemonde', 'Genderen', 'Gendringen', 'Gendt', + 'Genemuiden', 'Gennep', 'Gerkesklooster', 'Gersloot', 'Geulle', + 'Giesbeek', 'Giessen', 'Giessenburg', 'Gieten', 'Gieterveen', + 'Giethmen', 'Giethoorn', 'Gilze', 'Ginnum', 'Glane', 'Glimmen', + 'Godlinze', 'Goedereede', 'Goes', 'Goingarijp', 'Goirle', 'Goor', + 'Gorinchem', 'Gorredijk', 'Gorssel', 'Gouda', 'Gouderak', 'Goudriaan', + 'Goudswaard', 'Goutum', 'Goënga', 'Goëngahuizen', 'Graauw', + 'Grafhorst', 'Graft', 'Gramsbergen', 'Grashoek', 'Grathem', 'Grave', + 'Greonterp', 'Grevenbicht', 'Griendtsveen', 'Grijpskerk', + 'Grijpskerke', 'Groede', 'Groenekan', 'Groeningen', 'Groenlo', + 'Groesbeek', 'Groessen', 'Groet', 'Grolloo', 'Groningen', 'Gronsveld', + 'Groot-Ammers', 'Grootebroek', 'Grootegast', 'Grootschermer', 'Grou', + 'Grubbenvorst', 'Gulpen', 'Guttecoven', 'Gytsjerk', 'Haaften', + 'Haaksbergen', 'Haalderen', 'Haaren', 'Haarle', 'Haarlem', + 'Haarlemmerliede', 'Haarlo', 'Haarsteeg', 'Haarzuilens', 'Haastrecht', + 'Haelen', 'Hagestein', 'Haghorst', 'Haler', 'Halfweg', 'Hall', 'Halle', + 'Hallum', 'Halsteren', 'Handel', 'Hank', 'Hansweert', 'Hantum', + 'Hantumeruitburen', 'Hantumhuizen', 'Hapert', 'Haps', 'Harbrinkhoek', + 'Hardenberg', 'Harderwijk', 'Hardinxveld-Giessendam', 'Haren', + 'Haren Gn', 'Harfsen', 'Harich', 'Haringhuizen', 'Harkema', + 'Harkstede', 'Harlingen', 'Harmelen', 'Harreveld', 'Harskamp', + 'Hartwerd', 'Haskerdijken', 'Haskerhorne', 'Hasselt', 'Hattem', + 'Hattemerbroek', 'Haule', 'Haulerwijk', 'Hauwert', 'Havelte', + 'Havelterberg', 'Hazerswoude-Dorp', 'Hazerswoude-Rijndijk', 'Hedel', + 'Hedikhuizen', 'Hee', 'Heeg', 'Heel', 'Heelsum', 'Heelweg', + 'Heemserveen', 'Heemskerk', 'Heemstede', 'Heenvliet', 'Heerde', + 'Heerenveen', 'Heerewaarden', 'Heerhugowaard', 'Heerjansdam', 'Heerle', + 'Heerlen', 'Heesbeen', 'Heesch', 'Heesselt', 'Heeswijk-Dinther', + 'Heeten', 'Heeze', 'Hegebeintum', 'Hegelsom', 'Hei- en Boeicop', + 'Heibloem', 'Heide', 'Heijen', 'Heijenrath', 'Heijningen', 'Heikant', + 'Heilig Landstichting', 'Heiligerlee', 'Heiloo', 'Heinenoord', + 'Heinkenszand', 'Heino', 'Hekelingen', 'Hekendorp', 'Helden', + 'Helenaveen', 'Hellendoorn', 'Hellevoetsluis', 'Hellouw', 'Hellum', + 'Helmond', 'Helvoirt', 'Hem', 'Hemelum', 'Hemmen', 'Hempens', 'Hemrik', + 'Hendrik-Ido-Ambacht', 'Hengelo', 'Hengelo (Gld)', 'Hengevelde', + 'Hengstdijk', 'Hensbroek', 'Herbaijum', 'Herkenbosch', 'Herkingen', + 'Hernen', 'Herpen', 'Herpt', 'Herten', 'Hertme', 'Herveld', 'Herwen', + 'Herwijnen', 'Heteren', 'Heukelom', 'Heukelum', 'Heumen', 'Heusden', + 'Heveadorp', 'Heythuysen', 'Hezingen', 'Hiaure', 'Hichtum', 'Hidaard', + 'Hierden', 'Hieslum', 'Hijken', 'Hijum', 'Hilaard', 'Hillegom', + 'Hilvarenbeek', 'Hilversum', 'Hindeloopen', 'Hinnaard', + 'Hippolytushoef', 'Hitzum', 'Hobrede', 'Hoedekenskerke', 'Hoek', + 'Hoek van Holland', 'Hoenderloo', 'Hoensbroek', 'Hoenzadriel', + 'Hoevelaken', 'Hoeven', 'Hoge Hexel', 'Hollandsche Rading', + 'Hollandscheveld', 'Hollum', 'Holsloot', 'Holten', 'Holthees', + 'Holtheme', 'Holthone', 'Holtum', 'Holwerd', 'Holwierde', 'Hommerts', + 'Homoet', 'Honselersdijk', 'Hoofddorp', 'Hoofdplaat', 'Hoog Soeren', + 'Hoog-Keppel', 'Hoogblokland', 'Hooge Mierde', 'Hooge Zwaluwe', + 'Hoogeloon', 'Hoogenweg', 'Hoogerheide', 'Hoogersmilde', 'Hoogeveen', + 'Hoogezand', 'Hooghalen', 'Hoogkarspel', 'Hoogland', 'Hooglanderveen', + 'Hoogmade', 'Hoogvliet Rotterdam', 'Hoogwoud', 'Hoorn', 'Hoornaar', + 'Hoornsterzwaag', 'Horn', 'Hornhuizen', 'Horssen', 'Horst', 'Houten', + 'Houtigehage', 'Houwerzijl', 'Huijbergen', 'Huis ter Heide', + 'Huisduinen', 'Huisseling', 'Huissen', 'Huizen', 'Huizinge', + 'Hulsberg', 'Hulsel', 'Hulshorst', 'Hulst', 'Hulten', 'Hummelo', + 'Hunsel', 'Hurdegaryp', 'Hurwenen', 'Húns', 'IJhorst', 'IJlst', + 'IJmuiden', 'IJsselham', 'IJsselmuiden', 'IJsselstein', 'IJzendijke', + 'IJzendoorn', 'Idaerd', 'Idsegahuizum', 'Idskenhuizen', 'Idzega', + 'Iens', 'Ilpendam', 'Indijk', 'Ingber', 'Ingelum', 'Ingen', + 'It Heidenskip', 'Itens', 'Ittervoort', 'Jaarsveld', 'Jabeek', + 'Jannum', 'Jellum', 'Jelsum', 'Jirnsum', 'Jislum', 'Jisp', 'Jistrum', + 'Jonkerslân', 'Jonkersvaart', 'Joppe', 'Jorwert', 'Joure', 'Jouswier', + 'Jubbega', 'Julianadorp', 'Jutrijp', 'Kaag', 'Kaard', 'Kaatsheuvel', + 'Kalenberg', 'Kallenkote', 'Kamerik', 'Kampen', 'Kamperland', + 'Kamperveen', 'Kantens', 'Kapel Avezaath', 'Kapel-Avezaath', 'Kapelle', + 'Kapellebrug', 'Katlijk', 'Kats', 'Kattendijke', 'Katwijk', + 'Katwijk NB', 'Katwoude', 'Kedichem', 'Keent', 'Keijenborg', + 'Kekerdom', 'Kelpen-Oler', 'Kerk Avezaath', 'Kerk-Avezaath', + 'Kerkdriel', 'Kerkenveld', 'Kerkrade', 'Kerkwerve', 'Kerkwijk', + 'Kessel', 'Kesteren', 'Kiel-Windeweer', 'Kilder', 'Kimswerd', + 'Kinderdijk', 'Kinnum', 'Klaaswaal', 'Klarenbeek', 'Klazienaveen', + 'Klazienaveen-Noord', 'Klein Zundert', 'Klijndijk', 'Klimmen', + 'Kloetinge', 'Klooster Lidlum', 'Kloosterburen', 'Kloosterhaar', + 'Kloosterzande', 'Klundert', 'Knegsel', 'Koarnjum', 'Kockengen', + 'Koedijk', 'Koekange', 'Koewacht', 'Kolderwolde', 'Kolham', 'Kolhorn', + 'Kollum', 'Kollumerpomp', 'Kollumerzwaag', 'Kommerzijl', + 'Koningsbosch', 'Koningslust', 'Koog aan de Zaan', 'Koolwijk', + 'Kootstertille', 'Kootwijk', 'Kootwijkerbroek', 'Kornhorn', + 'Kornwerderzand', 'Kortehemmen', 'Kortenhoef', 'Kortgene', + 'Koudekerk aan den Rijn', 'Koudekerke', 'Koudum', 'Koufurderrige', + 'Krabbendijke', 'Kraggenburg', 'Kreileroord', 'Krewerd', + 'Krimpen aan de Lek', 'Krimpen aan den IJssel', 'Kring van Dorth', + 'Krommenie', 'Kronenberg', 'Kropswolde', 'Kruiningen', 'Kruisland', + 'Kudelstaart', 'Kuinre', 'Kuitaart', 'Kwadendamme', 'Kwadijk', + 'Kwintsheul', 'Kûbaard', 'Laag Zuthem', 'Laag-Keppel', 'Laag-Soeren', + 'Lage Mierde', 'Lage Vuursche', 'Lage Zwaluwe', 'Lageland', + 'Lambertschaag', 'Lamswaarde', 'Landerum', 'Landgraaf', 'Landhorst', + 'Landsmeer', 'Langbroek', 'Langedijke', 'Langelille', 'Langelo', + 'Langenboom', 'Langerak', 'Langeveen', 'Langeweg', 'Langezwaag', + 'Langweer', 'Laren', 'Lathum', 'Lattrop-Breklenkamp', 'Lauwersoog', + 'Lauwerzijl', 'Ledeacker', 'Leek', 'Leende', 'Leens', 'Leerbroek', + 'Leerdam', 'Leermens', 'Leersum', 'Leeuwarden', 'Legemeer', 'Leiden', + 'Leiderdorp', 'Leidschendam', 'Leimuiden', 'Leimuiderbrug', + 'Lekkerkerk', 'Lekkum', 'Lellens', 'Lelystad', 'Lemele', 'Lemelerveld', + 'Lemiers', 'Lemmer', 'Lengel', 'Lent', 'Leons', 'Lepelstraat', + 'Lettelbert', 'Lettele', 'Leunen', 'Leur', 'Leusden', 'Leuth', + 'Leutingewolde', 'Leuvenheim', 'Leveroy', 'Lewedorp', 'Lexmond', + 'Lichtaard', 'Lichtenvoorde', 'Liempde', 'Lienden', 'Lierderholthuis', + 'Lieren', 'Lierop', 'Lies', 'Lieshout', 'Liessel', 'Lievelde', + 'Lieveren', 'Lijnden', 'Limbricht', 'Limmen', 'Linde', 'Linden', + 'Linne', 'Linschoten', 'Lioessens', 'Lippenhuizen', 'Lisse', + 'Lisserbroek', 'Lith', 'Lithoijen', 'Lobith', 'Lochem', 'Loenen', + 'Loenen aan de Vecht', 'Loenersloot', 'Loerbeek', 'Lollum', 'Lomm', + 'Longerhouw', 'Loo Gld', 'Loon', 'Loon op Zand', 'Loosbroek', + 'Loosdrecht', 'Loozen', 'Lopik', 'Lopikerkapel', 'Loppersum', + 'Losdorp', 'Losser', 'Lottum', 'Loënga', 'Lucaswolde', 'Luddeweer', + 'Luinjeberd', 'Lunteren', 'Lutjebroek', 'Lutjegast', 'Lutjewinkel', + 'Luttelgeest', 'Lutten', 'Luttenberg', 'Luxwoude', 'Luyksgestel', + 'Lytsewierrum', 'Maarheeze', 'Maarn', 'Maarsbergen', 'Maarssen', + 'Maartensdijk', 'Maasbommel', 'Maasbracht', 'Maasbree', 'Maasdam', + 'Maasdijk', 'Maashees', 'Maasland', 'Maassluis', 'Maastricht', + 'Maastricht-Airport', 'Maasvlakte Rotterdam', 'Macharen', 'Made', + 'Makkinga', 'Makkum', 'Malden', 'Mander', 'Manderveen', 'Mantgum', + 'Mantinge', 'Maren-Kessel', 'Margraten', 'Maria Hoop', 'Mariahout', + 'Mariaparochie', 'Marijenkampen', 'Mariënberg', 'Mariënheem', + 'Mariënvelde', 'Markelo', 'Marken', 'Markenbinnen', 'Marknesse', + 'Marle', 'Marrum', 'Marsum', 'Marum', 'Marwijksoord', 'Mastenbroek', + 'Matsloot', 'Maurik', 'Mechelen', 'Medemblik', 'Meeden', 'Meedhuizen', + 'Meerkerk', 'Meerlo', 'Meerssen', 'Meerstad', 'Meeuwen', 'Megchelen', + 'Megen', 'Meijel', 'Melderslo', 'Melick', 'Meliskerke', 'Melissant', + 'Menaam', 'Mensingeweer', 'Meppel', 'Meppen', 'Merkelbeek', 'Merselo', + 'Meteren', 'Meterik', 'Metslawier', 'Mheer', 'Middelaar', 'Middelburg', + 'Middelharnis', 'Middelie', 'Middelstum', 'Middenbeemster', + 'Middenmeer', 'Midlaren', 'Midlum', 'Midsland', 'Midwolda', 'Midwolde', + 'Midwoud', 'Miedum', 'Mierlo', 'Mijdrecht', 'Mijnsheerenland', + 'Mildam', 'Milheeze', 'Mill', 'Millingen aan de Rijn', 'Milsbeek', + 'Minnertsga', 'Mirns', 'Moddergat', 'Moerdijk', 'Moergestel', + 'Moerkapelle', 'Moerstraten', 'Molenaarsgraaf', 'Molenhoek', + 'Molenschot', 'Molkwerum', 'Monnickendam', 'Monster', 'Montfoort', + 'Montfort', 'Mook', 'Mookhoek', 'Moordrecht', 'Moorveld', 'Morra', + 'Muiden', 'Muiderberg', 'Munnekeburen', 'Munnekezijl', 'Munstergeleen', + 'Muntendam', 'Mussel', 'Musselkanaal', 'Mûnein', 'Naaldwijk', + 'Naarden', 'Nagele', 'Nederasselt', 'Nederhemert', + 'Nederhorst den Berg', 'Nederland', 'Nederweert', 'Nederweert-Eind', + 'Neede', 'Neer', 'Neerijnen', 'Neeritter', 'Neerkant', 'Neerlangel', + 'Neerloon', 'Nes', 'Netersel', 'Netterden', 'Niawier', 'Nibbixwoud', + 'Niebert', 'Niehove', 'Niekerk', 'Nietap', 'Nieuw Annerveen', + 'Nieuw Beerta', 'Nieuw Heeten', 'Nieuw Namen', 'Nieuw Scheemda', + 'Nieuw- en Sint Joosland', 'Nieuw-Amsterdam', 'Nieuw-Balinge', + 'Nieuw-Beijerland', 'Nieuw-Buinen', 'Nieuw-Dordrecht', + 'Nieuw-Lekkerland', 'Nieuw-Roden', 'Nieuw-Schoonebeek', 'Nieuw-Vennep', + 'Nieuw-Vossemeer', 'Nieuw-Weerdinge', 'Nieuwaal', 'Nieuwdorp', + 'Nieuwe Niedorp', 'Nieuwe Pekela', 'Nieuwe Wetering', 'Nieuwe-Tonge', + 'Nieuwebrug', 'Nieuwediep', 'Nieuwegein', 'Nieuwehorne', 'Nieuwendijk', + 'Nieuwer Ter Aa', 'Nieuwerbrug aan den Rijn', 'Nieuwerkerk', + 'Nieuwerkerk aan den IJssel', 'Nieuweroord', 'Nieuwersluis', + 'Nieuweschoot', 'Nieuwkoop', 'Nieuwkuijk', 'Nieuwland', 'Nieuwlande', + 'Nieuwlande Coevorden', 'Nieuwleusen', 'Nieuwolda', 'Nieuwpoort', + 'Nieuwstadt', 'Nieuwveen', 'Nieuwvliet', 'Niezijl', 'Niftrik', + 'Nigtevecht', 'Nij Altoenae', 'Nij Beets', 'Nijbroek', 'Nijeberkoop', + 'Nijega', 'Nijehaske', 'Nijeholtpade', 'Nijeholtwolde', 'Nijelamer', + 'Nijemirdum', 'Nijensleek', 'Nijetrijne', 'Nijeveen', 'Nijhuizum', + 'Nijkerk', 'Nijkerkerveen', 'Nijland', 'Nijlande', 'Nijmegen', + 'Nijverdal', 'Nispen', 'Nisse', 'Nistelrode', 'Noardburgum', + 'Nooitgedacht', 'Noorbeek', 'Noord-Scharwoude', 'Noord-Sleen', + 'Noordbeemster', 'Noordbroek', 'Noordeinde', 'Noordeinde Gld', + 'Noordeloos', 'Noorden', 'Noordgouwe', 'Noordhoek', 'Noordhorn', + 'Noordlaren', 'Noordscheschut', 'Noordwelle', 'Noordwijk', + 'Noordwijkerhout', 'Noordwolde', 'Nootdorp', 'Norg', 'Notter', + 'Nuenen', 'Nuis', 'Nuland', 'Numansdorp', 'Nunhem', 'Nunspeet', 'Nuth', + 'Nutter', 'Obbicht', 'Obdam', 'Ochten', 'Odijk', 'Odiliapeel', + 'Odoorn', 'Odoornerveen', 'Oeffelt', 'Oegstgeest', 'Oene', 'Oentsjerk', + 'Offingawier', 'Ohé en Laak', 'Oijen', 'Oirlo', 'Oirsbeek', 'Oirschot', + 'Oisterwijk', 'Okkenbroek', 'Olburgen', 'Oldeberkoop', 'Oldebroek', + 'Oldeholtpade', 'Oldeholtwolde', 'Oldehove', 'Oldekerk', 'Oldelamer', + 'Oldemarkt', 'Oldenzaal', 'Oldenzijl', 'Oldeouwer', 'Oldetrijne', + 'Olst', 'Olterterp', 'Ommel', 'Ommen', 'Ommeren', 'Onderdendam', + 'Onna', 'Onnen', 'Onstwedde', 'Ooij', 'Ooltgensplaat', + 'Oost West en Middelbeers', 'Oost-Graftdijk', 'Oost-Souburg', + 'Oostburg', 'Oostdijk', 'Oosteind', 'Oosterbeek', 'Oosterbierum', + 'Oosterblokker', 'Oosterend', 'Oosterhesselen', 'Oosterhout', + 'Oosterland', 'Oosterleek', 'Oosternieland', 'Oosternijkerk', + 'Oosterstreek', 'Oosterwijk', 'Oosterwijtwerd', 'Oosterwolde', + 'Oosterwolde Gld', 'Oosterzee', 'Oosthem', 'Oosthuizen', 'Oostkapelle', + 'Oostknollendam', 'Oostrum', 'Oostvoorne', 'Oostwold', 'Oostwoud', + 'Oostzaan', 'Ootmarsum', 'Opeinde', 'Opende', 'Ophemert', 'Opheusden', + 'Opijnen', 'Oploo', 'Opmeer', 'Oppenhuizen', 'Opperdoes', 'Oranje', + 'Oranjewoud', 'Orvelte', 'Ospel', 'Oss', 'Ossendrecht', 'Ossenisse', + 'Ossenwaard', 'Ossenzijl', 'Oterleek', 'Otterlo', 'Ottersum', + 'Ottoland', 'Oud Ade', 'Oud Annerveen', 'Oud Gastel', 'Oud Ootmarsum', + 'Oud Zuilen', 'Oud-Alblas', 'Oud-Beijerland', 'Oud-Vossemeer', + 'Ouddorp', 'Oude Meer', 'Oude Niedorp', 'Oude Pekela', 'Oude Wetering', + 'Oude Willem', 'Oude-Tonge', 'Oudebildtzijl', 'Oudega', 'Oudehaske', + 'Oudehorne', 'Oudelande', 'Oudemirdum', 'Oudemolen', 'Oudenbosch', + 'Oudendijk', 'Oudenhoorn', 'Ouderkerk aan de Amstel', + 'Ouderkerk aan den IJssel', 'Oudeschans', 'Oudeschild', 'Oudeschip', + 'Oudeschoot', 'Oudesluis', 'Oudewater', 'Oudezijl', 'Oudheusden', + 'Oudkarspel', 'Oudorp', 'Oudwoude', 'Ouwerkerk', 'Ouwster-Nijega', + 'Ouwsterhaule', 'Overasselt', 'Overberg', 'Overdinkel', 'Overlangel', + 'Overloon', 'Overschild', 'Overslag', 'Overveen', 'Ovezande', + 'Paasloo', 'Paesens', 'Pannerden', 'Panningen', 'Papekop', + 'Papendrecht', 'Papenhoven', 'Papenvoort', 'Parrega', 'Paterswolde', + 'Peest', 'Peins', 'Peize', 'Peperga', 'Pernis Rotterdam', 'Persingen', + 'Pesse', 'Petten', 'Philippine', 'Piaam', 'Piershil', 'Pieterburen', + 'Pietersbierum', 'Pieterzijl', 'Pijnacker', 'Pingjum', 'Plasmolen', + 'Poederoijen', 'Poeldijk', 'Polsbroek', 'Poortugaal', 'Poortvliet', + 'Poppenwier', 'Posterholt', 'Prinsenbeek', 'Puiflijk', 'Punthorst', + 'Purmer', 'Purmerend', 'Purmerland', 'Puth', 'Putte', 'Putten', + 'Puttershoek', 'Raalte', 'Raamsdonk', 'Raamsdonksveer', 'Raard', + 'Radewijk', 'Radio Kootwijk', 'Raerd', 'Randwijk', 'Ransdaal', + 'Rasquert', 'Ravenstein', 'Ravenswaaij', 'Ravenswoud', 'Readtsjerk', + 'Reahûs', 'Reduzum', 'Reek', 'Reeuwijk', 'Reijmerstok', 'Reitsum', + 'Rekken', 'Renesse', 'Renkum', 'Renswoude', 'Ressen', 'Retranchement', + 'Reusel', 'Reutum', 'Reuver', 'Rha', 'Rheden', 'Rhee', 'Rheeze', + 'Rheezerveen', 'Rhenen', 'Rhenoy', 'Rhoon', 'Ridderkerk', 'Ried', + 'Riel', 'Rien', 'Riethoven', 'Rietmolen', 'Rijen', 'Rijkevoort', + 'Rijkevoort-De Walsert', 'Rijnsaterwoude', 'Rijnsburg', 'Rijpwetering', + 'Rijs', 'Rijsbergen', 'Rijsenhout', 'Rijssen', 'Rijswijk', + 'Rijswijk (GLD)', 'Rijswijk (NB)', 'Rilland', 'Rinsumageast', + 'Ritthem', 'Rockanje', 'Roden', 'Roderesch', 'Roderwolde', + 'Roelofarendsveen', 'Roermond', 'Rogat', 'Roggel', 'Rohel', 'Rolde', + 'Roodeschool', 'Roosendaal', 'Roosteren', 'Rosmalen', 'Rossum', + 'Roswinkel', 'Rotstergaast', 'Rotsterhaule', 'Rotterdam', + 'Rotterdam-Albrandswaard', 'Rottevalle', 'Rottum', 'Rouveen', + 'Rozenburg', 'Rozendaal', 'Rucphen', 'Ruigahuizen', 'Ruinen', + 'Ruinerwold', 'Rumpt', 'Rutten', 'Ruurlo', 'Ryptsjerk', 'Saaksum', + 'Saasveld', 'Saaxumhuizen', 'Sambeek', 'Sandfirden', 'Santpoort-Noord', + 'Santpoort-Zuid', 'Sappemeer', 'Sas van Gent', 'Sassenheim', 'Sauwerd', + 'Schagen', 'Schagerbrug', 'Schaijk', 'Schalkhaar', 'Schalkwijk', + 'Schalsum', 'Schardam', 'Scharendijke', 'Scharmer', 'Scharnegoutum', + 'Scharsterbrug', 'Scharwoude', 'Scheemda', 'Scheerwolde', + 'Schellinkhout', 'Schelluinen', 'Schermerhorn', 'Scherpenisse', + 'Scherpenzeel', 'Schettens', 'Scheulder', 'Schiedam', + 'Schiermonnikoog', 'Schijf', 'Schijndel', 'Schildwolde', 'Schimmert', + 'Schin op Geul', 'Schinnen', 'Schinveld', 'Schipborg', 'Schiphol', + 'Schiphol-Rijk', 'Schipluiden', 'Schokland', 'Schoondijke', + 'Schoonebeek', 'Schoonhoven', 'Schoonloo', 'Schoonoord', + 'Schoonrewoerd', 'Schoorl', 'Schore', 'Schouwerzijl', 'Schraard', + 'Schuinesloot', 'Sebaldeburen', 'Sellingen', 'Serooskerke', 'Sevenum', + 'Sexbierum', 'Sibculo', 'Sibrandabuorren', 'Sibrandahûs', 'Siddeburen', + 'Siebengewald', 'Siegerswoude', 'Sijbekarspel', 'Silvolde', + 'Simonshaven', 'Simpelveld', 'Sinderen', 'Sint Agatha', 'Sint Annen', + 'Sint Anthonis', 'Sint Geertruid', 'Sint Hubert', 'Sint Jansklooster', + 'Sint Jansteen', 'Sint Joost', 'Sint Kruis', 'Sint Maarten', + 'Sint Maartensbrug', 'Sint Maartensvlotbrug', 'Sint Nicolaasga', + 'Sint Odiliënberg', 'Sint Pancras', 'Sint Philipsland', + 'Sint-Annaland', 'Sint-Maartensdijk', 'Sint-Michielsgestel', + 'Sint-Oedenrode', 'Sintjohannesga', 'Sirjansland', 'Sittard', + 'Skingen', 'Slagharen', 'Slappeterp', 'Sleen', 'Sleeuwijk', 'Slenaken', + 'Sliedrecht', 'Slijk-Ewijk', 'Slijkenburg', 'Slochteren', 'Slootdorp', + 'Sloten', 'Sluis', 'Sluiskil', 'Smakt', 'Smalle Ee', 'Smallebrugge', + 'Smilde', 'Snakkerburen', 'Sneek', 'Snelrewaard', 'Snikzwaag', + 'Soerendonk', 'Soest', 'Soesterberg', 'Someren', 'Sommelsdijk', + 'Son en Breugel', 'Sondel', 'Sonnega', 'Spaarndam', + 'Spaarndam gem. Haarlem', 'Spanbroek', 'Spanga', 'Spankeren', + 'Spannum', 'Spaubeek', 'Spier', 'Spierdijk', 'Spijk', 'Spijk Gn', + 'Spijkenisse', 'Spijkerboor', 'Sprang-Capelle', 'Sprundel', 'Spui', + 'St. Willebrord', 'St.-Annaparochie', 'St.-Jacobiparochie', + "Stad aan 't Haringvliet", 'Stadskanaal', 'Stampersgat', + 'Standdaarbuiten', 'Staphorst', 'Starnmeer', 'Startenhuizen', + 'Stavenisse', 'Stavoren', 'Stedum', 'Steenbergen', 'Steendam', + 'Steenderen', 'Steenenkamer', 'Steensel', 'Steenwijk', + 'Steenwijkerwold', 'Stegeren', 'Steggerda', 'Stein', 'Stellendam', + 'Sterksel', 'Stevensbeek', 'Stevensweert', 'Steyl', 'Stieltjeskanaal', + 'Stiens', 'Stitswerd', 'Stokkum', 'Stolwijk', 'Stompetoren', + 'Stoutenburg', 'Stoutenburg Noord', 'Stramproy', 'Streefkerk', + 'Striep', 'Strijbeek', 'Strijen', 'Strijensas', 'Stroe', 'Stroobos', + 'Stuifzand', 'Sumar', 'Surhuisterveen', 'Surhuizum', 'Susteren', + 'Suwâld', 'Swalmen', 'Sweikhuizen', 'Swichum', 'Swifterbant', + 'Swolgen', 'Taarlo', 'Teeffelen', 'Teerns', 'Tegelen', 'Ten Boer', + 'Ten Post', 'Ter Aar', 'Ter Aard', 'Ter Apel', 'Ter Apelkanaal', + 'Ter Heijde', 'Ter Idzard', 'Terband', 'Terborg', 'Terheijden', + 'Terherne', 'Terhole', 'Terkaple', 'Termunten', 'Termunterzijl', + 'Ternaard', 'Terneuzen', 'Teroele', 'Terschuur', 'Tersoal', + 'Terwispel', 'Terwolde', 'Teteringen', 'Teuge', 'Thesinge', 'Tholen', + 'Thorn', 'Tiel', 'Tiendeveen', 'Tienhoven', 'Tienray', 'Tijnje', + 'Tilburg', 'Tilligte', 'Tinallinge', 'Tinte', 'Tirns', 'Tjalhuizum', + 'Tjalleberd', 'Tjerkgaast', 'Tjerkwerd', 'Tjuchem', 'Tolbert', + 'Toldijk', 'Tolkamer', 'Tollebeek', 'Tonden', 'Toornwerd', 'Tricht', + 'Triemen', 'Tripscompagnie', 'Tubbergen', 'Tuil', 'Tuitjenhorn', 'Tuk', + "Tull en 't Waal", 'Twello', 'Twijzel', 'Twijzelerheide', 'Twisk', + 'Tynaarlo', 'Tytsjerk', 'Tzum', 'Tzummarum', 'Ubbena', 'Ubbergen', + 'Uddel', 'Uden', 'Udenhout', 'Uffelte', 'Ugchelen', 'Uitdam', + 'Uitgeest', 'Uithoorn', 'Uithuizen', 'Uithuizermeeden', + 'Uitwellingerga', 'Uitwijk', 'Ulestraten', 'Ulft', 'Ulicoten', 'Ulrum', + 'Ulvenhout', 'Ulvenhout AC', 'Ureterp', 'Urk', 'Urmond', 'Ursem', + 'Ursem gem. S', 'Usquert', 'Utrecht', 'Vaals', 'Vaassen', 'Valburg', + 'Valkenburg', 'Valkenswaard', 'Valthe', 'Valthermond', 'Varik', + 'Varsselder', 'Varsseveld', 'Vasse', 'Veelerveen', 'Veen', 'Veendam', + 'Veenendaal', 'Veenhuizen', 'Veeningen', 'Veenklooster', 'Veenoord', + 'Veere', 'Veessen', 'Vegelinsoord', 'Veghel', 'Velddriel', 'Velden', + 'Veldhoven', 'Velp', 'Velsen-Noord', 'Velsen-Zuid', 'Velserbroek', + 'Ven-Zelderheide', 'Venebrugge', 'Venhorst', 'Venhuizen', 'Venlo', + 'Venray', 'Vessem', 'Vethuizen', 'Veulen', 'Vianen', 'Vianen NB', + 'Vierakker', 'Vierhouten', 'Vierhuizen', 'Vierlingsbeek', + 'Vierpolders', 'Vijfhuizen', 'Vijlen', 'Vilsteren', 'Vinkega', + 'Vinkel', 'Vinkenbuurt', 'Vinkeveen', 'Visvliet', 'Vlaardingen', + 'Vlagtwedde', 'Vledder', 'Vledderveen', 'Vleuten', 'Vlieland', + 'Vlierden', 'Vlijmen', 'Vlissingen', 'Vlist', 'Vlodrop', 'Voerendaal', + 'Vogelenzang', 'Vogelwaarde', 'Volendam', 'Volkel', 'Vollenhove', + 'Vondelingenplaat Rotterdam', 'Voorburg', 'Voorhout', 'Voorschoten', + 'Voorst', 'Voorthuizen', 'Vorchten', 'Vorden', 'Vorstenbosch', + 'Vortum-Mullem', 'Vragender', 'Vredenheim', 'Vredepeel', 'Vreeland', + 'Vries', 'Vriescheloo', 'Vriezenveen', 'Vroomshoop', 'Vrouwenakker', + 'Vrouwenparochie', 'Vrouwenpolder', 'Vught', 'Vuren', 'Waaksens', + 'Waal', 'Waalre', 'Waalwijk', 'Waarde', 'Waardenburg', 'Waarder', + 'Waardhuizen', 'Waarland', 'Waaxens', 'Wachtum', 'Waddinxveen', + 'Wadenoijen', 'Wagenberg', 'Wagenborgen', 'Wageningen', 'Walem', + 'Walsoorden', 'Wamel', 'Wanneperveen', 'Wanroij', 'Wanssum', + 'Wapenveld', 'Wapse', 'Wapserveen', 'Warder', 'Warffum', 'Warfhuizen', + 'Warfstermolen', 'Warmenhuizen', 'Warmond', 'Warns', 'Warnsveld', + 'Warstiens', 'Warten', 'Waskemeer', 'Waspik', 'Wassenaar', 'Wateren', + 'Watergang', 'Waterhuizen', 'Wateringen', 'Waterlandkerkje', + 'Waverveen', 'Wedde', 'Weerselo', 'Weert', 'Weesp', 'Wehe-den Hoorn', + 'Wehl', 'Weidum', 'Weiteveen', 'Wekerom', 'Well', 'Well L', + 'Wellerlooi', 'Welsum', 'Wemeldinge', 'Wenum Wiesel', 'Wergea', + 'Werkendam', 'Werkhoven', 'Wernhout', 'Wervershoof', 'Wesepe', + 'Wessem', 'West-Graftdijk', 'West-Terschelling', 'Westbeemster', + 'Westbroek', 'Westdorp', 'Westdorpe', 'Westendorp', 'Westerbeek', + 'Westerbork', 'Westerbroek', 'Westeremden', 'Westergeest', + 'Westerhaar-Vriezenveensewijk', 'Westerhoven', 'Westerland', + 'Westerlee', 'Westernieland', 'Westervelde', 'Westervoort', + 'Westerwijtwerd', 'Westhem', 'Westhoek', 'Westkapelle', + 'Westknollendam', 'Westmaas', 'Westwoud', 'Westzaan', 'Wetering', + 'Weteringbrug', 'Wetsens', 'Wetsinge', 'Weurt', 'Wezep', 'Wezup', + 'Wezuperbrug', 'Wichmond', 'Wier', 'Wierden', 'Wieringerwaard', + 'Wieringerwerf', 'Wierum', 'Wijchen', 'Wijckel', 'Wijdenes', + 'Wijdewormer', 'Wijhe', 'Wijk aan Zee', 'Wijk bij Duurstede', + 'Wijk en Aalburg', 'Wijlre', 'Wijnaldum', 'Wijnandsrade', 'Wijnbergen', + 'Wijngaarden', 'Wijnjewoude', 'Wijster', 'Wilbertoord', 'Wildervank', + 'Wilhelminadorp', 'Wilhelminaoord', 'Willemsoord', 'Willemstad', + 'Wilnis', 'Wilp', 'Wilsum', 'Winde', 'Windraak', 'Winkel', 'Winneweer', + 'Winschoten', 'Winssen', 'Winsum', 'Wintelre', 'Winterswijk', + 'Winterswijk Brinkheurne', 'Winterswijk Corle', 'Winterswijk Henxel', + 'Winterswijk Huppel', 'Winterswijk Kotten', 'Winterswijk Meddo', + 'Winterswijk Miste', 'Winterswijk Ratum', 'Winterswijk Woold', + 'Wirdum', 'Wirdum Gn', 'Wissenkerke', 'Witharen', 'Witmarsum', + 'Witte Paarden', 'Wittelte', 'Wittem', 'Witteveen', 'Wiuwert', + 'Wjelsryp', 'Woensdrecht', 'Woerden', 'Woerdense Verlaat', 'Wognum', + 'Woldendorp', 'Wolfheze', 'Wolphaartsdijk', 'Wolsum', 'Woltersum', + 'Wolvega', 'Wommels', 'Wons', 'Workum', 'Wormer', 'Wormerveer', + 'Woubrugge', 'Woudbloem', 'Woudenberg', 'Woudrichem', 'Woudsend', + 'Wouw', 'Wouwse Plantage', 'Wyns', 'Wytgaard', 'Wâlterswâld', + 'Wânswert', 'Yde', 'Yerseke', 'Ypecolsga', 'Ysbrechtum', 'Ysselsteyn', + 'Zaamslag', 'Zaandam', 'Zaandijk', 'Zalk', 'Zaltbommel', 'Zandberg', + 'Zandeweer', 'Zandhuizen', 'Zandpol', 'Zandvoort', 'Zeddam', 'Zeegse', + 'Zeeland', 'Zeerijp', 'Zeewolde', 'Zegge', 'Zegveld', 'Zeijen', + 'Zeijerveen', 'Zeijerveld', 'Zeist', 'Zelhem', 'Zenderen', + 'Zennewijnen', 'Zetten', 'Zevenaar', 'Zevenbergen', + 'Zevenbergschen Hoek', 'Zevenhoven', 'Zevenhuizen', 'Zierikzee', + 'Zieuwent', 'Zijderveld', 'Zijdewind', 'Zijldijk', 'Zoelen', + 'Zoelmond', 'Zoetermeer', 'Zoeterwoude', 'Zonnemaire', 'Zorgvlied', + 'Zoutelande', 'Zoutkamp', 'Zuid-Beijerland', 'Zuid-Scharwoude', + 'Zuidbroek', 'Zuiddorpe', 'Zuidermeer', 'Zuiderwoude', 'Zuidhorn', + 'Zuidlaarderveen', 'Zuidland', 'Zuidlaren', 'Zuidoostbeemster', + 'Zuidschermer', 'Zuidveen', 'Zuidveld', 'Zuidvelde', 'Zuidwolde', + 'Zuidzande', 'Zuilichem', 'Zuna', 'Zundert', 'Zurich', 'Zutphen', + 'Zuurdijk', 'Zwaag', 'Zwaagdijk-Oost', 'Zwaagdijk-West', 'Zwaanshoek', + 'Zwagerbosch', 'Zwammerdam', 'Zwanenburg', 'Zwartebroek', 'Zwartemeer', + 'Zwartewaal', 'Zwartsluis', 'Zweeloo', 'Zweins', 'Zwiggelte', + 'Zwijndrecht', 'Zwinderen', 'Zwolle', 'de Hoef', 'de Lutte', 'de Wijk', + 'de Woude', + ) + + provinces = ( + 'Drenthe', 'Flevoland', 'Friesland', 'Gelderland', 'Groningen', + 'Limburg', 'Noord-Brabant', 'Noord-Holland', 'Overijssel', 'Utrecht', + 'Zeeland', 'Zuid-Holland', + ) + + street_name_formats = ( + '{{first_name}}{{street_suffix}}', + ) + + street_address_formats = ( + '{{street_name}} {{building_number}}', + ) + + address_formats = ( + "{{street_address}}\n{{postcode}}\n{{city}}", + ) + + def province(self): + return self.random_element(self.provinces) + + def city(self): + return self.random_element(self.cities) diff --git a/testbed/joke2k__faker/faker/providers/address/no_NO/__init__.py b/testbed/joke2k__faker/faker/providers/address/no_NO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a49c7591295ceeba091667eb3a4faebd1993cdbe --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/no_NO/__init__.py @@ -0,0 +1,51 @@ +from collections import OrderedDict + +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_suffixes = ['berg', 'borg', 'by', 'bø', 'dal', 'eid', 'fjell', + 'fjord', 'foss', 'grunn', 'hamn', 'havn', 'helle', 'mark', + 'nes', 'odden', 'sand', 'sjøen', 'stad', 'strand', + 'strøm', 'sund', 'vik', 'vær', 'våg', 'ø', 'øy', 'ås'] + street_suffixes = ['alléen', 'bakken', 'berget', 'bråten', 'eggen', + 'engen', 'ekra', 'faret', 'flata', 'gata', 'gjerdet', + 'grenda', 'gropa', 'hagen', 'haugen', 'havna', 'holtet', + 'høgda', 'jordet', 'kollen', 'kroken', 'lia', 'lunden', + 'lyngen', 'løkka', 'marka', 'moen', 'myra', 'plassen', + 'ringen', 'roa', 'røa', 'skogen', 'skrenten', + 'spranget', 'stien', 'stranda', 'stubben', 'stykket', + 'svingen', 'tjernet', 'toppen', 'tunet', 'vollen', + 'vika', 'åsen'] + city_formats = [ + '{{first_name}}{{city_suffix}}', '{{last_name}}'] + street_name_formats = [ + '{{last_name}}{{street_suffix}}', + ] + street_address_formats = ('{{street_name}} {{building_number}}',) + address_formats = ('{{street_address}}, {{postcode}} {{city}}',) + building_number_formats = ('%', '%', '%', '%?', '##', '##', '##?', '###') + building_number_suffixes = OrderedDict([ + ('A', 0.2), + ('B', 0.2), + ('C', 0.2), + ('D', 0.1), + ('E', 0.1), + ('F', 0.1), + ('G', 0.05), + ('H', 0.05), + ]) + postcode_formats = ('####',) + + def building_number(self): + suffix = self.random_element(self.building_number_suffixes) + return self.numerify( + self.random_element( + self.building_number_formats)).replace( + '?', suffix) + + def city_suffix(self): + return self.random_element(self.city_suffixes) + + def street_suffix(self): + return self.random_element(self.street_suffixes) diff --git a/testbed/joke2k__faker/faker/providers/address/pl_PL/__init__.py b/testbed/joke2k__faker/faker/providers/address/pl_PL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..616c14e3e8c8912b185f695fd36bd10299b126dc --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/pl_PL/__init__.py @@ -0,0 +1,187 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + cities = ( + 'Warszawa', 'Kraków', 'Łódź', 'Wrocław', 'Poznań', 'Gdańsk', + 'Szczecin', + 'Bydgoszcz', 'Lublin', 'Katowice', 'Białystok', 'Gdynia', + 'Częstochowa', 'Radom', 'Sosnowiec', 'Toruń', 'Kielce', 'Gliwice', + 'Rzeszów', 'Zabrze', 'Bytom', 'Olsztyn', 'Bielsko-Biała', + 'Ruda Śląska', + 'Rybnik', 'Tychy', 'Dąbrowa Górnicza', 'Gorzów Wielkopolski', + 'Elbląg', + 'Płock', 'Opole', 'Wałbrzych', 'Zielona Góra', 'Włocławek', 'Tarnów', + 'Chorzów', 'Koszalin', 'Kalisz', 'Legnica', 'Grudziądz', 'Słupsk', + 'Jaworzno', 'Jastrzębie-Zdrój', 'Nowy Sącz', 'Jelenia Góra', 'Konin', + 'Piotrków Trybunalski', 'Siedlce', 'Inowrocław', 'Mysłowice', 'Piła', + 'Lubin', 'Ostrów Wielkopolski', 'Ostrowiec Świętokrzyski', 'Gniezno', + 'Stargard Szczeciński', 'Siemianowice Śląskie', 'Suwałki', 'Głogów', + 'Pabianice', 'Chełm', 'Zamość', 'Tomaszów Mazowiecki', 'Leszno', + 'Przemyśl', 'Stalowa Wola', 'Kędzierzyn-Koźle', 'Łomża', 'Żory', + 'Mielec', 'Tarnowskie Góry', 'Tczew', 'Bełchatów', 'Świdnica', + 'Ełk', 'Pruszków', 'Będzin', 'Biała Podlaska', 'Zgierz', + 'Piekary Śląskie', 'Racibórz', 'Legionowo', 'Ostrołęka', + 'Świętochłowice', 'Starachowice', 'Zawiercie', 'Wejherowo', + 'Puławy', 'Wodzisław Śląski', 'Starogard Gdański', 'Skierniewice', + 'Tarnobrzeg', 'Skarżysko-Kamienna', 'Radomsko', 'Krosno', 'Rumia', + 'Dębica', 'Kołobrzeg', 'Kutno', 'Nysa', 'Ciechanów', 'Otwock', + 'Piaseczno', 'Zduńska Wola', 'Sieradz', 'Świnoujście', 'Żyrardów', + 'Szczecinek', 'Świdnik', 'Chojnice', 'Nowa Sól', 'Oświęcim', + 'Bolesławiec', 'Mińsk Mazowiecki', 'Mikołów', 'Jarosław', 'Sanok', + 'Knurów', 'Malbork', 'Żary', 'Kwidzyn', 'Chrzanów', 'Sopot', + 'Sochaczew', 'Wołomin', 'Oleśnica', 'Brzeg', 'Olkusz', 'Jasło', + 'Cieszyn', 'Kraśnik', 'Lębork', 'Czechowice-Dziedzice', 'Dzierżoniów', + 'Ostróda', 'Police', 'Nowy Targ', 'Iława', 'Czeladź', 'Myszków', + 'Żywiec', 'Zgorzelec', 'Oława', 'Bielawa', 'Swarzędz', 'Mława', + 'Ząbki', 'Łuków', 'Augustów', 'Śrem', 'Bochnia', 'Luboń', 'Giżycko', + 'Grodzisk Mazowiecki', 'Łowicz', 'Krotoszyn', 'Września', + 'Turek', 'Pruszcz Gdański', 'Brodnica', 'Gorlice', + 'Czerwionka-Leszczyny', 'Kłodzko', 'Marki', 'Nowy Dwór Mazowiecki', + 'Kętrzyn', 'Zakopane', 'Wyszków', 'Biłgoraj', 'Żagań', + 'Bielsk Podlaski', 'Świecie', 'Wałcz', 'Jarocin', 'Pszczyna', + 'Wągrowiec', 'Szczytno', 'Białogard', 'Sandomierz', 'Bartoszyce', + 'Kluczbork', 'Lubliniec', 'Skawina', 'Jawor', 'Kościan', 'Wieluń', + 'Kościerzyna', 'Nowa Ruda', 'Świebodzice', 'Koło', 'Piastów', + 'Goleniów', 'Ostrów Mazowiecka', 'Polkowice', 'Lubartów', 'Zambrów', + 'Płońsk', 'Reda', 'Łaziska Górne', 'Środa Wielkopolska', + ) + + street_prefixes = ( + 'ulica', 'aleja', 'plac', + ) + + streets = ( + 'Polna', 'Leśna', 'Słoneczna', 'Krótka', 'Szkolna', 'Ogrodowa', + 'Lipowa', 'Brzozowa', 'Łąkowa', 'Kwiatowa', 'Sosnowa', 'Kościelna', + 'Akacjowa', 'Parkowa', 'Zielona', 'Kolejowa', 'Sportowa', 'Dębowa', + 'Kościuszki', 'Maja', 'Mickiewicza', 'Cicha', 'Spokojna', 'Klonowa', + 'Spacerowa', 'Swierkowa', 'Kasztanowa', 'Nowa', 'Piaskowa', + 'Sienkiewicza', 'Rózana', 'Topolowa', 'Wiśniowa', 'Dworcowa', + 'Wiejska', 'Graniczna', 'Słowackiego', 'Długa', 'Wrzosowa', + 'Konopnickiej', 'Boczna', 'Wąska', 'Wierzbowa', 'Jaśminowa', + 'Wspólna', 'Modrzewiowa', 'Kopernika', 'Jana Pawła II', + 'Poprzeczna', 'Wesoła', 'Pogodna', 'Żeromskiego', 'Rynek', 'Bukowa', + 'Wojska Polskiego', 'Sadowa', 'Górna', 'Jodłowa', 'Wolności', + 'Glówna', 'Młyńska', 'Strażacka', 'Prusa', 'Jesionowa', 'Przemysłowa', + 'Osiedlowa', 'Wiosenna', 'Sikorskiego', 'Chopina', 'Południowa', + 'Malinowa', 'Stawowa', 'Reymonta', 'Piłsudskiego', 'Zacisze', + 'Cmentarna', 'Okrężna', 'Kochanowskiego', 'Armii Krajowej', 'Miła', + 'Jasna', 'Wodna', 'Zamkowa', 'Witosa', 'Reja', 'Warszawska', + 'Miodowa', 'Partyzantów', 'Krzywa', 'Kilińskiego', 'Dolna', + 'Podgórna', 'Kreta', 'Jarzębinowa', 'Moniuszki', 'Targowa', 'Prosta', + 'Orzeszkowej', 'Spółdzielcza', 'Jagodowa', 'Działkowa', 'Staszica', + 'Orzechowa', 'Rzemieślnicza', 'Rzeczna', 'Bolesława Chrobrego', + 'Fabryczna', 'Tęczowa', 'Chabrowa', 'Poziomkowa', 'Konwaliowa', + 'Wyszyńskiego', 'Kalinowa', 'Północna', 'Matejki', 'Grunwaldzka', + 'Cisowa', 'Nadrzeczna', 'Pocztowa', 'Zachodnia', 'Dąbrowskiego', + 'Grabowa', 'Norwida', 'Źródlana', 'Asnyka', 'Gajowa', 'Paderewskiego', + 'Listopada', 'Wyspiańskiego', 'Mostowa', 'Broniewskiego', 'Tuwima', + 'Wschodnia', 'Jaworowa', 'Poznańska', 'Makowa', 'Bema', 'Jeziorna', + 'Piękna', 'Czereśniowa', 'Mała', 'Krakowska', 'Radosna', + 'Leszczynowa', 'Traugutta', 'Jadwigi', 'Rolna', 'Wyzwolenia', + 'Piastowska', 'Grzybowa', 'Krasickiego', 'Podleśna', 'Żytnia', + 'Złota', 'Bursztynowa', 'Żwirowa', 'Stycznia', 'Widokowa', + 'Kazimierza Wielkiego', 'Kamienna', 'Jałowcowa', 'Morelowa', + 'Mieszka I', 'Myśliwska', 'Łączna', 'Szpitalna', 'Wczasowa', + 'Żurawia', 'Fiołkowa', 'Głowackiego', 'Rolnicza', 'Tulipanowa', + 'Władysława Jagiełły', 'Dworska', 'Letnia', 'Liliowa', 'Owocowa', + 'Pułaskiego', 'Stefana Batorego', 'Harcerska', 'Kołłątaja', + 'Strzelecka', 'Kraszewskiego', 'Władysława Łokietka', + 'Żwirki i Wigury', 'Wrocławska', 'Gdańska', 'Turystyczna', + 'Niepodległości', 'Poniatowskiego', 'Korczaka', 'Rybacka', + 'Narutowicza', 'Okrzei', 'Krucza', 'Jagiellońska', 'Świerczewskiego', + 'Kasprowicza', 'Szeroka', 'Jana III Sobieskiego', 'Młynarska', + 'Olchowa', 'Powstańców Śląskich', 'Rumiankowa', 'Stroma', + 'Starowiejska', 'Mazowiecka', + 'Lawendowa', 'Robotnicza', 'Zbożowa', 'Mokra', + 'Powstańców Wielkopolskich', 'Towarowa', 'Dobra', 'Środkowa', + 'Willowa', 'Zielna', 'Zdrojowa', 'Opolska', 'Agrestowa', 'Księżycowa', + 'Zwycięstwa', 'Fredry', 'Letniskowa', 'Andersa', 'Baczynskiego', + 'Batalionów Chłopskich', 'Dąbrowskiej', 'Orla', 'Skłodowskiej-Curie', + 'Błękitna', 'Rubinowa', 'Brzoskwiniowa', 'Urocza', 'Gałczynskiego', + 'Krasińskiego', 'Pomorska', 'Szymanowskiego', 'Jeżynowa', + 'Czarnieckiego', 'Nałkowskiej', 'Zaciszna', 'Porzeczkowa', + 'Krańcowa', 'Jesienna', 'Klasztorna', 'Irysowa', 'Niecała', + 'Wybickiego', 'Nadbrzeżna', 'Szarych Szeregów', 'Wałowa', + 'Słowicza', 'Strumykowa', 'Drzymały', 'Gołębia', 'Torowa', + 'Cegielniana', 'Cyprysowa', 'Słowianska', 'Diamentowa', 'Waryńskiego', + 'Częstochowska', 'Dojazdowa', 'Przechodnia', 'Hallera', 'Lubelska', + 'Plater', 'Popiełuszki', 'Borówkowa', 'Chełmońskiego', 'Daszyńskiego', + 'Plażowa', 'Tartaczna', 'Jabłoniowa', 'Kossaka', 'Skargi', 'Ludowa', + 'Sokola', 'Azaliowa', 'Szmaragdowa', 'Lipca', 'Staffa', 'Tysiąclecia', + 'Brzechwy', 'Jastrzębia', 'Kusocińskiego', 'Storczykowa', 'Wilcza', + 'Górnicza', 'Szafirowa', 'Długosza', 'Handlowa', 'Krokusowa', + 'Składowa', 'Widok', 'Perłowa', 'Skośna', 'Wypoczynkowa', 'Chmielna', + 'Jaskółcza', 'Nowowiejska', 'Piwna', 'Śląska', 'Zaułek', 'Głogowa', + 'Górska', 'Truskawkowa', 'Kaszubska', 'Kosynierów', 'Mazurska', + 'Srebrna', 'Bociania', 'Ptasia', 'Cedrowa', 'Rycerska', + 'Wieniawskiego', 'Żabia', 'Toruńska', 'Podmiejska', 'Słonecznikowa', + 'Sowia', 'Stolarska', 'Powstańców', 'Sucharskiego', + 'Bolesława Krzywoustego', 'Konarskiego', + 'Szczęśliwa', 'Lazurowa', 'Miarki', 'Narcyzowa', 'Browarna', + 'Konstytucji 3 Maja', 'Majowa', 'Miłosza', 'Malczewskiego', 'Orkana', + 'Skrajna', 'Bankowa', 'Bydgoska', 'Piekarska', 'Żeglarska', 'Jana', + 'Turkusowa', 'Tylna', 'Wysoka', 'Zakątek', 'Maczka', 'Morska', + 'Rataja', 'Szewska', 'Podwale', 'Pałacowa', 'Magnoliowa', 'Ceglana', + 'Sawickiej', 'Ściegiennego', 'Wiklinowa', 'Zakole', 'Borowa', + 'Kolorowa', 'Lisia', 'Lotnicza', 'Sarnia', 'Wiązowa', 'Grottgera', + 'Kolonia', 'Królewska', 'Promienna', 'Daleka', 'Jana Sobieskiego', + 'Rejtana', 'Wiatraczna', 'Kaliska', 'Łanowa', 'Średnia', 'Wiślana', + 'Wróblewskiego', 'Koralowa', 'Kruczkowskiego', 'Lelewela', + 'Makuszyńskiego', 'Sybiraków', 'Kowalska', 'Morcinka', 'Odrzańska', + 'Okulickiego', 'Solidarnosci', 'Zapolskiej', 'Łabędzia', 'Wojciecha', + 'Bałtycka', 'Lwowska', 'Rajska', 'Korfantego', 'Pszenna', 'Ciasna', + 'Floriana', 'Hutnicza', 'Kielecka', + ) + + regions = ( + "Dolnośląskie", "Kujawsko - pomorskie", "Lubelskie", "Lubuskie", + "Łódzkie", "Małopolskie", "Mazowieckie", "Opolskie", "Podkarpackie", + "Podlaskie", "Pomorskie", "Śląskie", "Świętokrzyskie", + "Warmińsko - mazurskie", "Wielkopolskie", "Zachodniopomorskie", + ) + + building_number_formats = ('##', '###', "##/##") + postcode_formats = ('##-###',) + street_address_formats = ( + '{{street_prefix}} {{street_name}} {{building_number}}', + '{{street_prefix_short}} {{street_name}} {{building_number}}', + ) + address_formats = ( + "{{street_address}}\n{{postcode}} {{city}}", + ) + + def street_prefix(self): + """ + Randomly returns a street prefix + :example 'aleja' + """ + return self.random_element(self.street_prefixes) + + def street_prefix_short(self): + """ + Randomly returns an abbreviation of the street prefix. + :example 'al.' + """ + return self.random_element(self.street_prefixes)[:2] + '.' + + def street_name(self): + """ + Randomly returns a street name + :example 'Wróblewskiego' + """ + return self.random_element(self.streets) + + def city(self): + """ + Randomly returns a street name + :example 'Konin' + """ + return self.random_element(self.cities) + + def region(self): + """ + :example 'Wielkopolskie' + """ + return self.random_element(self.regions) diff --git a/testbed/joke2k__faker/faker/providers/address/pt_BR/__init__.py b/testbed/joke2k__faker/faker/providers/address/pt_BR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dacd633f8d6d28ec4887f343943274d8fb634d36 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/pt_BR/__init__.py @@ -0,0 +1,307 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_suffixes = ( + 'do Sul', + 'do Norte', + 'de Minas', + 'do Campo', + 'Grande', + 'da Serra', + 'do Oeste', + 'de Goiás', + 'Paulista', + 'da Mata', + 'Alegre', + 'da Praia', + 'das Flores', + 'das Pedras', + 'dos Dourados', + 'do Amparo', + 'do Galho', + 'da Prata', + 'Verde') + street_prefixes = ( + 'Aeroporto', + 'Alameda', + 'Área', + 'Avenida', + 'Campo', + 'Chácara', + 'Colônia', + 'Condomínio', + 'Conjunto', + 'Distrito', + 'Esplanada', + 'Estação', + 'Estrada', + 'Favela', + 'Fazenda', + 'Feira', + 'Jardim', + 'Ladeira', + 'Lago', + 'Lagoa', + 'Largo', + 'Loteamento', + 'Morro', + 'Núcleo', + 'Parque', + 'Passarela', + 'Pátio', + 'Praça', + 'Praia', + 'Quadra', + 'Recanto', + 'Residencial', + 'Rodovia', + 'Rua', + 'Setor', + 'Sítio', + 'Travessa', + 'Trecho', + 'Trevo', + 'Vale', + 'Vereda', + 'Via', + 'Viaduto', + 'Viela', + 'Vila') + city_formats = ( + '{{last_name}}', + '{{last_name}}', + '{{last_name}}', + '{{last_name}}', + '{{last_name}} {{city_suffix}}', + '{{last_name}} {{city_suffix}}', + '{{last_name}} {{city_suffix}}', + '{{last_name}} de {{last_name}}', + ) + street_name_formats = ( + '{{street_prefix}} {{last_name}}', + '{{street_prefix}} {{first_name}} {{last_name}}', + '{{street_prefix}} de {{last_name}}', + ) + + street_address_formats = ( + '{{street_name}}', + '{{street_name}}, {{building_number}}', + '{{street_name}}, {{building_number}}', + '{{street_name}}, {{building_number}}', + '{{street_name}}, {{building_number}}', + '{{street_name}}, {{building_number}}', + '{{street_name}}, {{building_number}}', + ) + + address_formats = ( + "{{street_address}}\n{{bairro}}\n{{postcode}} {{city}} / {{estado_sigla}}", ) + + building_number_formats = ('%', '%#', '%#', '%#', '%##') + + postcode_formats = ('########', '#####-###') + + bairros = ( + 'Aarão Reis', 'Acaba Mundo', 'Acaiaca', 'Ademar Maldonado', 'Aeroporto', 'Aguas Claras', 'Alípio De Melo', + 'Alpes', + 'Alta Tensão 1ª Seção', 'Alta Tensão 2ª Seção', 'Alto Caiçaras', 'Alto Das Antenas', 'Alto Dos Pinheiros', + 'Alto Vera Cruz', + 'Álvaro Camargos', 'Ambrosina', 'Andiroba', 'Antonio Ribeiro De Abreu 1ª Seção', 'Aparecida 7ª Seção', 'Ápia', + 'Apolonia', 'Araguaia', 'Atila De Paiva', 'Bacurau', 'Bairro Das Indústrias Ii', 'Baleia', + 'Barão Homem De Melo 1ª Seção', 'Barão Homem De Melo 2ª Seção', 'Barão Homem De Melo 3ª Seção', + 'Barreiro', 'Beija Flor', 'Beira Linha', 'Bela Vitoria', 'Belmonte', 'Bernadete', 'Betânia', 'Biquinhas', + 'Boa Esperança', 'Boa União 1ª Seção', 'Boa União 2ª Seção', 'Boa Viagem', 'Boa Vista', 'Bom Jesus', 'Bonfim', + 'Bonsucesso', 'Brasil Industrial', 'Braúnas', 'Buraco Quente', 'Cabana Do Pai Tomás', + 'Cachoeirinha', 'Caetano Furquim', 'Caiçara - Adelaide', 'Calafate', 'Califórnia', 'Camargos', 'Campo Alegre', + 'Camponesa 1ª Seção', 'Camponesa 2ª Seção', 'Canaa', 'Canadá', 'Candelaria', 'Capitão Eduardo', 'Cardoso', + 'Casa Branca', 'Castanheira', 'Cdi Jatoba', 'Cenaculo', 'Céu Azul', 'Chácara Leonina', + 'Cidade Jardim Taquaril', 'Cinquentenário', 'Colégio Batista', 'Comiteco', 'Concórdia', + 'Cônego Pinheiro 1ª Seção', + 'Cônego Pinheiro 2ª Seção', 'Confisco', 'Conjunto Bonsucesso', 'Conjunto Califórnia I', + 'Conjunto Califórnia Ii', + 'Conjunto Capitão Eduardo', 'Conjunto Celso Machado', 'Conjunto Floramar', + 'Conjunto Jardim Filadélfia', 'Conjunto Jatoba', 'Conjunto Lagoa', 'Conjunto Minas Caixa', + 'Conjunto Novo Dom Bosco', 'Conjunto Paulo Vi', 'Conjunto Providencia', 'Conjunto Santa Maria', + 'Conjunto São Francisco De Assis', 'Conjunto Serra Verde', 'Conjunto Taquaril', 'Copacabana', 'Coqueiros', + 'Corumbiara', + 'Custodinha', 'Das Industrias I', 'Delta', 'Diamante', 'Distrito Industrial Do Jatoba', 'Dom Bosco', + 'Dom Cabral', + 'Dom Joaquim', 'Dom Silverio', 'Dona Clara', 'Embaúbas', 'Engenho Nogueira', 'Ermelinda', 'Ernesto Nascimento', + 'Esperança', 'Estrela', 'Estrela Do Oriente', 'Etelvina Carneiro', 'Europa', + 'Eymard', 'Fazendinha', 'Flamengo', 'Flavio De Oliveira', 'Flavio Marques Lisboa', 'Floramar', 'Frei Leopoldo', + 'Gameleira', 'Garças', 'Glória', 'Goiania', 'Graça', 'Granja De Freitas', 'Granja Werneck', 'Grota', 'Grotinha', + 'Guarani', 'Guaratã', 'Havaí', 'Heliopolis', 'Horto Florestal', 'Inconfidência', + 'Indaiá', 'Independência', 'Ipe', 'Itapoa', 'Itatiaia', 'Jaqueline', 'Jaraguá', 'Jardim Alvorada', + 'Jardim Atlântico', 'Jardim Do Vale', 'Jardim Dos Comerciarios', 'Jardim Felicidade', 'Jardim Guanabara', + 'Jardim Leblon', 'Jardim Montanhês', 'Jardim São José', 'Jardim Vitoria', 'Jardinópolis', 'Jatobá', + 'João Alfredo', 'João Paulo Ii', 'Jonas Veiga', 'Juliana', 'Lagoa', 'Lagoinha', 'Lagoinha Leblon', 'Lajedo', + 'Laranjeiras', 'Leonina', 'Leticia', 'Liberdade', 'Lindéia', 'Lorena', 'Madre Gertrudes', 'Madri', + 'Mala E Cuia', + 'Manacas', 'Mangueiras', 'Mantiqueira', 'Marajó', 'Maravilha', 'Marçola', 'Maria Goretti', + 'Maria Helena', 'Maria Tereza', 'Maria Virgínia', 'Mariano De Abreu', 'Marieta 1ª Seção', 'Marieta 2ª Seção', + 'Marieta 3ª Seção', 'Marilandia', 'Mariquinhas', 'Marmiteiros', 'Milionario', 'Minas Brasil', 'Minas Caixa', + 'Minaslandia', 'Mineirão', 'Miramar', 'Mirante', 'Mirtes', 'Monsenhor Messias', 'Monte Azul', + 'Monte São José', 'Morro Dos Macacos', 'Nazare', 'Nossa Senhora Aparecida', 'Nossa Senhora Da Aparecida', + 'Nossa Senhora Da Conceição', 'Nossa Senhora De Fátima', 'Nossa Senhora Do Rosário', 'Nova America', + 'Nova Cachoeirinha', 'Nova Cintra', 'Nova Esperança', 'Nova Floresta', 'Nova Gameleira', 'Nova Pampulha', + 'Novo Aarão Reis', 'Novo Das Industrias', 'Novo Glória', 'Novo Santa Cecilia', 'Novo Tupi', 'Oeste', 'Olaria', + "Olhos D'água", 'Ouro Minas', 'Pantanal', 'Paquetá', 'Paraíso', 'Parque São José', 'Parque São Pedro', + 'Paulo Vi', + 'Pedreira Padro Lopes', 'Penha', 'Petropolis', 'Pilar', 'Pindorama', 'Pindura Saia', + 'Piraja', 'Piratininga', 'Pirineus', 'Pompéia', 'Pongelupe', 'Pousada Santo Antonio', 'Primeiro De Maio', + 'Providencia', 'Ribeiro De Abreu', 'Rio Branco', 'Salgado Filho', 'Santa Amelia', 'Santa Branca', + 'Santa Cecilia', + 'Santa Cruz', 'Santa Helena', 'Santa Inês', 'Santa Isabel', 'Santa Margarida', 'Santa Maria', + 'Santa Rita', 'Santa Rita De Cássia', 'Santa Sofia', 'Santa Terezinha', 'Santana Do Cafezal', 'Santo André', + 'São Benedito', 'São Bernardo', 'São Cristóvão', 'São Damião', 'São Francisco', 'São Francisco Das Chagas', + 'São Gabriel', 'São Geraldo', 'São Gonçalo', 'São João', 'São João Batista', 'São Jorge 1ª Seção', + 'São Jorge 2ª Seção', 'São Jorge 3ª Seção', 'São José', 'São Marcos', 'São Paulo', 'São Salvador', + 'São Sebastião', + 'São Tomaz', 'São Vicente', 'Satelite', 'Saudade', 'Senhor Dos Passos', 'Serra Do Curral', 'Serra Verde', + 'Serrano', + 'Solar Do Barreiro', 'Solimoes', 'Sport Club', 'Suzana', 'Taquaril', + 'Teixeira Dias', 'Tiradentes', 'Tirol', 'Tres Marias', 'Trevo', 'Túnel De Ibirité', 'Tupi A', 'Tupi B', 'União', + 'Unidas', 'Universitário', 'Universo', 'Urca', 'Vale Do Jatoba', 'Varzea Da Palma', 'Venda Nova', 'Ventosa', + 'Vera Cruz', 'Vila Aeroporto', 'Vila Aeroporto Jaraguá', 'Vila Antena', 'Vila Antena Montanhês', + 'Vila Atila De Paiva', 'Vila Bandeirantes', 'Vila Barragem Santa Lúcia', 'Vila Batik', 'Vila Betânia', + 'Vila Boa Vista', 'Vila Calafate', 'Vila Califórnia', 'Vila Canto Do Sabiá', 'Vila Cemig', 'Vila Cloris', + 'Vila Copacabana', 'Vila Copasa', 'Vila Coqueiral', 'Vila Da Amizade', 'Vila Da Ária', 'Vila Da Luz', + 'Vila Da Paz', 'Vila Das Oliveiras', 'Vila Do Pombal', 'Vila Dos Anjos', 'Vila Ecológica', + 'Vila Engenho Nogueira', + 'Vila Esplanada', 'Vila Formosa', 'Vila Fumec', 'Vila Havaí', 'Vila Independencia 1ª Seção', + 'Vila Independencia 2ª Seção', 'Vila Independencia 3ª Seção', 'Vila Inestan', 'Vila Ipiranga', + 'Vila Jardim Alvorada', 'Vila Jardim Leblon', 'Vila Jardim São José', 'Vila Madre Gertrudes 1ª Seção', + 'Vila Madre Gertrudes 2ª Seção', 'Vila Madre Gertrudes 3ª Seção', 'Vila Madre Gertrudes 4ª Seção', + 'Vila Maloca', + 'Vila Mangueiras', 'Vila Mantiqueira', 'Vila Maria', 'Vila Minaslandia', 'Vila Nossa Senhora Do Rosário', + 'Vila Nova', 'Vila Nova Cachoeirinha 1ª Seção', 'Vila Nova Cachoeirinha 2ª Seção', + 'Vila Nova Cachoeirinha 3ª Seção', 'Vila Nova Dos Milionarios', 'Vila Nova Gameleira 1ª Seção', + 'Vila Nova Gameleira 2ª Seção', 'Vila Nova Gameleira 3ª Seção', 'Vila Nova Paraíso', 'Vila Novo São Lucas', + 'Vila Oeste', "Vila Olhos D'água", + 'Vila Ouro Minas', 'Vila Paquetá', 'Vila Paraíso', 'Vila Petropolis', 'Vila Pilar', 'Vila Pinho', + 'Vila Piratininga', 'Vila Piratininga Venda Nova', 'Vila Primeiro De Maio', 'Vila Puc', 'Vila Real 1ª Seção', + 'Vila Real 2ª Seção', 'Vila Rica', 'Vila Santa Monica 1ª Seção', 'Vila Santa Monica 2ª Seção', + 'Vila Santa Rosa', + 'Vila Santo Antônio', 'Vila Santo Antônio Barroquinha', 'Vila São Dimas', 'Vila São Francisco', + 'Vila São Gabriel', + 'Vila São Gabriel Jacui', 'Vila São Geraldo', 'Vila São João Batista', 'Vila São Paulo', 'Vila São Rafael', + 'Vila Satélite', 'Vila Sesc', 'Vila Sumaré', 'Vila Suzana Primeira Seção', 'Vila Suzana Segunda Seção', + 'Vila Tirol', 'Vila Trinta E Um De Março', 'Vila União', 'Vila Vista Alegre', 'Virgínia', 'Vista Alegre', + 'Vista Do Sol', 'Vitoria', 'Vitoria Da Conquista', 'Xangri-Lá', 'Xodo-Marize', 'Zilah Sposito', 'Outro', + 'Novo São Lucas', 'Esplanada', 'Estoril', 'Novo Ouro Preto', 'Ouro Preto', 'Padre Eustáquio', 'Palmares', + 'Palmeiras', 'Vila De Sá', 'Floresta', 'Anchieta', 'Aparecida', 'Grajaú', 'Planalto', 'Bandeirantes', + 'Gutierrez', + 'Jardim América', 'Renascença', 'Barro Preto', 'Barroca', 'Sagrada Família', 'Ipiranga', 'Belvedere', + 'Santa Efigênia', 'Santa Lúcia', 'Santa Monica', 'Vila Jardim Montanhes', 'Santa Rosa', 'Santa Tereza', + 'Buritis', 'Vila Paris', 'Santo Agostinho', 'Santo Antônio', 'Caiçaras', 'São Bento', 'Prado', 'Lourdes', + 'Fernão Dias', 'Carlos Prates', 'Carmo', 'Luxemburgo', 'São Lucas', 'São Luiz', 'Mangabeiras', 'São Pedro', + 'Horto', + 'Cidade Jardim', 'Castelo', 'Cidade Nova', 'Savassi', 'Serra', 'Silveira', 'Sion', 'Centro', + 'Alto Barroca', 'Nova Vista', 'Coração De Jesus', 'Coração Eucarístico', 'Funcionários', 'Cruzeiro', + 'João Pinheiro', 'Nova Granada', 'Nova Suíça', 'Itaipu', + ) + countries = ( + 'Afeganistão', 'África do Sul', 'Akrotiri', 'Albânia', 'Alemanha', 'Andorra', 'Angola', 'Anguila', + 'Antártica', 'Antígua e Barbuda', 'Antilhas Holandesas', 'Arábia Saudita', 'Argélia', 'Argentina', + 'Armênia', 'Aruba', 'Ashmore and Cartier Islands', 'Austrália', 'Áustria', 'Azerbaijão', 'Bahamas', + 'Bangladesh', 'Barbados', 'Barein', 'Bélgica', 'Belize', 'Benim', 'Bermudas', 'Bielorrússia', + 'Birmânia', 'Bolívia', 'Bósnia e Herzegovina', 'Botsuana', 'Brasil', 'Brunei', 'Bulgária', + 'Burquina Faso', 'Burundi', 'Butão', 'Cabo Verde', 'Camarões', 'Camboja', 'Canadá', 'Catar', + 'Cazaquistão', 'Chade', 'Chile', 'China', 'Chipre', 'Clipperton Island', 'Colômbia', 'Comores', + 'Congo-Brazzaville', 'Congo-Kinshasa', 'Coral Sea Islands', 'Coreia do Norte', 'Coreia do Sul', + 'Costa do Marfim', 'Costa Rica', 'Croácia', 'Cuba', 'Dhekelia', 'Dinamarca', 'Domínica', 'Egito', + 'Costa do Marfim', 'Costa Rica', 'Croácia', 'Cuba', 'Dhekelia', 'Dinamarca', 'Domínica', 'Egito', + 'Emirados Árabes Unidos', 'Equador', 'Eritreia', 'Eslováquia', 'Eslovênia', 'Espanha', + 'Estados Unidos', + 'Estônia', 'Etiópia', 'Faroé', 'Fiji', 'Filipinas', 'Finlândia', 'França', 'Gabão', 'Gâmbia', 'Gana', + 'Geórgia', 'Geórgia do Sul e Sandwich do Sul', 'Gibraltar', 'Granada', 'Grécia', 'Gronelândia', + 'Guam', 'Guatemala', 'Guernsey', 'Guiana', 'Guiné', 'Guiné Equatorial', 'Guiné-Bissau', 'Haiti', + 'Honduras', 'Hong Kong', 'Hungria', 'Iêmen', 'Ilha Bouvet', 'Ilha do Natal', 'Ilha Norfolk', + 'Ilhas Caiman', 'Ilhas Cook', 'Ilhas dos Cocos', 'Ilhas Falkland', 'Ilhas Heard e McDonald', + 'Ilhas Marshall', 'Ilhas Salomão', 'Ilhas Turcas e Caicos', 'Ilhas Virgens Americanas', + 'Ilhas Virgens Britânicas', 'Índia', 'Indonésia', 'Iran', 'Iraque', 'Irlanda', 'Islândia', 'Israel', + 'Itália', 'Jamaica', 'Jan Mayen', 'Japão', 'Jersey', 'Jibuti', 'Jordânia', 'Kuwait', 'Laos', 'Lesoto', + 'Letônia', 'Líbano', 'Libéria', 'Líbia', 'Liechtenstein', 'Lituânia', 'Luxemburgo', 'Macau', + 'Macedônia', + 'Madagáscar', 'Malásia', 'Malávi', 'Maldivas', 'Mali', 'Malta', 'Man, Isle of', 'Marianas do Norte', + 'Marrocos', 'Maurícia', 'Mauritânia', 'Mayotte', 'México', 'Micronésia', 'Moçambique', 'Moldávia', + 'Mônaco', 'Mongólia', 'Monserrate', 'Montenegro', 'Namíbia', 'Nauru', 'Navassa Island', 'Nepal', + 'Nicarágua', 'Níger', 'Nigéria', 'Niue', 'Noruega', 'Nova Caledónia', 'Nova Zelândia', 'Omã', + 'Países Baixos', 'Palau', 'Panamá', 'Papua-Nova Guiné', 'Paquistão', 'Paracel Islands', 'Paraguai', + 'Peru', 'Pitcairn', 'Polinésia Francesa', 'Polônia', 'Porto Rico', 'Portugal', 'Quênia', + 'Quirguizistão', + 'Quiribáti', 'Reino Unido', 'República Centro-Africana', 'República Checa', 'República Dominicana', + 'Roménia', 'Ruanda', 'Rússia', 'Salvador', 'Samoa', 'Samoa Americana', 'Santa Helena', 'Santa Lúcia', + 'São Cristóvão e Neves', 'São Marinho', 'São Pedro e Miquelon', 'São Tomé e Príncipe', + 'São Vicente e Granadinas', 'Sara Ocidental', 'Seicheles', 'Senegal', 'Serra Leoa', 'Sérvia', + 'Singapura', 'Síria', 'Somália', 'Sri Lanka', 'Suazilândia', 'Sudão', 'Suécia', 'Suíça', 'Suriname', + 'Svalbard e Jan Mayen', 'Tailândia', 'Taiwan', 'Tajiquistão', 'Tanzânia', + 'Território Britânico do Oceano Índico', + 'Territórios Austrais Franceses', 'Timor Leste', 'Togo', 'Tokelau', 'Tonga', 'Trindade e Tobago', + 'Tunísia', 'Turquemenistão', 'Turquia', 'Tuvalu', 'Ucrânia', 'Uganda', 'União Europeia', 'Uruguai', + 'Usbequistão', 'Vanuatu', 'Vaticano', 'Venezuela', 'Vietnam', 'Wake Island', 'Wallis e Futuna', + 'Zâmbia', 'Zimbabué', + ) + + estados = ( + ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', + 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), + ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', + 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), + ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', + 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), + ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', + 'Piauí'), ('RJ', 'Rio de Janeiro'), + ('RN', 'Rio Grande do Norte'), + ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', + 'Roraima'), ('SC', 'Santa Catarina'), + ('SP', 'São Paulo'), + ('SE', 'Sergipe'), ('TO', 'Tocantins'), + ) + + def street_prefix(self): + """ + :example 'rua' + """ + return self.random_element(self.street_prefixes) + + def estado(self): + """ + Randomly returns a Brazilian State ('sigla' , 'nome'). + :example ('MG' . 'Minas Gerais') + """ + return self.random_element(self.estados) + + def estado_nome(self): + """ + Randomly returns a Brazilian State Name + :example 'Minas Gerais' + """ + return self.estado()[1] + + def estado_sigla(self): + """ + Randomly returns the abbreviation of a Brazilian State + + :example 'MG' + """ + return self.estado()[0] + + def bairro(self): + """ + Randomly returns a bairro (neighborhood) name. + The names were taken from the city of Belo Horizonte - Minas Gerais + + :example 'Serra' + """ + return self.random_element(self.bairros) + + # aliases + def neighborhood(self): + return self.bairro() + + def state(self): + return self.estado_nome() + + def state_abbr(self): + return self.estado_sigla() diff --git a/testbed/joke2k__faker/faker/providers/address/pt_PT/__init__.py b/testbed/joke2k__faker/faker/providers/address/pt_PT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7929b845326d7eac19acd4f3547093d6efd05e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/pt_PT/__init__.py @@ -0,0 +1,297 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + street_prefixes = ('Av', 'Avenida', 'R.', 'Rua', 'Travessa', 'Largo') + + city_formats = ('{{city_name}}',) + street_name_formats = ( + '{{street_prefix}} {{last_name}}', + '{{street_prefix}} {{first_name}} {{last_name}}', + '{{street_prefix}} de {{last_name}}', + ) + + street_address_formats = ( + '{{street_name}}, {{building_number}}', + ) + + address_formats = ( + "{{street_address}}\n{{postcode}} {{city}}", + ) + + building_number_formats = ('S/N', '%', '%#', '%#', '%#', '%##') + + postcode_formats = ('####-###',) + + cities = ( + 'Abrantes', 'Agualva-Cacém', 'Albufeira', 'Alcobaça', 'Alcácer do Sal', + 'Almada', 'Almeirim', 'Alverca do Ribatejo', 'Amadora', 'Amarante', + 'Amora', 'Anadia', 'Angra do Heroísmo', 'Aveiro', 'Barcelos', + 'Barreiro', 'Beja', 'Braga', 'Bragança', 'Caldas da Rainha', 'Caniço', + 'Cantanhede', 'Cartaxo', 'Castelo Branco', 'Chaves', 'Coimbra', + 'Costa da Caparica', 'Covilhã', 'Câmara de Lobos', 'Elvas', + 'Entroncamento', 'Ermesinde', 'Esmoriz', 'Espinho', 'Esposende', + 'Estarreja', 'Estremoz', 'Fafe', 'Faro', 'Felgueiras', + 'Figueira da Foz', 'Fiães', 'Freamunde', 'Funchal', 'Fundão', 'Fátima', + 'Gafanha da Nazaré', 'Gandra', 'Gondomar', 'Gouveia', 'Guarda', + 'Guimarães', 'Horta', 'Lagoa', 'Lagos', 'Lamego', 'Leiria', 'Lisboa', + 'Lixa', 'Loulé', 'Loures', 'Lourosa', 'Macedo de Cavaleiros', 'Maia', + 'Mangualde', 'Marco de Canaveses', 'Marinha Grande', 'Matosinhos', + 'Mealhada', 'Miranda do Douro', 'Mirandela', 'Montemor-o-Novo', + 'Montijo', 'Moura', 'Mêda', 'Odivelas', 'Olhão', 'Oliveira de Azeméis', + 'Oliveira do Bairro', 'Oliveira do Hospital', 'Ourém', 'Ovar', + 'Paredes', 'Paços de Ferreira', 'Penafiel', 'Peniche', 'Peso da Régua', + 'Pinhel', 'Pombal', 'Ponta Delgada', 'Ponte de Sor', 'Portalegre', + 'Portimão', 'Porto', 'Porto Santo', 'Praia da Vitória', + 'Póvoa de Santa Iria', 'Póvoa de Varzim', 'Quarteira', 'Queluz', + 'Rebordosa', 'Reguengos de Monsaraz', 'Ribeira Grande', 'Rio Maior', + 'Rio Tinto', 'Sabugal', 'Sacavém', 'Santa Comba Dão', 'Santa Cruz', + 'Santa Maria da Feira', 'Santana', 'Santarém', 'Santiago do Cacém', + 'Santo Tirso', 'Seia', 'Seixal', 'Serpa', 'Setúbal', 'Silves', 'Sines', + 'Sintra', 'São João da Madeira', 'São Mamede de Infesta', + 'São Salvador de Lordelo', 'Tarouca', 'Tavira', 'Tomar', 'Tondela', + 'Torres Novas', 'Torres Vedras', 'Trancoso', 'Trofa', 'Valbom', + 'Vale de Cambra', 'Valongo', 'Valpaços', 'Vendas Novas', + 'Viana do Castelo', 'Vila Franca de Xira', 'Vila Nova de Famalicão', + 'Vila Nova de Foz Côa', 'Vila Nova de Gaia', 'Vila Nova de Santo André', + 'Vila Real', 'Vila Real de Santo António', 'Vila do Conde', 'Viseu', + 'Vizela', 'Évora', 'Ílhavo', + ) + + countries = ( + 'Afeganistão', 'África do Sul', 'Akrotiri', 'Albânia', 'Alemanha', + 'Andorra', 'Angola', 'Anguila', 'Antárctida', 'Antígua e Barbuda', + 'Antilhas Neerlandesas', 'Arábia Saudita', 'Arctic Ocean', 'Argélia', + 'Argentina', 'Arménia', 'Aruba', 'Ashmore and Cartier Islands', + 'Atlantic Ocean', 'Austrália', 'Áustria', 'Azerbaijão', 'Baamas', + 'Bangladeche', 'Barbados', 'Barém', 'Bélgica', 'Belize', 'Benim', + 'Bermudas', 'Bielorrússia', 'Birmânia', 'Bolívia', + 'Bósnia e Herzegovina', 'Botsuana', 'Brasil', 'Brunei', 'Bulgária', + 'Burquina Faso', 'Burúndi', 'Butão', 'Cabo Verde', 'Camarões', + 'Camboja', 'Canadá', 'Catar', 'Cazaquistão', 'Chade', 'Chile', 'China', + 'Chipre', 'Clipperton Island', 'Colômbia', 'Comores', + 'Congo-Brazzaville', 'Congo-Kinshasa', 'Coral Sea Islands', + 'Coreia do Norte', 'Coreia do Sul', 'Costa do Marfim', 'Costa Rica', + 'Croácia', 'Cuba', 'Dhekelia', 'Dinamarca', 'Domínica', 'Egipto', + 'Emiratos Árabes Unidos', 'Equador', 'Eritreia', 'Eslováquia', + 'Eslovénia', 'Espanha', 'Estados Unidos', 'Estónia', 'Etiópia', 'Faroé', + 'Fiji', 'Filipinas', 'Finlândia', 'França', 'Gabão', 'Gâmbia', 'Gana', + 'Gaza Strip', 'Geórgia', 'Geórgia do Sul e Sandwich do Sul', + 'Gibraltar', 'Granada', 'Grécia', 'Gronelândia', 'Guame', 'Guatemala', + 'Guernsey', 'Guiana', 'Guiné', 'Guiné Equatorial', 'Guiné-Bissau', + 'Haiti', 'Honduras', 'Hong Kong', 'Hungria', 'Iémen', 'Ilha Bouvet', + 'Ilha do Natal', 'Ilha Norfolk', 'Ilhas Caimão', 'Ilhas Cook', + 'Ilhas dos Cocos', 'Ilhas Falkland', 'Ilhas Heard e McDonald', + 'Ilhas Marshall', 'Ilhas Salomão', 'Ilhas Turcas e Caicos', + 'Ilhas Virgens Americanas', 'Ilhas Virgens Britânicas', 'Índia', + 'Indian Ocean', 'Indonésia', 'Irão', 'Iraque', 'Irlanda', 'Islândia', + 'Israel', 'Itália', 'Jamaica', 'Jan Mayen', 'Japão', 'Jersey', 'Jibuti', + 'Jordânia', 'Kuwait', 'Laos', 'Lesoto', 'Letónia', 'Líbano', 'Libéria', + 'Líbia', 'Listenstaine', 'Lituânia', 'Luxemburgo', 'Macau', 'Macedónia', + 'Madagáscar', 'Malásia', 'Malávi', 'Maldivas', 'Mali', 'Malta', + 'Man, Isle of', 'Marianas do Norte', 'Marrocos', 'Maurícia', + 'Mauritânia', 'Mayotte', 'México', 'Micronésia', 'Moçambique', + 'Moldávia', 'Mónaco', 'Mongólia', 'Monserrate', 'Montenegro', 'Mundo', + 'Namíbia', 'Nauru', 'Navassa Island', 'Nepal', 'Nicarágua', 'Níger', + 'Nigéria', 'Niue', 'Noruega', 'Nova Caledónia', 'Nova Zelândia', 'Omã', + 'Pacific Ocean', 'Países Baixos', 'Palau', 'Panamá', 'Papua-Nova Guiné', + 'Paquistão', 'Paracel Islands', 'Paraguai', 'Peru', 'Pitcairn', + 'Polinésia Francesa', 'Polónia', 'Porto Rico', 'Portugal', 'Quénia', + 'Quirguizistão', 'Quiribáti', 'Reino Unido', + 'República Centro-Africana', 'República Checa', 'República Dominicana', + 'Roménia', 'Ruanda', 'Rússia', 'Salvador', 'Samoa', 'Samoa Americana', + 'Santa Helena', 'Santa Lúcia', 'São Cristóvão e Neves', 'São Marinho', + 'São Pedro e Miquelon', 'São Tomé e Príncipe', + 'São Vicente e Granadinas', 'Sara Ocidental', 'Seicheles', 'Senegal', + 'Serra Leoa', 'Sérvia', 'Singapura', 'Síria', 'Somália', + 'Southern Ocean', 'Spratly Islands', 'Sri Lanca', 'Suazilândia', + 'Sudão', 'Suécia', 'Suíça', 'Suriname', 'Svalbard e Jan Mayen', + 'Tailândia', 'Taiwan', 'Tajiquistão', 'Tanzânia', + 'Território Britânico do Oceano Índico', + 'Territórios Austrais Franceses', 'Timor Leste', 'Togo', 'Tokelau', + 'Tonga', 'Trindade e Tobago', 'Tunísia', 'Turquemenistão', 'Turquia', + 'Tuvalu', 'Ucrânia', 'Uganda', 'União Europeia', 'Uruguai', + 'Usbequistão', 'Vanuatu', 'Vaticano', 'Venezuela', 'Vietname', + 'Wake Island', 'Wallis e Futuna', 'West Bank', 'Zâmbia', 'Zimbabué', + ) + + # From https://pt.wikipedia.org/wiki/Distritos_de_Portugal + distritos = ( + 'Aveiro', 'Beja', 'Braga', 'Bragança', 'Castelo Branco', 'Coimbra', + 'Évora', 'Faro', 'Guarda', 'Leiria', 'Lisboa', 'Portalegre', 'Porto', + 'Santarém', 'Setúbal', 'Viana do Castelo', 'Vila Real', 'Viseu', + ) + + # From https://pt.wikipedia.org/wiki/Lista_de_concelhos_por_NUTS,_distritos_e_ilhas + concelhos = ( + "Águeda", "Aguiar da Beira", "Alandroal", "Albergaria-a-Velha", "Albufeira", + "Alcácer do Sal", "Alcanena", "Alcobaça", "Alcochete", "Alcoutim", "Alenquer", + "Alfândega da Fé", "Alijó", "Aljezur", "Aljustrel", "Almada", "Almeida", "Almeirim", + "Almodôvar", "Alpiarça", "Alter do Chão", "Alvaiázere", "Alvito", "Amadora", + "Amarante", "Amares", "Anadia", "Angra do Heroísmo", "Ansião", + "Arcos de Valdevez", "Arganil", "Armamar", "Arouca", "Arraiolos", + "Arronches", "Arruda dos Vinhos", "Aveiro", "Avis", "Azambuja", + "Baião", "Barcelos", "Barrancos", "Barreiro", "Batalha", "Beja", + "Belmonte", "Benavente", "Bombarral", "Borba", "Boticas", "Braga", + "Bragança", "Cabeceiras de Basto", "Cadaval", "Caldas da Rainha", + "Calheta (R.A.A.)", "Calheta (R.A.M.)", "Câmara de Lobos", "Caminha", + "Campo Maior", "Cantanhede", "Carrazeda de Ansiães", "Carregal do Sal", + "Cartaxo", "Cascais", "Castanheira de Pêra", "Castelo Branco", + "Castelo de Paiva", "Castelo de Vide", "Castro Daire", "Castro Marim", + "Castro Verde", "Celorico da Beira", "Celorico de Basto", "Chamusca", + "Chaves", "Cinfães", "Coimbra", "Condeixa-a-Nova", "Constância", + "Coruche", "Corvo", "Covilhã", "Crato", "Cuba", "Elvas", + "Entroncamento", "Espinho", "Esposende", "Estarreja", "Estremoz", + "Évora", "Fafe", "Faro", "Felgueiras", "Ferreira do Alentejo", + "Ferreira do Zêzere", "Figueira da Foz", "Figueira de Castelo Rodrigo", + "Figueiró dos Vinhos", "Fornos de Algodres", "Freixo de Espada à Cinta", + "Fronteira", "Funchal", "Fundão", "Gavião", "Góis", "Golegã", "Gondomar", + "Gouveia", "Grândola", "Guarda", "Guimarães", "Horta", "Idanha-a-Nova", + "Ílhavo", "Lagoa", "Lagoa (R.A.A)", "Lagos", "Lajes das Flores", + "Lajes do Pico", "Lamego", "Leiria", "Lisboa", "Loulé", "Loures", + "Lourinhã", "Lousã", "Lousada", "Mação", "Macedo de Cavaleiros", + "Machico", "Madalena", "Mafra", "Maia", "Mangualde", "Manteigas", + "Marco de Canaveses", "Marinha Grande", "Marvão", "Matosinhos", + "Mealhada", "Meda", "Melgaço", "Mértola", "Mesão Frio", "Mira", + "Miranda do Corvo", "Miranda do Douro", "Mirandela", "Mogadouro", + "Moimenta da Beira", "Moita", "Monção", "Monchique", "Mondim de Basto", + "Monforte", "Montalegre", "Montemor-o-Novo", "Montemor-o-Velho", "Montijo", + "Mora", "Mortágua", "Moura", "Mourão", "Murça", "Murtosa", "Nazaré", + "Nelas", "Nisa", "Nordeste", "Óbidos", "Odemira", "Odivelas", "Oeiras", + "Oleiros", "Olhão", "Oliveira de Azeméis", "Oliveira de Frades", + "Oliveira do Bairro", "Oliveira do Hospital", "Ourém", "Ourique", "Ovar", + "Paços de Ferreira", "Palmela", "Pampilhosa da Serra", "Paredes", + "Paredes de Coura", "Pedrógão Grande", "Penacova", "Penafiel", + "Penalva do Castelo", "Penamacor", "Penedono", "Penela", "Peniche", + "Peso da Régua", "Pinhel", "Pombal", "Ponta Delgada", "Ponta do Sol", + "Ponte da Barca", "Ponte de Lima", "Ponte de Sor", "Portalegre", "Portel", + "Portimão", "Porto", "Porto de Mós", "Porto Moniz", "Porto Santo", + "Povoação", "Póvoa de Lanhoso", "Póvoa de Varzim", "Proença-a-Nova", + "Redondo", "Reguengos de Monsaraz", "Resende", "Ribeira Brava", + "Ribeira de Pena", "Ribeira Grande", "Rio Maior", "Sabrosa", + "Sabugal", "Salvaterra de Magos", "Santa Comba Dão", "Santa Cruz", + "Santa Cruz da Graciosa", "Santa Cruz das Flores", "Santa Maria da Feira", + "Santa Marta de Penaguião", "Santana", "Santarém", "Santiago do Cacém", + "Santo Tirso", "São Brás de Alportel", "São João da Madeira", + "São João da Pesqueira", "São Pedro do Sul", "São Roque do Pico", + "São Vicente", "Sardoal", "Sátão", "Seia", "Seixal", "Sernancelhe", + "Serpa", "Sertã", "Sesimbra", "Setúbal", "Sever do Vouga", "Silves", + "Sines", "Sintra", "Sobral de Monte Agraço", "Soure", "Sousel", + "Tábua", "Tabuaço", "Tarouca", "Tavira", "Terras de Bouro", + "Tomar", "Tondela", "Torre de Moncorvo", "Torres Novas", + "Torres Vedras", "Trancoso", "Trofa", "Vagos", "Vale de Cambra", + "Valença", "Valongo", "Valpaços", "Velas", "Vendas Novas", + "Viana do Alentejo", "Viana do Castelo", "Vidigueira", + "Vieira do Minho", "Vila da Praia da Vitória", "Vila de Rei", + "Vila do Bispo", "Vila do Conde", "Vila do Porto", "Vila Flor", + "Vila Franca de Xira", "Vila Franca do Campo", "Vila Nova da Barquinha", + "Vila Nova de Cerveira", "Vila Nova de Famalicão", "Vila Nova de Foz Côa", + "Vila Nova de Gaia", "Vila Nova de Paiva", "Vila Nova de Poiares", + "Vila Pouca de Aguiar", "Vila Real", "Vila Real de Santo António", + "Vila Velha de Ródão", "Vila Verde", "Vila Viçosa", "Vimioso", + "Vinhais", "Viseu", "Vizela", "Vouzela", + ) + + # From https://pt.wikipedia.org/wiki/Lista_de_freguesias_de_Portugal + freguesias = [ + "Abrantes", "Águeda", "Aguiar da Beira", "Alandroal", + "Albergaria-a-Velha", "Albufeira", "Alcácer do Sal", "Alcanena", + "Alcobaça", "Alcochete", "Alcoutim", "Alenquer", "Alfândega da Fé", + "Alijó", "Aljezur", "Aljustrel", "Almada", "Almeida", "Almeirim", + "Almodôvar", "Alpiarça", "Alter do Chão", "Alvaiázere", "Alvito", + "Amadora", "Amarante", "Amares", "Anadia", "Angra do Heroísmo", + "Ansião", "Arcos de Valdevez", "Arganil", "Armamar", "Arouca", + "Arraiolos", "Arronches", "Arruda dos Vinhos", "Aveiro", "Avis", + "Azambuja", "Baião", "Barcelos", "Barrancos", "Barreiro", "Batalha", + "Beja", "Belmonte", "Benavente", "Bombarral", "Borba", "Boticas", + "Braga", "Bragança", "Cabeceiras de Basto", "Cadaval", + "Caldas da Rainha", "Calheta (Açores)", "Calheta (Madeira)", + "Câmara de Lobos", "Caminha", "Campo Maior", "Cantanhede", + "Carrazeda de Ansiães", "Carregal do Sal", "Cartaxo", "Cascais", + "Castanheira de Pêra", "Castelo Branco", "Castelo de Paiva", + "Castelo de Vide", "Castro Daire", "Castro Marim", "Castro Verde", + "Celorico da Beira", "Celorico de Basto", "Chamusca", "Chaves", + "Cinfães", "Coimbra", "Condeixa-a-Nova", "Constância", "Coruche", + "Corvo", "Covilhã", "Crato", "Cuba", "Elvas", "Entroncamento", + "Espinho", "Esposende", "Estarreja", "Estremoz", "Évora", "Fafe", + "Faro", "Felgueiras", "Ferreira do Alentejo", "Ferreira do Zêzere", + "Figueira da Foz", "Figueira de Castelo Rodrigo", + "Figueiró dos Vinhos", "Fornos de Algodres", + "Freixo de Espada à Cinta", "Fronteira", "Funchal", "Fundão", "Gavião", + "Góis", "Golegã", "Gondomar", "Gouveia", "Grândola", "Guarda", + "Guimarães", "Horta", "Idanha-a-Nova", "Ílhavo", "Lagoa", + "Lagoa (Açores)", "Lagos", "Lajes das Flores", "Lajes do Pico", + "Lamego", "Leiria", "Lisboa", "Loulé", "Loures", "Lourinhã", "Lousã", + "Lousada", "Mação", "Macedo de Cavaleiros", "Machico", "Madalena", + "Mafra", "Maia", "Mangualde", "Manteigas", "Marco de Canaveses", + "Marinha Grande", "Marvão", "Matosinhos", "Mealhada", "Mêda", + "Melgaço", "Mértola", "Mesão Frio", "Mira", "Miranda do Corvo", + "Miranda do Douro", "Mirandela", "Mogadouro", "Moimenta da Beira", + "Moita", "Monção", "Monchique", "Mondim de Basto", "Monforte", + "Montalegre", "Montemor-o-Novo", "Montemor-o-Velho", "Montijo", + "Mora", "Mortágua", "Moura", "Mourão", "Murça", "Murtosa", "Nazaré", + "Nelas", "Nisa", "Nordeste", "Óbidos", "Odemira", "Odivelas", + "Oeiras", "Oleiros", "Olhão", "Oliveira de Azeméis", + "Oliveira de Frades", "Oliveira do Bairro", "Oliveira do Hospital", + "Ourém", "Ourique", "Ovar", "Paços de Ferreira", "Palmela", + "Pampilhosa da Serra", "Paredes", "Paredes de Coura", "Pedrógão Grande", + "Penacova", "Penafiel", "Penalva do Castelo", "Penamacor", "Penedono", + "Penela", "Peniche", "Peso da Régua", "Pinhel", "Pombal", + "Ponta Delgada", "Ponta do Sol", "Ponte da Barca", "Ponte de Lima", + "Ponte de Sor", "Portalegre", "Portel", "Portimão", "Porto", + "Porto de Mós", "Porto Moniz", "Porto Santo", "Póvoa de Lanhoso", + "Póvoa de Varzim", "Povoação", "Praia da Vitória", "Proença-a-Nova", + "Redondo", "Reguengos de Monsaraz", "Resende", "Ribeira Brava", + "Ribeira de Pena", "Ribeira Grande", "Rio Maior", "Sabrosa", "Sabugal", + "Salvaterra de Magos", "Santa Comba Dão", "Santa Cruz", + "Santa Cruz da Graciosa", "Santa Cruz das Flores", + "Santa Maria da Feira", "Santa Marta de Penaguião", "Santana", + "Santarém", "Santiago do Cacém", "Santo Tirso", "São Brás de Alportel", + "São João da Madeira", "São João da Pesqueira", "São Pedro do Sul", + "São Roque do Pico", "São Vicente (Madeira)", "Sardoal", "Sátão", + "Seia", "Seixal", "Sernancelhe", "Serpa", "Sertã", "Sesimbra", + "Setúbal", "Sever do Vouga", "Silves", "Sines", "Sintra", + "Sobral de Monte Agraço", "Soure", "Sousel", "Tábua", "Tabuaço", + "Tarouca", "Tavira", "Terras de Bouro", "Tomar", "Tondela", + "Torre de Moncorvo", "Torres Novas", "Torres Vedras", "Trancoso", + "Trofa", "Vagos", "Vale de Cambra", "Valença", "Valongo", "Valpaços", + "Velas", "Vendas Novas", "Viana do Alentejo", "Viana do Castelo", + "Vidigueira", "Vieira do Minho", "Vila de Rei", "Vila do Bispo", + "Vila do Conde", "Vila do Porto", "Vila Flor", "Vila Franca de Xira", + "Vila Franca do Campo", "Vila Nova da Barquinha", + "Vila Nova de Cerveira", "Vila Nova de Famalicão", + "Vila Nova de Foz Côa", "Vila Nova de Gaia", "Vila Nova de Paiva", + "Vila Nova de Poiares", "Vila Pouca de Aguiar", "Vila Real", + "Vila Real de Santo António", "Vila Velha de Ródão", "Vila Verde", + "Vila Viçosa", "Vimioso", "Vinhais", "Viseu", "Vizela", "Vouzela", + ] + + def street_prefix(self): + """ + :example 'Rua' + """ + return self.random_element(self.street_prefixes) + + def city_name(self): + """ + :example 'Amora' + """ + return self.random_element(self.cities) + + def distrito(self): + """ + :example 'Bragança' + """ + return self.random_element(self.distritos) + + def concelho(self): + """ + :example 'Tondela' + """ + return self.random_element(self.concelhos) + + def freguesia(self): + """ + :example 'Miranda do Douro' + """ + return self.random_element(self.freguesias) diff --git a/testbed/joke2k__faker/faker/providers/address/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/address/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bed66a67adb468097c1d5c5a1e36f27b4eb315f9 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/ru_RU/__init__.py @@ -0,0 +1,395 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_suffixes = ('ск', 'вль', 'град', 'поль', 'ин', 'ов', 'бург') + street_suffixes = ('ул.', 'алл.', 'наб.', 'пр.', 'пер.', 'бул.', 'ш.') + region_suffixes = ('респ.', 'обл.', 'край', 'АО') + city_formats = ('{{city_prefix}} {{city_name}}', ) + street_address_formats = ('{{street_name}}, д. {{building_number}}', + '{{street_name}}, д. {{building_number}} к. {{building_number}}', + '{{street_name}}, д. {{building_number}} стр. {{building_number}}') + address_formats = ('{{city}}, {{street_address}}, {{postcode}}', ) + postcode_formats = ('######',) + building_number_formats = ('%##', '%#', '%', '%/%') + + city_prefixes = ('г.', 'п.', 'к.', 'с.', 'д.', 'клх', 'ст.') + + street_suffixes_masc = ('пр.', 'пер.', 'бул.') + street_suffixes_fem = ('ул.', 'алл.', 'наб.') + street_suffixes_neu = ('ш.', ) + + street_titles = ( + 'Советская', 'Молодежная', 'Центральная', 'Школьная', 'Новая', + 'Садовая', 'Лесная', 'Набережная', 'Октябрьская', 'Зеленая', + 'Комсомольская', 'Заречная', 'Первомайская', 'Полевая', 'Луговая', + 'Пионерская', 'Юбилейная', 'Северная', 'Пролетарская', 'Степная', + 'Южная', 'Колхозная', 'Рабочая', 'Солнечная', 'Железнодорожная', + 'Восточная', 'Заводская', 'Нагорная', 'Береговая', 'Кооперативная', + 'Красноармейская', 'Совхозная', 'Речная', 'Спортивная', 'Озерная', + 'Строительная', 'Парковая', 'Подгорная', 'Почтовая', 'Партизанская', + 'Вокзальная', 'Дорожная', 'Дачная', 'Западная', 'Московская', + 'Красная', 'Трудовая', 'Шоссейная', 'Коммунистическая', 'Сосновая', + 'Клубная', 'Березовая', 'Больничная', 'Интернациональная', 'Цветочная', + 'Трактовая', 'Горная', 'Весенняя', 'Коммунальная', 'Майская', + 'Привокзальная', 'Таежная', 'Транспортная', 'Овражная', 'Светлая', + 'Вишневая', 'Ключевая', 'Песчаная', 'Ленинградская', 'Профсоюзная', + 'Верхняя', 'Ленинская', 'Кирпичная', 'Мостовая', 'Станционная', + 'Уральская', 'Линейная', 'Фабричная', 'Магистральная', 'Сибирская', + 'Крестьянская', 'Российская', 'Тихая', 'Широкая', 'Нижняя', + 'Народная', 'Промышленная', 'Кольцевая', 'Дальняя', 'Базарная', + 'Целинная', 'Родниковая', 'Революционная', 'Социалистическая', 'Звездная', + 'Студенческая', 'Мирная', 'Кубанская', 'Гаражная', 'Фестивальная', + 'Гражданская', 'Песочная', 'Сиреневая', 'Сельская', 'Кузнечная', + 'Пушкинская', 'Крайняя', 'Гвардейская', 'Веселая', 'Загородная', + 'Олимпийская', 'Приозерная', 'Рябиновая', 'Заозерная', 'Боровая', + 'Урожайная', 'Торговая', 'Донская', 'Пограничная', 'Огородная', + 'Пригородная', 'Стадионная', 'Виноградная', 'Киевская', 'Индустриальная', + 'Красногвардейская', 'Волжская', 'Свободная', 'Кедровая', 'Подлесная', + 'Полярная', 'Раздольная', 'Карьерная', 'Мельничная', 'Украинская', + 'Шахтерская', 'Запрудная', 'Элеваторная', 'Театральная', 'Геологическая', + 'Болотная', 'Придорожная', 'Кленовая', 'Казачья', 'Малая', + 'Морская', 'Волгоградская', 'Средняя', 'Безымянная', 'Краснофлотская', + 'Братская', 'Тенистая', 'Учительская', 'Кавказская', 'Короткая', + 'Деповская', 'Амурская', 'Сенная', 'Поселковая', 'Прудовая', + 'Депутатская', 'Авиационная', 'Аэродромная', 'Большая', 'Приморская', + 'Алтайская', 'Тополиная', 'Ростовская', 'Тракторная', 'Мелиоративная', + 'Ольховая', 'Славянская', 'Радужная', 'Краснодарская', 'Стахановская', + 'Ярославская', 'Коллективная', 'Ангарская', 'Локомотивная', 'Ягодная', + 'Смоленская', 'Тепличная', 'Водопроводная', 'Республиканская', 'Осенняя', + 'Байкальская', 'Саратовская', 'Казанская', 'Воронежская', 'Брянская', + 'Производственная', 'Техническая', 'Енисейская', 'Севастопольская', 'Окружная', + 'Орловская', 'Хуторская', 'Тупиковая', 'Каштановая', 'Омская', + 'Привольная', 'Курортная', 'Ивановская', 'Выгонная', 'Крымская', + 'Путейская', 'Проезжая', 'Краснознаменная', 'Одесская', 'Логовая', + 'Высокая', 'Ясная', 'Портовая', 'Снежная', 'Санаторная', + 'Союзная', 'Ульяновская', 'Сахалинская', 'Горняцкая', 'Прибрежная', + 'Рыбацкая', 'Полтавская', 'Тамбовская', 'Красноярская', 'Новосельская', + 'Проточная', 'Черноморская', 'Минская', 'Главная', 'Вольная', + 'Хвойная', 'Космическая', 'Моховая', 'Курская', 'Курганная', + 'Угловая', 'Камская', 'Инженерная', 'Лесозаводская', 'Астраханская', + 'Белорусская', 'Заовражная', 'Азовская', 'Ручейная', 'Волочаевская', + 'Ставропольская', 'Слободская', 'Тульская', 'Харьковская', 'Петровская', + 'Владимирская', 'Высоковольтная', 'Лазурная', 'Покровская', 'Новгородская', + 'Ленская', 'Сплавная', 'Ударная', 'Калужская', 'Прудная', + 'Краснопартизанская', 'Ореховая', 'Таманская', 'Иркутская', 'Отрадная', + 'Большевистская', 'Троицкая', 'Лесхозная', 'Васильковая', 'Механическая', + 'Путевая', 'Кузнецкая', 'Физкультурная', 'Черемуховая', 'Флотская', + 'Угольная', 'Просторная', 'Поперечная', 'Городская', 'Абрикосовая', + 'Бульварная', 'Прохладная', 'Томская', 'Энергетическая', 'Литейная', + 'Медицинская', 'Заливная', 'Бригадная', 'Детская', 'Запорожская', + 'Дальневосточная', 'Балтийская', 'Февральская', 'Лунная', 'Высотная', + 'Рязанская', 'Малиновая', + + ) + + street_titles_noflex = ( + 'Ленина', 'Мира', 'Гагарина', 'Кирова', 'Пушкина', 'Калинина', + 'Чапаева', 'Строителей', 'Победы', 'Горького', 'Чкалова', + 'Мичурина', 'Дружбы', 'Лермонтова', 'Свободы', 'Маяковского', + 'Фрунзе', 'Дзержинского', 'Свердлова', 'Некрасова', 'Гоголя', + 'Чехова', 'Труда', 'Комарова', 'Матросова', 'Островского', + 'Куйбышева', 'Крупской', 'Карла Маркса', '8 Марта', 'Суворова', + 'Ломоносова', 'Космонавтов', 'Энергетиков', 'Шевченко', 'Механизаторов', + '40 лет Победы', 'Энгельса', 'Чернышевского', 'Урицкого', 'Ворошилова', + 'Тургенева', 'Толстого', 'Буденного', 'Орджоникидзе', 'Герцена', + 'Щорса', 'Луначарского', 'Энтузиастов', 'Титова', 'Лазо', + '50 лет Октября', 'Пугачева', 'Володарского', 'Кутузова', 'Чайковского', + 'Мелиораторов', 'Новоселов', 'Белинского', 'Тельмана', 'Тимирязева', + 'Котовского', '60 лет Октября', 'Есенина', 'К.Маркса', '40 лет Октября', + 'Крылова', 'Декабристов', '70 лет Октября', 'Фурманова', 'Гайдара', + 'Терешковой', 'Ватутина', 'Коммунаров', 'Гастелло', 'Жданова', + 'Радищева', 'Нефтяников', 'Осипенко', 'Нахимова', 'Жукова', + 'Павлова', 'Степана Разина', 'Попова', 'Жуковского', 'Королева', + 'Грибоедова', 'Менделеева', 'Достоевского', 'Репина', 'Циолковского', + 'Воровского', 'Максима Горького', 'Революции', 'Кошевого', 'Пархоменко', + 'Серова', 'Добролюбова', '50 лет Победы', 'Красина', 'Коминтерна', + '30 лет Победы', 'Разина', 'Черняховского', 'Ветеранов', 'Пирогова', + 'Льва Толстого', 'Геологов', 'Димитрова', 'М.Горького', 'Розы Люксембург', + 'Маркса', 'Ушакова', 'Юности', 'Короленко', 'Шолохова', + '50 лет ВЛКСМ', 'Черемушки', 'Кольцова', 'Плеханова', 'Макаренко', + 'Глинки', 'Специалистов', 'Халтурина', 'Морозова', 'Коммуны', + 'Красных Партизан', 'Зои Космодемьянской', 'Карбышева', 'Баумана', 'Марта 8', + 'Правды', 'Маркса Карла', 'Фадеева', '60 лет СССР', 'Челюскинцев', + 'Олега Кошевого', 'Новостройка', 'Шмидта', 'Кузнецова', 'Войкова', + 'Панфилова', 'Карла Либкнехта', 'Парижской Коммуны', 'Автомобилистов', 'Космодемьянской', + 'Седова', 'Блюхера', 'Демьяна Бедного', 'Спартака', 'Николаева', + 'Бабушкина', 'Октября', 'Щетинкина', 'Гончарова', 'Щербакова', + 'Азина', 'Сурикова', '9 Января', 'Подстанция', 'Волкова', + 'Никитина', 'Рылеева', 'Химиков', 'Курчатова', 'Микрорайон', + 'Докучаева', 'Просвещения', 'Смирнова', 'Макарова', 'Иванова', + 'Л.Толстого', 'Гафури', 'Высоцкого', 'Бажова', 'Кочубея', + 'Леонова', 'Надежды', 'Металлистов', 'Вавилова', 'Ульянова', + 'Павлика Морозова', 'Семашко', 'Шаумяна', 'Чайкиной', 'Ермака', + 'Дорожников', 'Советской Армии', 'Монтажников', 'Шишкина', 'Металлургов', + 'Беляева', 'Дружба', 'Серафимовича', 'Ильича', 'Мусы Джалиля', + 'Невского', 'Клары Цеткин', 'Леваневского', 'Водников', 'Вахитова', + 'Станиславского', 'Советов', 'Восьмого Марта', 'Пожарского', 'Папанина', + 'Победа', '8-е Марта', 'Журавлева', 'Культуры', 'Мая 1', + 'Минина', 'Машиностроителей', 'ДОС', 'Тюленина', 'Громова', + 'О.Кошевого', 'Р.Люксембург', 'Толбухина', 'Дарвина', 'З.Космодемьянской', + '1 Мая', '9 мая', 'Тукая', + ) + + street_titles_irregular_masc = { + 'Полевая': 'Полевой', 'Луговая': 'Луговой', 'Степная': 'Степной', 'Заводская': 'Заводской', + 'Береговая': 'Береговой', 'Речная': 'Речной', 'Трудовая': 'Трудовой', 'Ключевая': 'Ключевой', + 'Мостовая': 'Мостовой', 'Кольцевая': 'Кольцевой', 'Боровая': 'Боровой', 'Донская': 'Донской', + 'Морская': 'Морской', 'Сенная': 'Сенной', 'Прудовая': 'Прудовой', 'Большая': 'Большой', + 'Окружная': 'Окружной', 'Хуторская': 'Хуторской', 'Логовая': 'Логовой', 'Моховая': 'Моховой', + 'Угловая': 'Угловой', 'Слободская': 'Слободской', 'Путевая': 'Путевой', 'Городская': 'Городской', + 'Рабочая': 'Рабочий', 'Верхняя': 'Верхний', 'Тихая': 'Тихий', 'Широкая': 'Широкий', 'Нижняя': 'Нижний', + 'Дальняя': 'Дальний', 'Крайняя': 'Крайний', 'Казачья': 'Казачий', 'Весенняя': 'Весенний', 'Средняя': 'Средний', + 'Короткая': 'Короткий', 'Осенняя': 'Осенний', 'Проезжая': 'Проезжий', 'Высокая': 'Высокий', + } + + street_titles_irregular_neu = { + 'Весенняя': 'Весеннее', 'Верхняя': 'Верхнее', 'Нижняя': 'Нижнее', 'Средняя': 'Среднее', 'Дальняя': 'Дальнее', + 'Крайняя': 'Крайнее', 'Казачья': 'Казачье', 'Рабочая': 'Рабочее', 'Осеняя': 'Осеннее', 'Проезжая': 'Проезжее', + } + + city_names = ( + 'Абакан', 'Абинск', 'Агата', 'Агинское (Забайк.)', 'Адлер', 'Адыгейск', + 'Азов (Рост.)', 'Алагир', 'Алапаевск', 'Алдан', 'Александров', + 'Александров Гай', 'Александровск', 'Александровск-Сахалинский', + 'Алексин', 'Амдерма', 'Амурск', 'Анадырь', 'Анапа', 'Ангарск', + 'Андреаполь', 'Анива', 'Апатиты', 'Апрелевка', 'Апшеронск', 'Аргаяш', + 'Ардон', 'Арзамас', 'Армавир', 'Арсеньев', 'Артем', 'Архангельск', + 'Архыз', 'Аршан (Бурят.)', 'Асбест', 'Асино', 'Астрахань', 'Ахтубинск', + 'Ачинск', 'Ачхой Мартан', 'Аша', 'Бавлы', 'Байкальск', 'Баксан', + 'Балашиха', 'Балашов', 'Балтийск', 'Баргузин', 'Барнаул', 'Батайск', + 'Белгород', 'Белогорск (Амур.)', 'Белокуриха', 'Беломорск', 'Белорецк', + 'Белореченск', 'Белоярский', 'Белый Яр (Томск.)', 'Березники', + 'Беслан', 'Бийск', 'Билибино', 'Биробиджан', 'Бирск', + 'Благовещенск (Амур.)', 'Богучар', 'Бодайбо', 'Бологое', 'Бомнак', + 'Борзя', 'Боровск', 'Братск', 'Бреды', 'Бронницы', 'Брянск', + 'Бугульма', 'Бугуруслан', 'Буденновск', 'Бузулук', 'Буйнакск', + 'Быково (метеост.)', 'Валаам', 'Валдай', 'Ведено', 'Великие Луки', + 'Великий Устюг', 'Вендинга', 'Верещагино (Перм.)', 'Верхнее Пенжино', + 'Верхний Баскунчак', 'Верхний Тагил', 'Верхний Уфалей', 'Верхотурье', + 'Верхоянск', 'Видное', 'Вилюйск', 'Витим', 'Владивосток', + 'Владикавказ', 'Владимир', 'Внуково (метеост.)', 'Волгоград', + 'Волгодонск', 'Вологда', 'Волоколамск', 'Волхов', 'Воркута', + 'Воронеж', 'Воскресенск', 'Воткинск', 'Всеволожск', 'Вуктыл', 'Выборг', + 'Вытегра', 'Вязьма', 'Гаврилов-Ям', 'Гагарин', 'Галич', 'Гатчина', + 'Гдов', 'Геленджик', 'Глазов', 'Голицыно', 'Горно-Алтайск', + 'Городовиковск', 'Горячий Ключ', 'Горячинск', 'Гремячинск (Бурят.)', + 'Гремячинск (Перм.)', 'Грозный', 'Губаха', 'Губкин', 'Губкинский', + 'Гудермес', 'Гусь-Хрустальный', 'Дагомыс', 'Далматово', 'Данков', + 'Двинской', 'Дербент', 'Джейрах', 'Джубга', 'Дзержинск', 'Дивногорск', + 'Диксон', 'Дмитров', 'Дно', 'Добрянка', 'Долинск', 'Домбай', + 'Домодедово', 'Дубна', 'Дудинка', 'Егорьевск', 'Ейск', 'Екатеринбург', + 'Елабуга', 'Елатьма', 'Елец', 'Ельня', 'Енисейск', 'Ербогачен', + 'Ершов', 'Ессентуки', 'Железногорск(Курск.)', 'Жиганск', 'Жигулевск', + 'Жуковский', 'Забайкальск', 'Заводоуковск', 'Завьялиха', 'Зарайск', + 'Звенигород', 'Зеленогорск (Ленин.)', 'Зеленоград', 'Златоуст', + 'Змеиногорск', 'Иваново', 'Ивдель', 'Игарка', 'Игнашино', 'Ижевск', + 'Избербаш', 'Инта', 'Ирбит', 'Иркутск', 'Истра', 'Ишим', 'Йошкар-Ола', + 'Кабанск', 'Кажим', 'Казань', 'Калач', 'Калач-на-Дону', 'Калачинск', + 'Калевала', 'Калининград', 'Калуга', 'Калязин', 'Каменномостский', + 'Каменск-Уральский', 'Каменск-Шахтинский', 'Камень-на-Оби', 'Камышин', + 'Камышлов', 'Кандалакша', 'Каневская', 'Канск', 'Карабудахкент', + 'Карабулак', 'Карачаевск', 'Каргасок', 'Каргополь', 'Карпинск', + 'Карталы', 'Касимов', 'Каспийск', 'Катав-Ивановск', 'Катайск', + 'Качканар', 'Кашира', 'Кашхатау', 'Кедровый', 'Кежма', 'Кемерово', + 'Кетченеры', 'Кижи', 'Кизел', 'Кизилюрт', 'Кизляр', 'Кимры', + 'Кингисепп', 'Кинешма', 'Киренск', 'Киржач', 'Кириши', 'Киров (Вятка)', + 'Кирово-Чепецк', 'Кировск (Мурм.)', 'Кировск (Ленин.)', 'Кисловодск', + 'Клин', 'Ковров', 'Когалым', 'Коломна', 'Колпашево', + 'Комсомольск-на-Амуре', 'Кондопога', 'Королев', 'Корсаков', + 'Костомукша', 'Кострома', 'Котельнич', 'Котлас', 'Кош-Агач', + 'Красная Поляна', 'Красновишерск', 'Красногорск (Моск.)', 'Краснодар', + 'Краснокамск', 'Красноселькуп', 'Краснотурьинск', 'Красноуральск', + 'Красноуфимск', 'Красноярск', 'Кропоткин (Краснод.)', 'Крымск', + 'Кудымкар', 'Кузнецк', 'Кулу', 'Кулунда', 'Кунгур', 'Курган', + 'Курганинск', 'Курильск', 'Курск', 'Куртамыш', 'Курумкан', 'Курчатов', + 'Кущевская', 'Кызыл', 'Кырен', 'Кыштым', 'Кяхта', 'Лабинск', + 'Лабытнанги', 'Лагань', 'Лазаревское', 'Лесной (Сверд.)', 'Липецк', + 'Листвянка (Иркут.)', 'Лодейное Поле', 'Лотошино', 'Луга', 'Луховицы', + 'Лысьва', 'Льгов', 'Любань', 'Люберцы', 'Лянтор', 'Магадан', 'Магас', + 'Магнитогорск', 'Майкоп', 'Макаров', 'Макушино', 'Малая Вишера', + 'Малгобек', 'Малоярославец', 'Махачкала', 'Медногорск', + 'Междуреченский', 'Мезень', 'Мелеуз', 'Меренга', 'Миасс', + 'Миллерово', 'Минеральные Воды', 'Минусинск', 'Мирный', 'Мичуринск', + 'Можайск', 'Можга', 'Моздок', 'Мокшан', 'Мончегорск', 'Морозовск', + 'Моршанск', 'Москва', 'Москва, МГУ', 'Мостовской', 'Муравленко', + 'Мураши', 'Мурманск', 'Муром', 'Мценск', 'Мыс Шмидта', 'Мытищи', + 'Набережные Челны', 'Надым', 'Назрань', 'Нальчик', 'Наро-Фоминск', + 'Нарткала', 'Нарым', 'Нарьян-Мар', 'Находка', 'Невельск', + 'Невинномысск', 'Невьянск', 'Неплюевка', 'Нерчинск', 'Нефедова', + 'Нефтегорск (Самар.)', 'Нефтекамск', 'Нефтеюганск', 'Нижневартовск', + 'Нижнекамск', 'Нижнеудинск', 'Нижний Новгород', 'Нижний Тагил', + 'Новая Игирма', 'Новгород Великий', 'Новокузнецк', 'Новомичуринск', + 'Новомосковск', 'Новороссийка', 'Новороссийск', 'Новосибирск', + 'Новочеркасск', 'Новый Оскол', 'Новый Уренгой', 'Ногинск (Моск.)', + 'Ноглики', 'Норильск', 'Ноябрьск', 'Нурлат', 'Нягань', 'Нязепетровск', + 'Обнинск', 'Обоянь', 'Объячево', 'Одинцово', 'Озеры', 'Оймякон', + 'Октябрьский (Башк.)', 'Октябрьское (Хант.)', 'Октябрьское (Челяб.)', + 'Оленегорск (Якут.)', 'Оленек', 'Омск', 'Онега', 'Орел', 'Оренбург', + 'Орехово-Зуево', 'Орск', 'Оса', 'Осташков', 'Оха', 'Охотск', + 'Павловская', 'Павловский Посад', 'Палана', 'Партизанск', 'Певек', + 'Пенза', 'Переславль-Залесский', 'Пермь', 'Петрозаводск', + 'Петропавловск-Камчатский', 'Петухово', 'Петушки', 'Печенга', 'Печора', + 'Пинега', 'Плес', 'Плесецк', 'Подольск', 'Поронайск', 'Поярково', + 'Приморско-Ахтарск', 'Приозерск', 'Прохладный', 'Псебай', 'Псков', + 'Пушкин', 'Пушкино (Моск.)', 'Пушкинские Горы', 'Пышма', 'Пятигорск', + 'Радужный', 'Раменское', 'Ребриха', 'Ревда (Сверд.)', 'Ржев', + 'Рославль', 'Россошь', 'Ростов', 'Ростов-на-Дону', 'Рубцовск', 'Руза', + 'Рыбинск', 'Рыльск', 'Ряжск', 'Рязань', 'Салават', 'Салехард', + 'Сальск', 'Самара', 'Санкт-Петербург', 'Саранск', 'Сарапул', 'Саратов', + 'Саров (Морд.)', 'Сасово', 'Саянск', 'Светлогорск (Калин.)', + 'Северо-Курильск', 'Северобайкальск', 'Северодвинск', 'Североморск', + 'Североуральск', 'Сеймчан', 'Семлячики', 'Серафимович', + 'Сергиев Посад', 'Серебряные Пруды', 'Середниково', 'Серов', + 'Серпухов', 'Сибай', 'Сковородино', 'Славгород', 'Славянск-на-Кубани', + 'Сладково', 'Слюдянка', 'Смирных', 'Смоленск', 'Снежинск', + 'Снежногорск (Мурм.)', 'Соболево', 'Советский', 'Соликамск', + 'Солнечногорск', 'Соловки', 'Соль-Илецк', 'Сорочинск', 'Сортавала', + 'Сосновый Бор', 'Сосногорск', 'Сосьва (Хант.)', 'Сочи', 'Ставрополь', + 'Старая Русса', 'Старый Оскол', 'Стерлитамак', 'Стрежевой', 'Ступино', + 'Суздаль', 'Сузун', 'Сунтар', 'Сургут (Хант.)', 'Сусуман', 'Сухиничи', + 'Сызрань', 'Сыктывкар', 'Тавда', 'Таганрог', 'Тайшет', 'Талдом', + 'Тамбей', 'Тамбов', 'Тарко-Сале', 'Таштагол', 'Тверь', 'Теберда', + 'Темрюк', 'Териберка', 'Терней', 'Терскол', 'Тикси', 'Тимашевск', + 'Тихвин', 'Тихорецк', 'Тобольск', 'Токма', 'Токсово', 'Тольятти', + 'Томари', 'Томпа', 'Томск', 'Торжок', 'Тосно', 'Тотьма', + 'Троицк (Челяб.)', 'Троицк (Моск.)', 'Троицко-Печорск', 'Туапсе', + 'Тула', 'Тулпан', 'Тулун', 'Тура', 'Туруханск', 'Тутаев', 'Тутончаны', + 'Тымовское', 'Тында', 'Тырныауз', 'Тюмень', 'Уварово', 'Углегорск', + 'Углич', 'Улан-Удэ', 'Ульяновск', 'Урай', 'Уренгой', 'Урус-Мартан', + 'Урюпинск', 'Усинск', 'Усмань', 'Усолье Сибирское', 'Уссурийск', + 'Усть-Баргузин', 'Усть-Джегута', 'Усть-Илимск', 'Усть-Ишим', + 'Усть-Калманка', 'Усть-Камчатск', 'Усть-Катав', 'Усть-Кулом', + 'Усть-Кут', 'Усть-Ордынский', 'Устюжна', 'Уфа', 'Ухта', 'Учалы', + 'Уэлен', 'Фатеж', 'Хабаровск', 'Ханты-Мансийск', 'Хасавюрт', + 'Хасан', 'Хатанга', 'Химки', 'Холмогоры', 'Холмск', 'Хоста', + 'Хужир', 'Цимлянск', 'Чайковский', 'Чебаркуль', 'Чебоксары', + 'Чегем', 'Челюскин', 'Челябинск', 'Черемхово', 'Череповец', + 'Черкесск', 'Чермоз', 'Черняховск', 'Черский', 'Черусти', 'Чехов', + 'Чикола', 'Чита', 'Чокурдах', 'Чулым', 'Чусовой', 'Шадринск', 'Шали', + 'Шамары', 'Шарья', 'Шатки', 'Шатой', 'Шатура', 'Шаховская', 'Шахты', + 'Шелагонцы', 'Шелехов', 'Шенкурск', 'Шерегеш', 'Шереметьево', 'Шилка', + 'Шумиха', 'Шуя', 'Щелково', 'Щельяюр', 'Элиста', 'Эльбрус', 'Эльтон', + 'Энгельс', 'Югорск', 'Южно-Курильск', 'Южно-Сахалинск', 'Южноуральск', + 'Юровск', 'Юрьев-Польский', 'Юрьевец (Иван.)', 'Юрюзань', 'Якутск', + 'Якша', 'Ялуторовск', 'Ямбург', 'Яр-Сале', 'Ярославль', + 'Ясный (Оренб.)', 'Яхрома', 'Яшалта', 'Яшкуль', + ) + + # https://en.wikipedia.org/wiki/Federal_subjects_of_Russia + region_republics = ( + 'Адыгея', 'Алтай', 'Башкортостан', 'Бурятия', 'Дагестан', + 'Ингушетия', 'Кабардино-Балкария', 'Калмыкия', 'Карачаево-Черкесия', 'Карелия', + 'Коми', 'Крым', 'Марий-Эл', 'Мордовия', 'Саха (Якутия)', + 'Северная Осетия - Алания', 'Татарстан', 'Тыва', 'Удмуртия', 'Хакасия', + 'Чечня', 'Чувашия', + ) + + region_krai = ( + 'Алтайский', 'Забайкальский', 'Камчатский', 'Краснодарский', 'Красноярский', + 'Пермский', 'Приморский', 'Ставропольский', 'Хабаровский', + ) + + region_oblast = ( + 'Амурская', 'Архангельская', 'Астраханская', 'Белгородская', 'Брянская', + 'Владимирская', 'Волгоградская', 'Вологодская', 'Воронежская', 'Ивановская', + 'Иркутская', 'Калининградская', 'Калужская', 'Кемеровская', 'Кировская', + 'Костромская', 'Курганская', 'Курская', 'Ленинградская', 'Липецкая', + 'Магаданская', 'Московская', 'Мурманская', 'Нижегородская', 'Новгородская', + 'Новосибирская', 'Омская', 'Оренбургская', 'Орловская', 'Пензенская', + 'Псковская', 'Ростовская', 'Рязанская', 'Самарская', 'Саратовская', + 'Сахалинская', 'Свердловская', 'Смоленская', 'Тамбовская', 'Тверская', + 'Томская', 'Тульская', 'Тюменская', 'Ульяновская', 'Челябинская', + 'Ярославская', + ) + + region_ao = ( + 'Еврейская', 'Ханты-Мансийский', 'Чукотский', 'Ямало-Ненецкий', 'Ненецкий', + ) + + countries = ( + 'Австралия', 'Австрия', 'Азербайджан', 'Албания', + 'Алжир', 'Ангола', 'Андорра', 'Антигуа и Барбуда', + 'Аргентина', 'Армения', 'Афганистан', 'Багамские Острова', + 'Бангладеш', 'Барбадос', 'Бахрейн', 'Белоруссия', 'Белиз', + 'Бельгия', 'Бенин', 'Болгария', 'Боливия', 'Босния и Герцеговина', + 'Ботсвана', 'Бразилия', 'Бруней', 'Буркина-Фасо', 'Бурунди', + 'Бутан', 'Вануату', 'Великобритания', 'Венгрия', 'Венесуэла', + 'Восточный Тимор', 'Вьетнам', 'Габон', 'Гаити', 'Гайана', + 'Гамбия', 'Гана', 'Гватемала', 'Гвинея', 'Гвинея-Бисау', 'Германия', + 'Гондурас', 'Гренада', 'Греция', 'Грузия', 'Дания', 'Джибути', + 'Доминика', 'Доминиканская Республика', 'Египет', 'Замбия', + 'Зимбабве', 'Израиль', 'Индия', 'Индонезия', 'Иордания', + 'Ирак', 'Иран', 'Ирландия', 'Исландия', 'Испания', 'Италия', + 'Йемен', 'Кабо-Верде', 'Казахстан', 'Камбоджа', 'Камерун', + 'Канада', 'Катар', 'Кения', 'Кипр', 'Киргизия', 'Кирибати', + 'Китай', 'Колумбия', 'Коморы', 'Республика Конго', + 'Демократическая Республика Конго', 'КНДР', 'Республика Корея', + 'Коста-Рика', 'Кот-д’Ивуар', 'Куба', 'Кувейт', 'Лаос', 'Латвия', + 'Лесото', 'Либерия', 'Ливан', 'Ливия', 'Литва', 'Лихтенштейн', + 'Люксембург', 'Маврикий', 'Мавритания', 'Мадагаскар', 'Малави', + 'Малайзия', 'Мали', 'Мальдивы', 'Мальта', 'Марокко', 'Маршалловы Острова', + 'Мексика', 'Мозамбик', 'Молдавия', 'Монако', 'Монголия', 'Мьянма', + 'Намибия', 'Науру', 'Непал', 'Нигер', 'Нигерия', 'Нидерланды', + 'Никарагуа', 'Новая Зеландия', 'Норвегия', 'ОАЭ', 'Оман', 'Пакистан', + 'Палау', 'Панама', 'Папуа', 'Парагвай', 'Перу', 'Польша', 'Португалия', + 'Россия', 'Руанда', 'Румыния', 'Сальвадор', 'Самоа', 'Сан-Марино', + 'Сан-Томе и Принсипи', 'Саудовская Аравия', 'Северная Македония', + 'Сейшельские Острова', 'Сенегал', 'Сент-Винсент и Гренадины', + 'Сент-Китс и Невис', 'Сент-Люсия', 'Сербия', 'Сингапур', 'Сирия', + 'Словакия', 'Словения', 'США', 'Соломоновы Острова', 'Сомали', + 'Судан', 'Суринам', 'Сьерра-Леоне', 'Таджикистан', 'Таиланд', + 'Танзания', 'Того', 'Тонга', 'Тринидад и Тобаго', 'Тувалу', + 'Тунис', 'Туркмения', 'Турция', 'Уганда', 'Узбекистан', 'Украина', + 'Уругвай', 'Федеративные Штаты Микронезии', 'Фиджи', 'Филиппины', + 'Финляндия', 'Франция', 'Хорватия', 'Центральноафриканская Республика', + 'Чад', 'Черногория', 'Чехия', 'Чили', 'Швейцария', 'Швеция', + 'Шри-Ланка', 'Эквадор', 'Экваториальная Гвинея', 'Эритрея', + 'Эсватини', 'Эстония', 'Эфиопия', 'ЮАР', 'Южный Судан', 'Ямайка', 'Япония', + ) + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def city_name(self): + return self.random_element(self.city_names) + + def country(self): + return self.random_element(self.countries) + + def region(self): + regions_suffix = self.random_element(self.region_suffixes) + if regions_suffix == 'респ.': + return regions_suffix + ' ' + self.random_element(self.region_republics) + elif regions_suffix == 'край': + return self.random_element(self.region_krai) + ' ' + regions_suffix + elif regions_suffix == 'обл.': + return self.random_element(self.region_oblast) + ' ' + regions_suffix + elif regions_suffix == 'АО': + return self.random_element(self.region_ao) + ' ' + regions_suffix + + def street_suffix(self): + return self.random_element(self.street_suffixes) + + def street_title(self): + return self.random_element(self.street_titles + self.street_titles_noflex) + + def street_name(self): + suffix = self.street_suffix() + street = self.street_title() + stem = street[:-2] + result = street + if street not in self.street_titles_noflex and suffix not in self.street_suffixes_fem: + if suffix in self.street_suffixes_masc: + if street in self.street_titles_irregular_masc.keys(): + result = self.street_titles_irregular_masc[street] + else: + result = stem + 'ый' + if stem.endswith('ск') or stem.endswith('цк'): + result = stem + 'ий' + elif suffix in self.street_suffixes_neu: + if street in self.street_titles_irregular_neu.keys(): + result = self.street_titles_irregular_neu[street] + else: + result = stem + 'ое' + return suffix + ' ' + result diff --git a/testbed/joke2k__faker/faker/providers/address/sk_SK/__init__.py b/testbed/joke2k__faker/faker/providers/address/sk_SK/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a675d6fa8a45f0547b9e9d204cff3f8a5b4623e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/sk_SK/__init__.py @@ -0,0 +1,1159 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_formats = ('{{city_name}}', ) + + street_name_formats = ('{{street_name}}', ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) + + building_number_formats = ('####', '###', '##', '#', '#/#') + + street_suffixes_long = ('ulica', ) + street_suffixes_short = ('ul.', ) + + postcode_formats = ('### ##', ) + + cities = ( + 'Ábelová', 'Abovce', 'Abrahám', 'Abrahámovce', 'Abrahámovce', + 'Abramová', 'Abranovce', 'Adidovce', 'Alekšince', 'Andovce', + 'Andrejová', 'Ardanovce', 'Ardovo', 'Arnutovce', 'Báb', 'Babie', + 'Babín', 'Babiná', 'Babindol', 'Babinec', 'Bacúch', 'Bacúrov', 'Báč', + 'Bačka', 'Bačkov', 'Bačkovík', 'Badín', 'Baďan', 'Báhoň', 'Bajany', + 'Bajč', 'Bajerov', 'Bajerovce', 'Bajka', 'Bajtava', 'Baka', 'Baláže', + 'Baldovce', 'Balog nad Ipľom', 'Baloň', 'Banka', 'Bánov', + 'Bánovce nad Bebravou', 'Bánovce nad Ondavou', 'Banská Belá', + 'Banská Štiavnica', 'Banská Bystrica', 'Banské', 'Banský Studenec', + 'Baňa', 'Bara', 'Barca', 'Bartošovce', 'Bardoňovo', + 'Bartošova Lehôtka', 'Bardejov', 'Baška', 'Baškovce', 'Baškovce', + 'Bašovce', 'Batizovce', 'Bátorová', 'Bátka', 'Bátorove Kosihy', + 'Bátovce', 'Beharovce', 'Beckov', 'Becherov', 'Belá', 'Belá', + 'Belá - Dulice', 'Belá nad Cirochou', 'Beladice', 'Belejovce', 'Belín', + 'Belina', 'Belince', 'Bellova Ves', 'Beloveža', 'Beluj', 'Beluša', + 'Belža', 'Beniakovce', 'Benice', 'Benkovce', 'Beňadiková', + 'Beňadikovce', 'Beňadovo', 'Beňatina', 'Beňuš', 'Bernolákovo', + 'Bertotovce', 'Beša', 'Beša', 'Bešeňov', 'Bešeňová', 'Betlanovce', + 'Betliar', 'Bežovce', 'Bidovce', 'Biel', 'Bielovce', 'Biely Kostol', + 'Bijacovce', 'Bílkove Humence', 'Bíňa', 'Bíňovce', 'Biskupice', + 'Biskupová', 'Bitarová', 'Blahová', 'Blatná na Ostrove', + 'Blatná Polianka', 'Blatné', 'Blatné Remety', 'Blatné Revištia', + 'Blatnica', 'Blažice', 'Blažovce', 'Blesovce', 'Blhovce', 'Bobot', + 'Bobrov', 'Bobrovček', 'Bobrovec', 'Bobrovník', 'Bočiar', 'Bodíky', + 'Bodiná', 'Bodorová', 'Bodovce', 'Bodružal', 'Bodza', + 'Bodzianske Lúky', 'Bogliarka', 'Bohdanovce', 'Bohdanovce nad Trnavou', + 'Boheľov', 'Bohunice', 'Bohunice', 'Bohúňovo', 'Bojná', 'Bojnice', + 'Bojničky', 'Boldog', 'Boleráz', 'Bolešov', 'Boliarov', 'Boľ', + 'Boľkovce', 'Borcová', 'Borčany', 'Borčice', 'Borinka', 'Borová', + 'Borovce', 'Borský Mikuláš', 'Borský Svätý Jur', 'Borša', 'Bory', + 'Bošáca', 'Bošany', 'Bottovo', 'Boťany', 'Bôrka', 'Bracovce', 'Branč', + 'Branovo', 'Bratislava', 'Okres Bratislava II', 'Okres Bratislava III', + 'Okres Bratislava IV', 'Okres Bratislava V', 'Braväcovo', 'Brdárka', + 'Brehov', 'Brehy', 'Brekov', 'Brestov', 'Brestov', + 'Brestov nad Laborcom', 'Brestovany', 'Brestovec', 'Brestovec', + 'Bretejovce', 'Bretka', 'Breza', 'Brezany', 'Brezina', 'Breziny', + 'Breznica', 'Breznička', 'Breznička', 'Brezno', 'Brezolupy', 'Brezov', + 'Brezová pod Bradlom', 'Brezovec', 'Brezovica', 'Brezovica', + 'Brezovička', 'Brezovka', 'Brežany', 'Brhlovce', 'Brieštie', 'Brodské', + 'Brodzany', 'Brunovce', 'Brusnica', 'Brusník', 'Brusno', 'Brutovce', + 'Bruty', 'Brvnište', 'Brzotín', 'Buclovany', 'Búč', 'Bučany', 'Budča', + 'Budikovany', 'Budimír', 'Budiná', 'Budince', 'Budiš', 'Budkovce', + 'Budmerice', 'Buglovce', 'Buková', 'Bukovce', 'Bukovec', 'Bukovec', + 'Bukovina', 'Bulhary', 'Bunetice', 'Bunkovce', 'Bušince', 'Bušovce', + 'Buzica', 'Buzitka', 'Bystrá', 'Bystrá', 'Bystrany', 'Bystré', + 'Bystričany', 'Bystrička', 'Byšta', 'Bytča', 'Bzenica', 'Bzenov', + 'Bzince pod Javorinou', 'Bziny', 'Bzovík', 'Bzovská Lehôtka', 'Bžany', + 'Cabaj - Čápor', 'Cabov', 'Cakov', 'Cejkov', 'Cernina', 'Cerová', + 'Cerovo', 'Cestice', 'Cífer', 'Cigeľ', 'Cigeľka', 'Cigla', 'Cimenná', + 'Cinobaňa', 'Čabalovce', 'Čabiny', 'Čabradský Vrbovok', 'Čadca', + 'Čachtice', 'Čajkov', 'Čaka', 'Čakajovce', 'Čakanovce', 'Čakanovce', + 'Čakany', 'Čaklov', 'Čalovec', 'Čamovce', 'Čaňa', 'Čaradice', 'Čáry', + 'Častá', 'Častkov', 'Častkovce', 'Čata', 'Čataj', 'Čavoj', 'Čebovce', + 'Čečehov', 'Čečejovce', 'Čechy', 'Čechynce', 'Čekovce', 'Čeláre', + 'Čelkova Lehota', 'Čelovce', 'Čelovce', 'Čeľadice', 'Čeľadince', + 'Čeľovce', 'Čenkovce', 'Čerenčany', 'Čereňany', 'Čerhov', 'Čerín', + 'Čermany', 'Černík', 'Černina', 'Černochov', 'Čertižné', + 'Červená Voda', 'Červenica', 'Červenica pri Sabinove', 'Červeník', + 'Červený Hrádok', 'Červený Kameň', 'Červený Kláštor', 'Červeňany', + 'České Brezovo', 'Čičarovce', 'Čičava', 'Čičmany', 'Číčov', 'Čierna', + 'Čierna Lehota', 'Čierna Lehota', 'Čierna nad Tisou', 'Čierna Voda', + 'Čierne', 'Čierne Kľačany', 'Čierne nad Topľou', 'Čierne Pole', + 'Čierny Balog', 'Čierny Brod', 'Čierny Potok', 'Čifáre', + 'Čiližská Radvaň', 'Čimhová', 'Čirč', 'Číž', 'Čižatice', 'Čoltovo', + 'Čremošné', 'Čučma', 'Čukalovce', 'Dačov Lom', 'Daletice', 'Danišovce', + 'Dargov', 'Davidov', 'Debraď', 'Dedačov', 'Dedina Mládeže', 'Dedinka', + 'Dedinky', 'Dechtice', 'Dekýš', 'Demandice', 'Demänovská Dolina', + 'Demjata', 'Detrík', 'Detva', 'Detvianska Huta', 'Devičany', 'Devičie', + 'Dežerice', 'Diaková', 'Diakovce', 'Diviacka Nová Ves', + 'Diviaky nad Nitricou', 'Divín', 'Divina', 'Divinka', 'Dlhá', + 'Dlhá nad Kysucou', 'Dlhá nad Oravou', 'Dlhá nad Váhom', 'Dlhá Ves', + 'Dlhé Klčovo', 'Dlhé nad Cirochou', 'Dlhé Pole', 'Dlhé Stráže', + 'Dlhoňa', 'Dlžín', 'Dobrá', 'Dobrá Niva', 'Dobrá Voda', 'Dobroč', + 'Dobrohošť', 'Dobroslava', 'Dobšiná', 'Dohňany', 'Dojč', 'Dolinka', + 'Dolná Breznica', 'Dolná Krupá', 'Dolná Lehota', 'Dolná Mariková', + 'Dolná Mičiná', 'Dolná Poruba', 'Dolná Seč', 'Dolná Streda', + 'Dolná Strehová', 'Dolná Súča', 'Dolná Tižina', 'Dolná Trnávka', + 'Dolná Ves', 'Dolná Ždaňa', 'Dolné Dubové', 'Dolné Kočkovce', + 'Dolné Lefantovce', 'Dolné Lovčice', 'Dolné Mladonice', + 'Dolné Naštice', 'Dolné Obdokovce', 'Dolné Orešany', 'Dolné Otrokovce', + 'Dolné Plachtince', 'Dolné Saliby', 'Dolné Semerovce', 'Dolné Srnie', + 'Dolné Strháre', 'Dolné Trhovište', 'Dolné Vestenice', 'Dolné Zahorany', + 'Dolné Zelenice', 'Dolný Badín', 'Dolný Bar', 'Dolný Harmanec', + 'Dolný Hričov', 'Dolný Chotár', 'Dolný Kalník', 'Dolný Kubín', + 'Dolný Lieskov', 'Dolný Lopašov', 'Dolný Ohaj', 'Dolný Pial', + 'Dolný Štál', 'Dolný Vadičov', 'Doľany', 'Doľany', 'Domadice', + 'Domaníky', 'Domaniža', 'Domaňovce', 'Donovaly', 'Drábsko', 'Drahňov', + 'Drahovce', 'Dravce', 'Dražice', 'Dražkovce', 'Drážovce', 'Drienčany', + 'Drienica', 'Drienov', 'Drienovec', 'Drienovo', 'Drienovská Nová Ves', + 'Drietoma', 'Drnava', 'Drňa', 'Družstevná pri Hornáde', 'Drženice', + 'Držkovce', 'Dubinné', 'Dubnica nad Váhom', 'Dubnička', 'Dubník', + 'Dubno', 'Dubodiel', 'Dubová', 'Dubová', 'Dubovany', 'Dubovce', + 'Dubové', 'Dubové', 'Dubovec', 'Dubovica', 'Dúbrava', 'Dúbrava', + 'Dúbrava', 'Dúbravica', 'Dúbravka', 'Dúbravy', 'Ducové', 'Dudince', + 'Dukovce', 'Dulov', 'Dulova Ves', 'Dulovce', 'Dulovo', + 'Dunajská Lužná', 'Dunajov', 'Dunajská Streda', 'Dunajský Klátov', + 'Duplín', 'Dvorany nad Nitrou', 'Dvorec', 'Dvorianky', 'Dvorníky', + 'Dvorníky - Včeláre', 'Dvory nad Žitavou', 'Ďačov', 'Ďanová', + 'Ďapalovce', 'Ďubákovo', 'Ďurčiná', 'Ďurďoš', 'Ďurďošík', 'Ďurďové', + 'Ďurkov', 'Ďurková', 'Ďurkovce', 'Egreš', 'Fačkov', 'Falkušovce', + 'Farná', 'Fekišovce', 'Figa', 'Fijaš', 'Fiľakovo', 'Fiľakovské Kováče', + 'Fintice', 'Folkušová', 'Forbasy', 'Frička', 'Fričkovce', 'Fričovce', + 'Fulianka', 'Gabčíkovo', 'Gaboltov', 'Gajary', 'Galanta', 'Galovany', + 'Gánovce', 'Gáň', 'Gbelce', 'Gbely', 'Gbeľany', 'Geča', 'Gelnica', + 'Gemer', 'Gemerček', 'Gemerská Hôrka', 'Gemerská Panica', + 'Gemerská Poloma', 'Gemerská Ves', 'Gemerské Dechtáre', + 'Gemerské Michalovce', 'Gemerské Teplice', 'Gemerský Jablonec', + 'Gemerský Sad', 'Geraltov', 'Gerlachov', 'Gerlachov', 'Giglovce', + 'Giraltovce', 'Girovce', 'Glabušovce', 'Gočaltovo', 'Gočovo', + 'Golianovo', 'Gortva', 'Gôtovany', 'Granč - Petrovce', + 'Gregorova Vieska', 'Gregorovce', 'Gribov', 'Gruzovce', 'Gyňov', + 'Habovka', 'Habura', 'Hačava', 'Háj', 'Háj', 'Hajná Nová Ves', + 'Hajnáčka', 'Hájske', 'Hajtovka', 'Haláčovce', 'Halič', 'Haligovce', + 'Haluzice', 'Hamuliakovo', 'Handlová', 'Hanigovce', 'Haniska', + 'Haniska', 'Hanková', 'Hankovce', 'Hankovce', 'Hanušovce nad Topľou', + 'Harakovce', 'Harhaj', 'Harichovce', 'Harmanec', 'Hatalov', 'Hatné', + 'Havaj', 'Havka', 'Havranec', 'Hažín', 'Hažín nad Cirochou', 'Hažlín', + 'Helcmanovce', 'Heľpa', 'Henckovce', 'Henclová', 'Hencovce', + 'Hendrichovce', 'Herľany', 'Hermanovce', 'Hermanovce nad Topľou', + 'Hertník', 'Hervartov', 'Hiadeľ', 'Hincovce', 'Hladovka', 'Hlboké', + 'Hliník nad Hronom', 'Hlinné', 'Hlivištia', 'Hlohovec', 'Hniezdne', + 'Hnilčík', 'Hnilec', 'Hnojné', 'Hnúšťa', 'Hodejov', 'Hodejovec', + 'Hodkovce', 'Hodruša - Hámre', 'Hokovce', 'Holčíkovce', 'Holiare', + 'Holice', 'Holíč', 'Holiša', 'Holumnica', 'Honce', 'Hontianska Vrbica', + 'Hontianske Moravce', 'Hontianske Nemce', 'Hontianske Tesáre', + 'Hontianske Trsťany', 'Horná Breznica', 'Horná Kráľová', 'Horná Krupá', + 'Horná Lehota', 'Horná Lehota', 'Horná Mariková', 'Horná Mičiná', + 'Horná Poruba', 'Horná Potôň', 'Horná Seč', 'Horná Streda', + 'Horná Strehová', 'Horná Súča', 'Horná Štubňa', 'Horná Ves', + 'Horná Ves', 'Horná Ždaňa', 'Horné Dubové', 'Horné Hámre', + 'Horné Chlebany', 'Horné Lefantovce', 'Horné Mladonice', 'Horné Mýto', + 'Horné Naštice', 'Horné Obdokovce', 'Horné Orešany', 'Horné Otrokovce', + 'Horné Plachtince', 'Horné Pršany', 'Horné Saliby', 'Horné Semerovce', + 'Horné Srnie', 'Horné Strháre', 'Horné Štitáre', 'Horné Trhovište', + 'Horné Turovce', 'Horné Vestenice', 'Horné Zahorany', 'Horné Zelenice', + 'Horný Badín', 'Horný Bar', 'Horný Hričov', 'Horný Kalník', + 'Horný Lieskov', 'Horný Pial', 'Horný Tisovník', 'Horný Vadičov', + 'Horňa', 'Horňany', 'Horovce', 'Horovce', 'Hoste', 'Hostice', 'Hostie', + 'Hostišovce', 'Hostovice', 'Hosťová', 'Hosťovce', 'Hosťovce', + 'Hozelec', 'Hôrka', 'Hôrka nad Váhom', 'Hôrky', 'Hrabičov', 'Hrabkov', + 'Hrabová Roztoka', 'Hrabovčík', 'Hrabovec', 'Hrabovec nad Laborcom', + 'Hrabské', 'Hrabušice', 'Hradisko', 'Hradište', 'Hradište', + 'Hradište pod Vrátnom', 'Hrádok', 'Hrachovište', 'Hrachovo', + 'Hraničné', 'Hranovnica', 'Hraň', 'Hrašné', 'Hrašovík', 'Hrčeľ', + 'Hrhov', 'Hriadky', 'Hričovské Podhradie', 'Hriňová', 'Hrišovce', + 'Hrkovce', 'Hrlica', 'Hrnčiarovce nad Parnou', 'Hrnčiarska Ves', + 'Hrnčiarske Zalužany', 'Hrochoť', 'Hromoš', 'Hronec', 'Hronovce', + 'Hronsek', 'Hronská Breznica', 'Hronská Dúbrava', 'Hronské Kľačany', + 'Hronské Kosihy', 'Hronský Beňadik', 'Hrubá Borša', 'Hruboňovo', + 'Hrubov', 'Hrubý Šúr', 'Hrušov', 'Hrušov', 'Hrušovany', 'Hrušovo', + 'Hruštín', 'Hubice', 'Hubina', 'Hubošovce', 'Hubová', 'Hubovo', + 'Hucín', 'Hudcovce', 'Hul', 'Humenné', 'Huncovce', 'Hunkovce', + 'Hurbanova Ves', 'Hurbanovo', 'Husák', 'Husiná', 'Hutka', 'Huty', + 'Hviezdoslavov', 'Hvozdnica', 'Hybe', 'Hýľov', 'Chanava', 'Chlebnice', + 'Chlmec', 'Chľaba', 'Chmeľnica', 'Chmeľov', 'Chmeľová', 'Chmeľovec', + 'Chminianska Nová Ves', 'Chminianske Jakubovany', 'Chmiňany', 'Choča', + 'Chocholná - Velčice', 'Choňkovce', 'Chorvátsky Grob', 'Chorváty', + 'Chotča', 'Chotín', 'Chrabrany', 'Chrámec', 'Chrastince', 'Chrastné', + 'Chrasť nad Hornádom', 'Chrenovec - Brusno', 'Chropov', 'Chrťany', + 'Chtelnica', 'Chudá Lehota', 'Chvalová', 'Chvojnica', 'Chvojnica', + 'Chynorany', 'Chyžné', 'Igram', 'Ihľany', 'Ihráč', 'Ilava', 'Iliašovce', + 'Ilija', 'Imeľ', 'Inovce', 'Iňa', 'Iňačovce', 'Ipeľské Predmostie', + 'Ipeľské Úľany', 'Ipeľský Sokolec', 'Istebné', 'Ivachnová', 'Ivančiná', + 'Ivanice', 'Ivanka pri Dunaji', 'Ivanka pri Nitre', 'Ivanovce', 'Iža', + 'Ižipovce', 'Ižkovce', 'Jablonec', 'Jablonica', 'Jablonka', 'Jablonov', + 'Jablonov nad Turňou', 'Jablonové', 'Jablonové', 'Jabloň', 'Jabloňovce', + 'Jacovce', 'Jahodná', 'Jaklovce', 'Jakovany', 'Jakubany', 'Jakubov', + 'Jakubova Voľa', 'Jakubovany', 'Jakubovany', 'Jakušovce', 'Jalová', + 'Jalovec', 'Jalovec', 'Jalšové', 'Jalšovík', 'Jamník', 'Jamník', + 'Janice', 'Janík', 'Janíky', 'Jankovce', 'Janov', 'Janova Lehota', + 'Janovce', 'Jánovce', 'Jánovce', 'Janovík', 'Jarabá', 'Jarabina', + 'Jarok', 'Jarovnice', 'Jasenica', 'Jasenie', 'Jasenov', 'Jasenov', + 'Jasenová', 'Jasenovce', 'Jasenové', 'Jasenovo', 'Jaslovské Bohunice', + 'Jasov', 'Jasová', 'Jastrabá', 'Jastrabie nad Topľou', + 'Jastrabie pri Michalovciach', 'Jatov', 'Javorina (vojenský obvod)', + 'Jazernica', 'Jedlinka', 'Jedľové Kostoľany', 'Jelenec', 'Jelka', + 'Jelšava', 'Jelšovce', 'Jelšovec', 'Jenkovce', 'Jesenské', 'Jesenské', + 'Jestice', 'Ješkova Ves', 'Jezersko', 'Jovice', 'Jovsa', + 'Jur nad Hronom', 'Jurkova Voľa', 'Jurová', 'Jurské', 'Juskova Voľa', + 'Kačanov', 'Kajal', 'Kalameny', 'Kalinkovo', 'Kalinov', 'Kalinovo', + 'Kalná nad Hronom', 'Kalná Roztoka', 'Kálnica', 'Kalnište', 'Kalonda', + 'Kalša', 'Kaloša', 'Kaluža', 'Kaľamenová', 'Kaľava', 'Kamanová', + 'Kamenec pod Vtáčnikom', 'Kamenica', 'Kamenica nad Cirochou', + 'Kamenica nad Hronom', 'Kameničany', 'Kameničná', 'Kamenín', + 'Kamenná Poruba', 'Kamenná Poruba', 'Kamenné Kosihy', 'Kamenný Most', + 'Kameňany', 'Kamienka', 'Kamienka', 'Kanianka', 'Kapišová', 'Kaplna', + 'Kapušany', 'Kapušianske Kľačany', 'Karlová', 'Karná', 'Kašov', + 'Kátlovce', 'Kátov', 'Kazimír', 'Kecerovce', 'Kecerovský Lipovec', + 'Kečkovce', 'Kečovo', 'Kechnec', 'Kendice', 'Kesovce', 'Keť', + 'Kežmarok', 'Kiarov', 'Kladzany', 'Klasov', 'Kláštor pod Znievom', + 'Klátova Nová Ves', 'Klčov', 'Klenov', 'Klenová', 'Klenovec', + 'Kleňany', 'Klieština', 'Klin', 'Klin nad Bodrogom', 'Klížska Nemá', + 'Klokoč', 'Klokočov', 'Klokočov', 'Klubina', 'Kluknava', 'Kľačany', + 'Kľače', 'Kľačno', 'Kľak', 'Kľúčovec', 'Kľušov', 'Kmeťovo', + 'Kobeliarovo', 'Kobylnice', 'Kobyly', 'Koceľovce', 'Kociha', + 'Kocurany', 'Kočín - Lančár', 'Kočovce', 'Kochanovce', 'Kochanovce', + 'Kojatice', 'Kojšov', 'Kokava nad Rimavicou', 'Kokošovce', + 'Kokšov - Bakša', 'Kolačkov', 'Kolačno', 'Koláre', 'Kolárovice', + 'Kolárovo', 'Kolbasov', 'Kolbovce', 'Kolibabovce', 'Kolinovce', + 'Kolíňany', 'Kolonica', 'Kolta', 'Komárany', 'Komárno', 'Komárov', + 'Komárovce', 'Komjatice', 'Komjatná', 'Komoča', 'Koniarovce', + 'Konrádovce', 'Konská', 'Konská', 'Koňuš', 'Kopčany', 'Kopernica', + 'Koplotovce', 'Koprivnica', 'Kordíky', 'Korejovce', 'Korňa', 'Koromľa', + 'Korunková', 'Korytárky', 'Korytné', 'Kosihovce', 'Kosihy nad Ipľom', + 'Kosorín', 'Kostolec', 'Kostolište', 'Kostolná pri Dunaji', + 'Kostolná Ves', 'Kostolná - Záriečie', 'Kostolné', 'Kostolné Kračany', + 'Kostoľany pod Tribečom', 'Koš', 'Košariská', 'Košarovce', 'Košeca', + 'Košecké Podhradie', 'Košice', 'Okres Košice II', 'Okres Košice III', + 'Okres Košice IV', 'Košická Belá', 'Košická Polianka', + 'Košické Oľšany', 'Košický Klečenov', 'Koškovce', 'Košolná', 'Košúty', + 'Košťany nad Turcom', 'Kotešová', 'Kotmanová', 'Kotrčiná Lúčka', + 'Kováčová', 'Kováčová', 'Kováčovce', 'Koválov', 'Koválovec', 'Kovarce', + 'Kozárovce', 'Kozelník', 'Kozí Vrbovok', 'Kožany', 'Kožuchov', + 'Kožuchovce', 'Kračúnovce', 'Krahule', 'Krajná Bystrá', 'Krajná Poľana', + 'Krajná Porúbka', 'Krajné', 'Krajné Čierno', 'Krakovany', 'Králiky', + 'Kráľ', 'Kráľov Brod', 'Kráľova Lehota', 'Kráľová nad Váhom', + 'Kráľová pri Senci', 'Kraľovany', 'Kráľovce', 'Kráľovce - Krnišov', + 'Kráľovičove Kračany', 'Kráľovský Chlmec', 'Kraskovo', 'Krásna Lúka', + 'Krásna Ves', 'Krásno', 'Krásno nad Kysucou', 'Krásnohorská Dlhá Lúka', + 'Krásnohorské Podhradie', 'Krásnovce', 'Krásny Brod', 'Krasňany', + 'Kravany', 'Kravany', 'Kravany nad Dunajom', 'Krčava', 'Kremná', + 'Kremnica', 'Kremnické Bane', 'Kristy', 'Krišľovce', + 'Krišovská Liesková', 'Krivá', 'Krivany', 'Kriváň', 'Krivé', + 'Krivoklát', 'Krivosúd - Bodovka', 'Kríže', 'Krížová Ves', 'Krížovany', + 'Križovany nad Dudváhom', 'Krná', 'Krnča', 'Krokava', 'Krompachy', + 'Krpeľany', 'Krškany', 'Krtovce', 'Kručov', 'Krupina', 'Krušetnica', + 'Krušinec', 'Krušovce', 'Kružlov', 'Kružlová', 'Kružná', 'Kružno', + 'Kšinná', 'Kubáňovo', 'Kučín', 'Kučín', 'Kuchyňa', 'Kuklov', 'Kuková', + 'Kukučínov', 'Kunerad', 'Kunešov', 'Kunova Teplica', 'Kuraľany', + 'Kurima', 'Kurimany', 'Kurimka', 'Kurov', 'Kusín', 'Kútniky', 'Kúty', + 'Kuzmice', 'Kuzmice', 'Kvačany', 'Kvačany', 'Kvakovce', 'Kvašov', + 'Kvetoslavov', 'Kyjatice', 'Kyjov', 'Kynceľová', 'Kysak', 'Kyselica', + 'Kysta', 'Kysucké Nové Mesto', 'Kysucký Lieskovec', 'Láb', 'Lackov', + 'Lacková', 'Lada', 'Ladce', 'Ladice', 'Ladmovce', 'Ladomerská Vieska', + 'Ladomirov', 'Ladomirová', 'Ladzany', 'Lakšárska Nová Ves', 'Lascov', + 'Laskár', 'Lastomír', 'Lastovce', 'Laškovce', 'Látky', 'Lazany', + 'Lazisko', 'Lazy pod Makytou', 'Lažany', 'Lednica', 'Lednické Rovne', + 'Legnava', 'Lehnice', 'Lehota', 'Lehota nad Rimavicou', + 'Lehota pod Vtáčnikom', 'Lehôtka', 'Lehôtka pod Brehmi', 'Lechnica', + 'Lekárovce', 'Leles', 'Leľa', 'Lemešany', 'Lenartov', 'Lenartovce', + 'Lendak', 'Lenka', 'Lentvora', 'Leopoldov', 'Lesenice', 'Lesíček', + 'Lesné', 'Lesnica', 'Leštiny', 'Lešť (vojenský obvod)', 'Letanovce', + 'Letničie', 'Leváre', 'Levice', 'Levkuška', 'Levoča', 'Ležiachov', + 'Libichava', 'Licince', 'Ličartovce', 'Liesek', 'Lieskovany', + 'Lieskovec', 'Lieskovec', 'Liešno', 'Liešťany', 'Lietava', + 'Lietavská Lúčka', 'Lietavská Svinná - Babkov', 'Likavka', 'Limbach', + 'Lipany', 'Lipník', 'Lipníky', 'Lipová', 'Lipová', 'Lipovany', + 'Lipovce', 'Lipové', 'Lipovec', 'Lipovec', 'Lipovník', 'Lipovník', + 'Liptovská Anna', 'Liptovská Kokava', 'Liptovská Lúžna', + 'Liptovská Osada', 'Liptovská Porúbka', 'Liptovská Sielnica', + 'Liptovská Štiavnica', 'Liptovská Teplá', 'Liptovská Teplička', + 'Liptovské Beharovce', 'Liptovské Kľačany', 'Liptovské Matiašovce', + 'Liptovské Revúce', 'Liptovské Sliače', 'Liptovský Hrádok', + 'Liptovský Ján', 'Liptovský Michal', 'Liptovský Mikuláš', + 'Liptovský Ondrej', 'Liptovský Peter', 'Liptovský Trnovec', 'Lisková', + 'Lišov', 'Litava', 'Litmanová', 'Livina', 'Livinské Opatovce', 'Livov', + 'Livovská Huta', 'Lodno', 'Lok', 'Lokca', 'Lom nad Rimavicou', 'Lomná', + 'Lomné', 'Lomnička', 'Lontov', 'Lopašov', 'Lopúchov', 'Lopušné Pažite', + 'Lošonec', 'Lovce', 'Lovča', 'Lovčica - Trubín', 'Lovinobaňa', + 'Lozorno', 'Ložín', 'Lubeník', 'Lubina', 'Lúč na Ostrove', 'Lučatín', + 'Lučenec', 'Lúčina', 'Lučivná', 'Lúčka', 'Lúčka', 'Lúčka', 'Lúčka', + 'Lúčky', 'Lúčky', 'Lúčky', 'Lúčnica nad Žitavou', 'Ludanice', + 'Ludrová', 'Luhyňa', 'Lúka', 'Lukačovce', 'Lukáčovce', 'Lukavica', + 'Lukavica', 'Lukov', 'Lukovištia', 'Lúky', 'Lula', 'Lupoč', 'Lutila', + 'Lutiše', 'Lužany', 'Lužany pri Topli', 'Lužianky', 'Lysá pod Makytou', + 'Lysica', 'Ľubá', 'Ľubela', 'Ľubica', 'Ľubietová', 'Ľubiša', 'Ľubochňa', + 'Ľuboreč', 'Ľuboriečka', 'Ľubotice', 'Ľubotín', 'Ľubovec', 'Ľudovítová', + 'Ľutina', 'Ľutov', 'Macov', 'Mad', 'Madunice', 'Magnezitovce', + 'Machulince', 'Majcichov', 'Majere', 'Majerovce', 'Makov', 'Makovce', + 'Malacky', 'Malachov', 'Malá Čalomija', 'Malá Čausa', 'Malá Čierna', + 'Malá Domaša', 'Malá Franková', 'Malá Hradná', 'Malá Ida', + 'Malá Lehota', 'Malá Lodina', 'Malá nad Hronom', 'Malá Poľana', + 'Malá Tŕňa', 'Málaš', 'Malatiná', 'Malatíny', 'Malcov', 'Malčice', + 'Malé Borové', 'Malé Dvorníky', 'Malé Chyndice', 'Malé Hoste', + 'Malé Kosihy', 'Malé Kozmálovce', 'Malé Kršteňany', 'Malé Lednice', + 'Malé Leváre', 'Malé Ludince', 'Malé Ozorovce', 'Malé Raškovce', + 'Malé Ripňany', 'Malé Straciny', 'Malé Trakany', 'Malé Uherce', + 'Malé Vozokany', 'Malé Zálužie', 'Malé Zlievce', 'Málinec', 'Malinová', + 'Malinovo', 'Malužiná', 'Malý Cetín', 'Malý Čepčín', 'Malý Horeš', + 'Malý Kamenec', 'Malý Krtíš', 'Malý Lapáš', 'Malý Lipník', + 'Malý Slavkov', 'Malý Slivník', 'Malý Šariš', 'Malženice', 'Mankovce', + 'Maňa', 'Marcelová', 'Margecany', 'Marhaň', 'Marianka', 'Markovce', + 'Markuška', 'Markušovce', 'Maršová - Rašov', 'Martin', + 'Martin nad Žitavou', 'Martinček', 'Martinová', 'Martovce', 'Mašková', + 'Maškovce', 'Matejovce nad Hornádom', 'Matiaška', 'Matiašovce', + 'Matovce', 'Matúškovo', 'Matysová', 'Maťovské Vojkovce', 'Medovarce', + 'Medvedie', 'Medveďov', 'Medzany', 'Medzev', 'Medzianky', 'Medzibrod', + 'Medzibrodie nad Oravou', 'Medzilaborce', 'Melčice - Lieskové', 'Melek', + 'Meliata', 'Mengusovce', 'Merašice', 'Merník', 'Mestečko', 'Mestisko', + 'Mičakovce', 'Mierovo', 'Miezgovce', 'Michajlov', 'Michal na Ostrove', + 'Michal nad Žitavou', 'Michalková', 'Michalok', 'Michalová', + 'Michalovce', 'Michaľany', 'Miklušovce', 'Miková', 'Mikulášová', + 'Mikušovce', 'Mikušovce', 'Milhosť', 'Miloslavov', 'Milpoš', 'Miňovce', + 'Mirkovce', 'Miroľa', 'Mládzovo', 'Mlynárovce', 'Mlynčeky', 'Mlynica', + 'Mlynky', 'Mníchova Lehota', 'Mníšek nad Hnilcom', + 'Mníšek nad Popradom', 'Moča', 'Močenok', 'Močiar', 'Modra', + 'Modra nad Cirochou', 'Modrany', 'Modrová', 'Modrovka', 'Modrý Kameň', + 'Mojmírovce', 'Mojš', 'Mojtín', 'Mojzesovo', 'Mokrá Lúka', 'Mokrance', + 'Mokroluh', 'Mokrý Háj', 'Moldava nad Bodvou', 'Moravany', + 'Moravany nad Váhom', 'Moravské Lieskové', 'Moravský Svätý Ján', + 'Most pri Bratislave', 'Mostová', 'Moškovec', 'Mošovce', 'Moštenica', + 'Mošurov', 'Motešice', 'Motyčky', 'Môlča', 'Mrázovce', 'Mučín', + 'Mudroňovo', 'Mudrovce', 'Muľa', 'Muráň', 'Muránska Dlhá Lúka', + 'Muránska Huta', 'Muránska Lehota', 'Muránska Zdychava', 'Mútne', + 'Mužla', 'Myjava', 'Myslina', 'Mýtna', 'Mýtne Ludany', + 'Mýto pod Ďumbierom', 'Nacina Ves', 'Nadlice', 'Naháč', 'Nálepkovo', + 'Námestovo', 'Nána', 'Nandraž', 'Necpaly', 'Nedanovce', 'Nedašovce', + 'Neded', 'Nededza', 'Nedožery - Brezany', 'Nechválova Polianka', + 'Nemce', 'Nemcovce', 'Nemcovce', 'Nemčice', 'Nemčiňany', 'Nemecká', + 'Nemečky', 'Nemešany', 'Nemšová', 'Nenince', 'Neporadza', 'Neporadza', + 'Nesvady', 'Nesluša', 'Neverice', 'Nevidzany', 'Nevidzany', 'Nevoľné', + 'Nezbudská Lúčka', 'Nimnica', 'Nitra', 'Nitra nad Ipľom', + 'Nitrianska Blatnica', 'Nitrianska Streda', 'Nitrianske Hrnčiarovce', + 'Nitrianske Pravno', 'Nitrianske Rudno', 'Nitrianske Sučany', 'Nitrica', + 'Nižná', 'Nižná', 'Nižná Boca', 'Nižná Hutka', 'Nižná Jablonka', + 'Nižná Jedľová', 'Nižná Kamenica', 'Nižná Myšľa', 'Nižná Olšava', + 'Nižná Pisaná', 'Nižná Polianka', 'Nižná Rybnica', 'Nižná Sitnica', + 'Nižná Slaná', 'Nižná Voľa', 'Nižné Ladičkovce', 'Nižné Nemecké', + 'Nižné Repaše', 'Nižné Ružbachy', 'Nižný Čaj', 'Nižný Hrabovec', + 'Nižný Hrušov', 'Nižný Klátov', 'Nižný Komárnik', 'Nižný Kručov', + 'Nižný Lánec', 'Nižný Mirošov', 'Nižný Orlík', 'Nižný Skálnik', + 'Nižný Slavkov', 'Nižný Tvarožec', 'Nižný Žipov', 'Nolčovo', 'Norovce', + 'Nová Baňa', 'Nová Bašta', 'Nová Bošáca', 'Nová Bystrica', + 'Nová Dedina', 'Nová Dedinka', 'Nová Dubnica', 'Nová Kelča', + 'Nová Lehota', 'Nová Lesná', 'Nová Ľubovňa', 'Nová Polhora', + 'Nová Polianka', 'Nová Sedlica', 'Nová Ves', 'Nová Ves nad Váhom', + 'Nová Ves nad Žitavou', 'Nová Vieska', 'Nováčany', 'Nováky', 'Nové Hony', + 'Nové Mesto nad Váhom', 'Nové Sady', 'Nové Zámky', 'Novosad', 'Novoť', + 'Nový Ruskov', 'Nový Salaš', 'Nový Tekov', 'Nový Život', 'Nýrovce', + 'Ňagov', 'Ňárad', 'Obeckov', 'Obišovce', 'Oborín', 'Obručné', 'Obyce', + 'Očkov', 'Očová', 'Odorín', 'Ohrady', 'Ohradzany', 'Ochodnica', + 'Ochtiná', 'Okoč', 'Okoličná na Ostrove', 'Okrúhle', 'Okružná', + 'Olcnava', 'Olejníkov', 'Olešná', 'Olováry', 'Olšovany', 'Oľdza', + 'Oľka', 'Oľšavce', 'Oľšavica', 'Oľšavka', 'Oľšavka', 'Oľšinkov', + 'Oľšov', 'Omastiná', 'Omšenie', 'Ondavka', 'Ondavské Matiašovce', + 'Ondrašovce', 'Ondrašová', 'Ondrejovce', 'Opátka', 'Opatovce', + 'Opatovce nad Nitrou', 'Opatovská Nová Ves', 'Opava', 'Opiná', 'Opoj', + 'Oponice', 'Oravce', 'Orávka', 'Oravská Jasenica', 'Oravská Lesná', + 'Oravská Polhora', 'Oravská Poruba', 'Oravský Biely Potok', + 'Oravský Podzámok', 'Ordzovany', 'Orechová', 'Orechová Potôň', + 'Oravské Veselé', 'Oreské', 'Oreské', 'Orešany', 'Orlov', 'Orovnica', + 'Ortuťová', 'Osádka', 'Osadné', 'Osikov', 'Oslany', 'Osrblie', + 'Ostrá Lúka', 'Ostratice', 'Ostrov', 'Ostrov', 'Ostrovany', + 'Ostrý Grúň', 'Osturňa', 'Osuské', 'Oščadnica', 'Otrhánky', 'Otročok', + 'Ovčiarsko', 'Ovčie', 'Ozdín', 'Ožďany', 'Pača', 'Padáň', 'Padarovce', + 'Pakostov', 'Palárikovo', 'Palín', 'Palota', 'Panické Dravce', 'Paňa', + 'Paňovce', 'Papín', 'Papradno', 'Parchovany', 'Parihuzovce', 'Párnica', + 'Partizánska Ľupča', 'Partizánske', 'Pastovce', 'Pastuchov', 'Pašková', + 'Paština Závada', 'Pata', 'Pataš', 'Pavčina Lehota', 'Pavlice', + 'Pavlová', 'Pavlova Ves', 'Pavlovce', 'Pavlovce', 'Pavlovce nad Uhom', + 'Pavľany', 'Pažiť', 'Pčoliné', 'Pečenice', 'Pečeňady', 'Pečeňany', + 'Pečovská Nová Ves', 'Peder', 'Perín - Chym', 'Pernek', 'Petkovce', + 'Petrikovce', 'Petrová', 'Petrova Lehota', 'Petrova Ves', 'Petrovany', + 'Petrovce', 'Petrovce', 'Petrovce', 'Petrovce nad Laborcom', + 'Petrovice', 'Petrovo', 'Pezinok', 'Piešťany', 'Pichne', 'Píla', + 'Píla', 'Píla', 'Pinciná', 'Pinkovce', 'Piskorovce', 'Pitelová', + 'Plášťovce', 'Plavé Vozokany', 'Plavecké Podhradie', 'Plavecký Mikuláš', + 'Plavecký Peter', 'Plavecký Štvrtok', 'Plaveč', 'Plavnica', + 'Plechotice', 'Pleš', 'Plešivec', 'Plevník - Drienové', 'Pliešovce', + 'Ploské', 'Ploské', 'Pobedim', 'Počarová', 'Počúvadlo', 'Podbiel', + 'Podbranč', 'Podbrezová', 'Podhájska', 'Podhorany', 'Podhorany', + 'Podhorany', 'Podhorie', 'Podhorie', 'Podhoroď', 'Podhradie', + 'Podhradie', 'Podhradie', 'Podhradík', 'Podkonice', 'Podkriváň', + 'Podkylava', 'Podlužany', 'Podlužany', 'Podolie', 'Podolínec', + 'Podrečany', 'Podskalie', 'Podtureň', 'Podvysoká', 'Podzámčok', + 'Pohorelá', 'Pohranice', 'Pohronská Polhora', 'Pohronský Bukovec', + 'Pohronský Ruskov', 'Pochabany', 'Pokryváč', 'Poliakovce', 'Polianka', + 'Polichno', 'Polina', 'Poloma', 'Polomka', 'Poltár', 'Poluvsie', + 'Poľanovce', 'Poľany', 'Poľný Kesov', 'Pongrácovce', 'Poniky', + 'Poprad', 'Poproč', 'Poproč', 'Popudinské Močidľany', 'Poráč', + 'Poriadie', 'Porostov', 'Poruba', 'Poruba pod Vihorlatom', 'Porúbka', + 'Porúbka', 'Porúbka', 'Porúbka', 'Poša', 'Potok', 'Potok', 'Potoky', + 'Potôčky', 'Potvorice', 'Považany', 'Považská Bystrica', 'Povina', + 'Povoda', 'Povrazník', 'Pozba', 'Pozdišovce', 'Pôtor', 'Praha', + 'Prakovce', 'Prašice', 'Prašník', 'Pravenec', 'Pravica', 'Pravotice', + 'Práznovce', 'Prečín', 'Predajná', 'Predmier', 'Prenčov', 'Preseľany', + 'Prestavlky', 'Prešov', 'Príbelce', 'Pribeník', 'Pribeta', 'Pribiš', + 'Príbovce', 'Pribylina', 'Priechod', 'Priekopa', 'Priepasné', + 'Prietrž', 'Prietržka', 'Prievaly', 'Prievidza', 'Prihradzany', + 'Príkra', 'Príslop', 'Prituľany', 'Proč', 'Prochot', 'Prosačov', + 'Prosiek', 'Prša', 'Pruské', 'Prusy', 'Pružina', 'Pstriná', 'Ptičie', + 'Ptrukša', 'Pucov', 'Púchov', 'Pukanec', 'Pusté Čemerné', 'Pusté Pole', + 'Pusté Sady', 'Pusté Úľany', 'Pušovce', 'Rabča', 'Rabčice', 'Rad', + 'Radatice', 'Radava', 'Radimov', 'Radnovce', 'Radobica', 'Radoľa', + 'Radoma', 'Radošina', 'Radošovce', 'Radošovce', 'Radôstka', + 'Radvanovce', 'Radvaň nad Dunajom', 'Radvaň nad Laborcom', 'Radzovce', + 'Rafajovce', 'Rajčany', 'Rajec', 'Rajecká Lesná', 'Rajecké Teplice', + 'Rákoš', 'Rákoš', 'Raková', 'Rakovčík', 'Rakovec nad Ondavou', + 'Rakovice', 'Rakovnica', 'Rakovo', 'Rakša', 'Rakúsy', 'Rakytník', + 'Rankovce', 'Rapovce', 'Raslavice', 'Rastislavice', 'Rašice', 'Ratka', + 'Ratková', 'Ratkovce', 'Ratkovo', 'Ratkovská Lehota', 'Ratkovská Suchá', + 'Ratkovské Bystré', 'Ratnovce', 'Ratvaj', 'Ráztočno', 'Ráztoka', + 'Ražňany', 'Reca', 'Regetovka', 'Rejdová', 'Reľov', 'Remeniny', + 'Remetské Hámre', 'Renčišov', 'Repejov', 'Repište', 'Rešica', 'Rešov', + 'Revúca', 'Revúcka Lehota', 'Riečka', 'Riečka', 'Richnava', 'Richvald', + 'Rimavská Baňa', 'Rimavská Seč', 'Rimavská Sobota', 'Rimavské Brezovo', + 'Rimavské Janovce', 'Rimavské Zalužany', 'Rohov', 'Rohovce', 'Rohožník', + 'Rohožník', 'Rochovce', 'Rokycany', 'Rokytov', 'Rokytov pri Humennom', + 'Rokytovce', 'Rosina', 'Roškovce', 'Roštár', 'Rovensko', 'Rovinka', + 'Rovné', 'Rovné', 'Rovné', 'Rovňany', 'Rozhanovce', 'Rozložná', + 'Roztoky', 'Rožkovany', 'Rožňava', 'Rožňavské Bystré', 'Rúbaň', + 'Rudina', 'Rudinka', 'Rudinská', 'Rudlov', 'Rudná', 'Rudnianska Lehota', + 'Rudník', 'Rudník', 'Rudno', 'Rudno nad Hronom', 'Rudňany', 'Rumanová', + 'Rumince', 'Runina', 'Ruská', 'Ruská Bystrá', 'Ruská Kajňa', + 'Ruská Nová Ves', 'Ruská Poruba', 'Ruská Volová', 'Ruská Voľa', + 'Ruská Voľa nad Popradom', 'Ruskov', 'Ruskovce', 'Ruskovce', + 'Ruský Hrabovec', 'Ruský Potok', 'Ružiná', 'Ružindol', 'Ružomberok', + 'Rybany', 'Rybky', 'Rybník', 'Rybník', 'Rykynčice', 'Sabinov', + 'Sačurov', 'Sádočné', 'Sady nad Torysou', 'Salka', 'Santovka', 'Sap', + 'Sása', 'Sása', 'Sasinkovo', 'Sazdice', 'Sebedín - Bečov', 'Sebedražie', + 'Sebechleby', 'Seč', 'Sečianky', 'Sečovce', 'Sečovská Polianka', + 'Sedliacka Dubová', 'Sedliská', 'Sedmerovec', 'Sejkov', 'Sekule', + 'Selce', 'Selce', 'Selce', 'Selec', 'Selice', 'Seľany', 'Semerovo', + 'Senec', 'Seniakovce', 'Senica', 'Senné', 'Senné', 'Senohrad', 'Seňa', + 'Sereď', 'Sielnica', 'Sihelné', 'Sihla', 'Sikenica', 'Sikenička', + 'Siladice', 'Silica', 'Silická Brezová', 'Silická Jablonica', 'Sirk', + 'Sirník', 'Skačany', 'Skalica', 'Skalité', 'Skalka nad Váhom', 'Skároš', + 'Skerešovo', 'Sklabiná', 'Sklabinský Podzámok', 'Sklabiňa', 'Sklené', + 'Sklené Teplice', 'Skrabské', 'Skýcov', 'Sládkovičovo', 'Slančík', + 'Slanec', 'Slanská Huta', 'Slanské Nové Mesto', 'Slaská', 'Slatina', + 'Slatina nad Bebravou', 'Slatinka nad Bebravou', 'Slatinské Lazy', + 'Slatvina', 'Slavec', 'Slavkovce', 'Slavnica', 'Slavoška', 'Slavošovce', + 'Slepčany', 'Sliač', 'Sliepkovce', 'Slizké', 'Slivník', 'Slopná', + 'Slovany', 'Slovenská Kajňa', 'Slovenská Ľupča', 'Slovenská Nová Ves', + 'Slovenská Ves', 'Slovenská Volová', 'Slovenské Ďarmoty', + 'Slovenské Kľačany', 'Slovenské Krivé', 'Slovenské Nové Mesto', + 'Slovenské Pravno', 'Slovenský Grob', 'Slovinky', 'Sľažany', 'Smilno', + 'Smižany', 'Smolenice', 'Smolinské', 'Smolnícka Huta', 'Smolník', + 'Smrdáky', 'Smrečany', 'Snakov', 'Snežnica', 'Snina', 'Socovce', + 'Soblahov', 'Soboš', 'Sobotište', 'Sobrance', 'Sokolce', 'Sokolovce', + 'Sokoľ', 'Sokoľany', 'Solčany', 'Solčianky', 'Sološnica', 'Soľ', + 'Soľnička', 'Soľník', 'Somotor', 'Sopkovce', 'Spišská Belá', + 'Spišská Nová Ves', 'Spišská Stará Ves', 'Spišská Teplica', + 'Spišské Bystré', 'Spišské Hanušovce', 'Spišské Podhradie', + 'Spišské Tomášovce', 'Spišské Vlachy', 'Spišský Hrhov', 'Spišský Hrušov', + 'Spišský Štiavnik', 'Spišský Štvrtok', 'Stakčín', 'Stakčínska Roztoka', + 'Stanča', 'Stankovany', 'Stankovce', 'Stará Bašta', 'Stará Bystrica', + 'Stará Halič', 'Stará Huta', 'Stará Kremnička', 'Stará Lehota', + 'Stará Lesná', 'Stará Ľubovňa', 'Stará Myjava', 'Stará Turá', + 'Stará Voda', 'Staré', 'Staré Hory', 'Starina', 'Starý Hrádok', + 'Starý Tekov', 'Staškov', 'Staškovce', 'Stebnícka Huta', 'Stebník', + 'Stožok', 'Stráne pod Tatrami', 'Stránska', 'Stránske', 'Stráňany', + 'Stráňavy', 'Stratená', 'Stráža', 'Strážne', 'Strážske', 'Strečno', + 'Streda nad Bodrogom', 'Stredné Plachtince', 'Strekov', 'Strelníky', + 'Stretava', 'Stretavka', 'Streženice', 'Strihovce', 'Stročín', + 'Stropkov', 'Studená', 'Studenec', 'Studienka', 'Stuľany', 'Stupava', + 'Stupné', 'Sučany', 'Sudince', 'Súdovce', 'Suchá Dolina', 'Suchá Hora', + 'Suchá nad Parnou', 'Sucháň', 'Suché', 'Suché Brezovo', 'Suchohrad', + 'Sukov', 'Sulín', 'Súlovce', 'Súľov - Hradná', 'Sušany', 'Sútor', + 'Svätá Mária', 'Svätoplukovo', 'Svätuš', 'Svätuše', 'Svätý Anton', + 'Svätý Jur', 'Svätý Kríž', 'Svätý Peter', 'Svederník', 'Sverepec', + 'Sveržov', 'Svetlice', 'Svidnička', 'Svidník', 'Svinia', 'Svinica', + 'Svinice', 'Svinná', 'Svit', 'Svodín', 'Svrbice', 'Svrčinovec', 'Šahy', + 'Šajdíkove Humence', 'Šalgovce', 'Šalgočka', 'Šalov', 'Šaľa', 'Šambron', + 'Šamorín', 'Šamudovce', 'Šandal', 'Šarbov', 'Šarišská Poruba', + 'Šarišská Trstená', 'Šarišské Bohdanovce', 'Šarišské Čierne', + 'Šarišské Dravce', 'Šarišské Jastrabie', 'Šarišské Michaľany', + 'Šarišské Sokolovce', 'Šarišský Štiavnik', 'Šarkan', 'Šarovce', + 'Šašová', 'Šaštín - Stráže', 'Šávoľ', 'Šelpice', 'Šemetkovce', 'Šemša', + 'Šenkvice', 'Šiatorská Bukovinka', 'Šiba', 'Šíd', 'Šimonovce', + 'Šindliar', 'Šintava', 'Šípkov', 'Šípkové', 'Širákov', 'Širkovce', + 'Široké', 'Šišov', 'Šivetice', 'Šmigovec', 'Šoltýska', 'Šoporňa', + 'Špačince', 'Špania Dolina', 'Španie Pole', 'Šrobárová', 'Štefanov', + 'Štefanov nad Oravou', 'Štefanová', 'Štefanovce', 'Štefanovce', + 'Štefanovičová', 'Štefurov', 'Šterusy', 'Štiavnické Bane', + 'Štiavnička', 'Štiavnik', 'Štítnik', 'Štós', 'Štôla', 'Štrba', + 'Štrkovec', 'Štúrovo', 'Štvrtok', 'Štvrtok na Ostrove', 'Šuľa', + 'Šumiac', 'Šuňava', 'Šurany', 'Šurianky', 'Šurice', 'Šúrovce', + 'Šútovo', 'Šútovce', 'Švábovce', 'Švedlár', 'Švošov', 'Tachty', + 'Tajná', 'Tajov', 'Tarnov', 'Tatranská Javorina', 'Tašuľa', 'Tehla', + 'Tekolďany', 'Tekovská Breznica', 'Tekovské Lužany', 'Tekovské Nemce', + 'Tekovský Hrádok', 'Telgárt', 'Telince', 'Temeš', 'Teplička', + 'Teplička nad Váhom', 'Tepličky', 'Teplý Vrch', 'Terany', 'Terchová', + 'Teriakovce', 'Terňa', 'Tesáre', 'Tesárske Mlyňany', 'Tešedíkovo', + 'Tibava', 'Tichý Potok', 'Timoradza', 'Tisinec', 'Tisovec', 'Tlmače', + 'Točnica', 'Tokajík', 'Tomášikovo', 'Tomášov', 'Tomášovce', + 'Tomášovce', 'Topoľa', 'Topoľčany', 'Topoľčianky', 'Topoľnica', + 'Topoľníky', 'Topoľovka', 'Toporec', 'Tornaľa', 'Torysa', 'Torysky', + 'Tovarné', 'Tovarnianska Polianka', 'Tovarníky', 'Tôň', 'Trakovice', + 'Trávnica', 'Trávnik', 'Trebatice', 'Trebejov', 'Trebeľovce', + 'Trebichava', 'Trebišov', 'Trebostovo', 'Trebušovce', 'Trenč', + 'Trenčianska Teplá', 'Trenčianska Turná', 'Trenčianske Bohuslavice', + 'Trenčianske Jastrabie', 'Trenčianske Mitice', 'Trenčianske Stankovce', + 'Trenčianske Teplice', 'Trenčín', 'Trhová Hradská', 'Trhovište', + 'Trnava', 'Trnavá Hora', 'Trnava pri Laborci', 'Trnávka', 'Trnávka', + 'Trnkov', 'Trnovec', 'Trnovec nad Váhom', 'Trnovo', 'Tročany', 'Trpín', + 'Trstená', 'Trstená na Ostrove', 'Trstené', 'Trstené pri Hornáde', + 'Trstice', 'Trstín', 'Trsťany', 'Tŕnie', 'Tuhár', 'Tuhrina', 'Tuchyňa', + 'Tulčík', 'Tupá', 'Turá', 'Turany', 'Turany nad Ondavou', 'Turcovce', + 'Turček', 'Turčianky', 'Turčianska Štiavnička', 'Turčianske Jaseno', + 'Turčianske Kľačany', 'Turčianske Teplice', 'Turčiansky Ďur', + 'Turčiansky Peter', 'Turčok', 'Turecká', 'Tureň', 'Turie', 'Turík', + 'Turnianska Nová Ves', 'Turňa nad Bodvou', 'Turová', 'Turzovka', + 'Tušice', 'Tušická Nová Ves', 'Tužina', 'Tvarožná', 'Tvrdomestice', + 'Tvrdošín', 'Tvrdošovce', 'Ťapešovo', 'Ubľa', 'Úbrež', 'Udavské', + 'Udiča', 'Údol', 'Uhliská', 'Úhorná', 'Uhorská Ves', 'Uhorské', + 'Uhrovec', 'Uhrovské Podhradie', 'Ulič', 'Uličské Krivé', 'Uloža', + 'Úľany nad Žitavou', 'Unín', 'Uňatín', 'Urmince', 'Utekáč', 'Uzovce', + 'Uzovská Panica', 'Uzovské Pekľany', 'Uzovský Šalgov', 'Vaďovce', + 'Vagrinec', 'Váhovce', 'Vajkovce', 'Valaliky', 'Valaská', + 'Valaská Belá', 'Valaská Dubová', 'Valaškovce (vojenský obvod)', + 'Valča', 'Valentovce', 'Valice', 'Valkovce', 'Vaľkovňa', 'Vaniškovce', + 'Vápeník', 'Varadka', 'Varechovce', 'Varhaňovce', 'Varín', 'Vasiľov', + 'Vavrečka', 'Vavrinec', 'Vavrišovo', 'Važec', 'Vechec', 'Velčice', + 'Veličná', 'Velušovce', 'Veľaty', 'Veľká Čausa', 'Veľká Čierna', + 'Veľká Dolina', 'Veľká Franková', 'Veľká Hradná', 'Veľká Ida', + 'Veľká Lesná', 'Veľká Lodina', 'Veľká Lomnica', 'Veľká Mača', + 'Veľká Paka', 'Veľká Tŕňa', 'Veľké Bierovce', 'Veľké Blahovo', + 'Veľké Borové', 'Veľké Držkovce', 'Veľké Dvorany', 'Veľké Dvorníky', + 'Veľké Hoste', 'Veľké Chlievany', 'Veľké Chyndice', 'Veľké Kapušany', + 'Veľké Kosihy', 'Veľké Kostoľany', 'Veľké Kozmálovce', 'Veľké Kršteňany', + 'Veľké Leváre', 'Veľké Lovce', 'Veľké Ludince', 'Veľké Orvište', + 'Veľké Ozorovce', 'Veľké Raškovce', 'Veľké Revištia', 'Veľké Ripňany', + 'Veľké Rovné', 'Veľké Slemence', 'Veľké Trakany', 'Veľké Turovce', + 'Veľké Uherce', 'Veľké Úľany', 'Veľké Vozokany', 'Veľké Zálužie', + 'Veľkrop', 'Veľký Biel', 'Veľký Cetín', 'Veľký Čepčín', 'Veľký Ďur', + 'Veľký Folkmar', 'Veľký Grob', 'Veľký Horeš', 'Veľký Kamenec', + 'Veľký Klíž', 'Veľký Krtíš', 'Veľký Kýr', 'Veľký Lapáš', 'Veľký Lipník', + 'Veľký Meder', 'Veľký Slavkov', 'Veľký Slivník', 'Veľký Šariš', + 'Veľopolie', 'Vernár', 'Veselé', 'Veterná Poruba', 'Vieska', 'Vieska', + 'Vieska nad Žitavou', 'Vikartovce', 'Vinica', 'Viničky', 'Viničné', + 'Vinné', 'Vinodol', 'Vinohrady nad Váhom', 'Vinosady', 'Virt', + 'Vislanka', 'Vislava', 'Visolaje', 'Višňov', 'Višňové', 'Višňové', + 'Vištuk', 'Vitanová', 'Vítkovce', 'Víťaz', 'Víťazovce', 'Vlača', + 'Vladiča', 'Vlachovo', 'Vlachy', 'Vlčany', 'Vlčkovce', 'Vlkas', + 'Vlková', 'Vlkovce', 'Vlky', 'Voderady', 'Vojany', 'Vojčice', 'Vojka', + 'Vojka nad Dunajom', 'Vojkovce', 'Vojnatina', 'Vojňany', 'Vojtovce', + 'Volica', 'Volkovce', 'Voľa', 'Vozokany', 'Vozokany', 'Vráble', + 'Vrádište', 'Vrakúň', 'Vranov nad Topľou', 'Vrbnica', 'Vrbov', + 'Vrbovce', 'Vrbová nad Váhom', 'Vrbové', 'Vrchteplá', 'Vrícko', + 'Vršatské Podhradie', 'Vrútky', 'Vtáčkovce', 'Výborná', + 'Výčapy - Opatovce', 'Vydrany', 'Vydrná', 'Vydrník', 'Východná', + 'Výrava', 'Vysočany', 'Vysoká', 'Vysoká', 'Vysoká nad Kysucou', + 'Vysoká nad Uhom', 'Vysoká pri Morave', 'Vysoké Tatry', 'Vyškovce', + 'Vyškovce nad Ipľom', 'Vyšná Boca', 'Vyšná Hutka', 'Vyšná Jablonka', + 'Vyšná Jedľová', 'Vyšná Kamenica', 'Vyšná Myšľa', 'Vyšná Olšava', + 'Vyšná Pisaná', 'Vyšná Polianka', 'Vyšná Rybnica', 'Vyšná Sitnica', + 'Vyšná Slaná', 'Vyšná Šebastová', 'Vyšná Voľa', 'Vyšné Ladičkovce', + 'Vyšné nad Hronom', 'Vyšné Nemecké', 'Vyšné Remety', 'Vyšné Repaše', + 'Vyšné Ružbachy', 'Vyšný Čaj', 'Vyšný Hrabovec', 'Vyšný Hrušov', + 'Vyšný Kazimír', 'Vyšný Klátov', 'Vyšný Komárnik', 'Vyšný Kručov', + 'Vyšný Kubín', 'Vyšný Mirošov', 'Vyšný Orlík', 'Vyšný Slavkov', + 'Vyšný Tvarožec', 'Vyšný Žipov', 'Zábiedovo', 'Záborie', 'Záborské', + 'Zádiel', 'Záhor', 'Záhorie (vojenský obvod)', 'Záhorská Ves', + 'Záhradné', 'Zákamenné', 'Zákopčie', 'Zalaba', 'Zálesie', 'Zálesie', + 'Zalužice', 'Zamarovce', 'Zámutov', 'Záriečie', 'Záskalie', 'Zatín', + 'Závada', 'Závada', 'Závadka', 'Závadka', 'Závadka', 'Zavar', + 'Závažná Poruba', 'Závod', 'Zázrivá', 'Zbehňov', 'Zbehy', 'Zboj', + 'Zbojné', 'Zborov', 'Zborov nad Bystricou', 'Zbrojníky', + 'Zbudská Belá', 'Zbudské Dlhé', 'Zbudza', 'Zbyňov', 'Zeleneč', + 'Zemianska Olča', 'Zemianske Kostoľany', 'Zemianske Podhradie', + 'Zemianske Sady', 'Zemné', 'Zemplín', 'Zemplínska Nová Ves', + 'Zemplínska Široká', 'Zemplínska Teplica', 'Zemplínske Hámre', + 'Zemplínske Hradište', 'Zemplínske Jastrabie', 'Zemplínske Kopčany', + 'Zemplínsky Branč', 'Zlatá Baňa', 'Zlatá Idka', 'Zlaté', 'Zlaté Klasy', + 'Zlaté Moravce', 'Zlatná na Ostrove', 'Zlatník', 'Zlatníky', 'Zlatno', + 'Zlatno', 'Zliechov', 'Zohor', 'Zubák', 'Zuberec', 'Zubné', + 'Zubrohlava', 'Zvolen', 'Zvončín', 'Žabokreky', 'Žabokreky nad Nitrou', + 'Žakarovce', 'Žakovce', 'Žalobín', 'Žarnov', 'Žarnovica', 'Žaškov', + 'Žbince', 'Ždaňa', 'Ždiar', 'Žehňa', 'Žehra', 'Železník', 'Želiezovce', + 'Želmanovce', 'Žemberovce', 'Žemliare', 'Žiar', 'Žiar', + 'Žiar nad Hronom', 'Žihárec', 'Žikava', 'Žilina', 'Žipov', 'Žirany', + 'Žitavany', 'Žitavce', 'Žitná - Radiša', 'Žlkovce', 'Župčany', + ) + + streets = ( + 'Adámiho', 'Agátová', 'Ahoj', 'Albánska', 'Albrechtova', 'Alejová', + 'Alešova', 'Alstrova', 'Alžbetínska', 'Alžbety Gwerkovej', + 'Amarelková', 'Ambroseho', 'Ambrova', 'Ambrušova', 'Americká', + 'Americké námestie', 'Americké námestie', 'Amurská', 'Andreja Mráza', + 'Andreja Plávku', 'Andrusovova', 'Anenská', 'Anenská', 'Anízová', + 'Antická', 'Antolská', 'Arménska', 'Astronomická', 'Astrová', + 'Avarská', 'Azalková', 'Azovská', 'Babuškova', 'Bagarova', 'Báger', + 'Bahniatková', 'Bachova', 'Bajkalská', 'Bajkalská', 'Bajkalská', + 'Bajkalská', 'Bajkalská', 'Bajkalská', 'Bajzova', 'Bakošova', + 'Balkánska', 'Baltská', 'Bancíkovej', 'Banícka', 'Baničova', + 'Baníkova', 'Banskobystrická', 'Banšelova', 'Bardejovská', 'Bárdošova', + 'Barónka', 'Bartókova', 'Bartoňova', 'Bartoškova', 'Baštová', + 'Batkova', 'Bazalková', 'Bazová', 'Bazovského', 'Bažantia', + 'Beblavého', 'Bebravská', 'Beckovská', 'Bedľová', 'Begóniová', + 'Belániková', 'Belehradská', 'Belianska', 'Belinského', 'Bellova', + 'Belopotockého', 'Beňadická', 'Bencúrova', 'Benediktiho', 'Beniakova', + 'Beňovského', 'Bernolákova', 'Beskydská', 'Betliarska', 'Bezekova', + 'Bezručova', 'Biela', 'Bielkova', 'Bieloruská', 'Bilíkova', + 'Biskupická', 'Björnsonova', 'Blagoevova', 'Blatnická', 'Blatúchová', + 'Bleduľová', 'Blumentálska', 'Blyskáčová', 'Bočná', 'Bodliaková', + 'Bodrocká', 'Bodvianska', 'Bohrova', 'Bohúňova', 'Bojnická', + 'Boragová', 'Borekova', 'Borievková', 'Borinská', 'Borodáčova', + 'Borovicová', 'Borská', 'Bosákova', 'Boskovičova', 'Bošániho', + 'Botanická', 'Bottova', 'Boženy Němcovej', 'Bôrik', 'Bradáčova', + 'Bradlianska', 'Brančská', 'Bratislava-Vinohrady', 'Bratislavská', + 'Bratská', 'Brečtanová', 'Brestová', 'Brezová', 'Brezovská', 'Brežná', + 'Bridlicová', 'Briežky', 'Brigádnická', 'Brižitská', 'Brnianska', + 'Brodná', 'Brodská', 'Brokolicová', 'Bronzová', 'Broskyňová', + 'Bršlenová', 'Brumovická', 'Brusnicová', 'Břeclavská', 'Bučinová', + 'Budatínska', 'Budatínska', 'Budatínska', 'Búdkova cesta', + 'Budovateľská', 'Budyšínska', 'Budyšínska', 'Bujnáková', 'Buková', + 'Bukovinská', 'Bukureštská', 'Bulharská', 'Bulíkova', 'Bullova', + 'Burgundská', 'Buzalkova', 'Bystrého', 'Bystrická', 'BzovIcka', + 'Cabanova', 'Cablkova', 'Cádrova', 'Cesta mládeže', 'Cesta mládeže', + 'Cesta na Červený most', 'Cesta na Červený most', 'Cesta na Kamzík', + 'Cesta na Klanec', 'Cesta na Senec', 'Cígeľská', 'Cikkerova', + 'Cintorínska', 'Cintulova', 'Colnícka', 'Cukrová', 'Cyklámenová', + 'Cyprichova', 'Cyprichova', 'Cyrilova', 'Čachtická', 'Čajakova', + 'Čajakova', 'Čajkovského', 'Čakanková', 'Čaklovská', 'Čalovská', + 'Čapajevova', 'Čapkova', 'Čárskeho', 'Čavojského', 'Čečinová', + 'Čelakovského', 'Čerešňová', 'Černicová', 'Černockého', 'Černockého', + 'Černyševského', 'Červená', 'Červeňákova', 'Červeňova', 'Česká', + 'Československých par', 'Československých tan', 'Čiernohorská', + 'Čiernovodská', 'Čierny chodník', 'Čiližská', 'Čipkárska', 'Čmelíkova', + 'Čmeľovec', 'Čremchová', 'Čučoriedková', 'Čulenova', + 'Daliborovo námestie', 'Damborského', 'Dankovského', 'Dargovská', + 'Ďatelinová', 'Daxnerovo námestie', 'Delená', 'Delená cesta', + 'Demänovská', 'Desiata', 'Detvianska', 'Devätinová', 'Deviata', + 'Devínska cesta', 'Devínska cesta - kam', 'Devínske jazero', 'Dlhá', + 'Dlhé diely I.', 'Dlhé diely II.', 'Dlhé diely III.', 'Dneperská', + 'Dobrovičova', 'Dobrovičova', 'Dobrovského', 'Dobšinského', + 'Dohnalova', 'Dohnányho', 'Doležalova', 'Dolná', 'Dolné Koruny', + 'Dolnokorunská', 'Dolnozemská cesta', 'Domašská', 'Domkárska', + 'Domové role', 'Donnerova', 'Donovalova', 'Donská', 'Dopravná', + 'Dorastenecká', 'Dostojevského rad', 'Dr. Vladimíra Clemen', + 'Dražická', 'Drevená', 'Drieňová', 'Drieňová', 'Drieňová', 'Drobného', + 'Drotárska cesta', 'Drotárska cesta', 'Drotárska cesta', 'Druhá', + 'Druidská', 'Družicová', 'Družobná', 'Družstevná', 'Dubnická', + 'Dubová', 'Dúbravčická', 'Dúbravská cesta', 'Dudova', 'Dudvážska', + 'Dulovo námestie', 'Dulovo námestie', 'Ďumbierska', 'Dunajská', + 'Ďurgalova', 'Dvanásta', 'Dvojkrížna', 'Dvojkrížna', + 'Dvořákovo nábrežie', 'Edisonova', 'Egrešová', 'Einsteinova', + 'Eisnerova', 'Elektrárenská', 'Estónska', 'Estónska', 'Exnárova', + 'F. Kostku', 'Fadruszova', 'Fajnorovo nábrežie', 'Fándlyho', 'Farebná', + 'Farská', 'Farského', 'Fazuľová', 'Fedákova', 'Fedinova', + 'Ferienčíkova', 'Fialkové údolie', 'Fibichova', 'Fikusová', + 'Filiálne nádražie', 'Fláviovská', 'Flöglova', 'Floriánske námestie', + 'Fraňa Kráľa', 'Francisciho', 'Francúzskych partizá', 'Frankovská', + 'Františkánska', 'Františkánske námest', 'Františka Schmuckera', + 'Furdekova', 'Furdekova', 'Furmanská', 'Furmintská', 'Gabčíkova', + 'Gagarinova', 'Gagarinova', 'Gagarinova', 'Gajarská', 'Gajc', 'Gajova', + 'Galaktická', 'Galandova', 'Galbavého', 'Gallayova', 'Gallova', + 'Galvaniho', 'Gašparíkova', 'Gaštanová', 'Gavlovičova', 'Gbelská', + 'Gelnická', 'Gemerská', 'Geologická', 'Georgínová', 'Gercenova', + 'Gerulatská', 'Gessayova', 'Gettingová', 'Glavica', 'Godrova', + 'Gogoľova', 'Goláňova', 'Gondova', 'Goralská', 'Gorazdova', 'Gorkého', + 'Gregorovej', 'Gronárska', 'Grösslingova', 'Gruzínska', 'Gunduličova', + 'Guothova', 'Gusevova', 'Haanova', 'Haburská', 'Hadia cesta', + 'Hadriánová', 'Hagarova', 'Hagarova', 'Hájová', 'Halašova', 'Hálkova', + 'Hálova', 'Hamuliakova', 'Hanácka', 'Handlovská', 'Hanulova', + 'Hanulova', 'Hany Meličkovej', 'Hargašova', 'Harmanecká', 'Harmincova', + 'Hasičská', 'Hattalova', 'Havelkova', 'Havlíčkova', 'Havrania', + 'Haydnova', 'Hečkova', 'Herlianska', 'Herlianska', 'Heydukova', + 'Heyrovského', 'Hlaváčikova', 'Hlavatého', 'Hlavná', 'Hlavné námestie', + 'Hlbinná', 'Hlboká cesta', 'Hlboká cesta', 'Hlinická', 'Hlinická', + 'Hlivová', 'Hlohová', 'Hlučínska', 'Hnilecká', 'Hodálova', + 'Hodonínska', 'Hodonínska', 'Hodonínska', 'Hodžovo námestie', + 'Holekova', 'Holíčska', 'Hollého', 'Holubyho', 'Homolova', + 'Hontianska', 'Horárska', 'Horcová', 'Horčičná', 'Horná', + 'Horná Vančurová', 'Hornádska', 'Horné Židiny', 'Horská', 'Horská', + 'Horská', 'Hospodárska', 'Hrabový chodník', 'Hrad', 'Hradištná', + 'Hradná', 'Hradné údolie', 'Hradská', 'Hrachová', 'Hraničiarska', + 'Hraničná', 'Hraničný priechod-Ču', 'Hrdličkova', 'Hrebendova', + 'Hríbová', 'Hriňovská', 'Hrobákova', 'Hrobárska', 'Hroboňova', + 'Hronska', 'Hroznová', 'Hrušková', 'Hrušovská', 'Hubeného', 'Hubeného', + 'Hudecova', 'Humenské námestie', 'Hummelova', 'Hurbanovo námestie', + 'Hurbanovo námestie', 'Husova', 'Húščavova', 'Hutnícka', 'Hviezdna', + 'Hviezdicová', 'Hviezdoslavova', 'Hviezdoslavovo námes', 'Hyacintová', + 'Hybešova', 'Hydinárska', 'Hýrošova', 'Chalupkova', 'Charkovská', + 'Chemická', 'Chladná', 'Chlumeckého', 'Chmeľová', 'Chorvátska', + 'Chorvátska', 'Chotárna', 'Chrasťová', 'Chrenová', 'Chrobákova', + 'Ihličnatá', 'Ihrisková', 'Iľjušinova', 'Ilkovičova', 'Ílová', + 'Ilýrska', 'Imelová', 'Inovecká', 'Inovecká', 'Ipeľská', 'Irisová', + 'Irkutská', 'Iršajská', 'Iskerníková', 'Istrijská', 'Ivana Blazeviča', + 'Ivana Bukovčana', 'Ivana Horvátha', 'Ivánska cesta', 'J.C.Hronského', + 'Jabloňová', 'Jačmenná', 'Jadranská', 'Jadrová', 'Jahodová', + 'Jakabova', 'Jakubíkova', 'Jakubovo námestie', 'Jakubská', 'Jalovcová', + 'Jamnického', 'Jána Jonáša', 'Jána Poničana', 'Jána Raka', + 'Jána Smreka', 'Jána Stanislava', 'Janáčkova', 'Jančova', + 'Janíkove role', 'Janka Kráľa', 'Jankolova', 'Jánošíkova', 'Jánoškova', + 'Janotova', 'Janšákova', 'Jantárová', 'Jantárová', 'Jantárová cesta', + 'Jarabinková', 'Jarná', 'Jaroslavova', 'Jarošova', 'Jasencová', + 'Jaseňová', 'Jaskový rad', 'Jasná', 'Jasovská', 'Jastrabia', 'Jašíkova', + 'Javorinská', 'Javorová', 'Jazdecká', 'Jazerná', 'Jazmínová', + 'Jedenásta', 'Jedlíkova', 'Jedľová', 'Jégého', 'Jegeneš', 'Jelačičova', + 'Jelenia', 'Jelšová', 'Jeséniova', 'Jesenná', 'Jesenského', + 'Jesienková', 'Jiráskova', 'Jiskrova', 'Jókaiho', 'Jozefa Mikisitsa', + 'Jozefa Vachovského', 'Jozefská', 'Júlová', 'Junácka', 'Jungmannova', + 'Júnová', 'Jurigovo námestie', 'Jurkovičova', 'Jurovského', 'Jurská', + 'Justičná', 'K horárskej studni', 'K lomu', 'K pasienkom', + 'K Železnej studienke', 'Kadnárova', 'Kadnárova', 'Kadnárova', + 'Kadnárova', 'Kadnárova', 'Kafendova', 'Kalinčiakova', 'Kalinová', + 'Kalištná', 'Kaméliová', 'Kamenárska', 'Kamenné námestie', 'Kamilková', + 'Kamilková', 'Kamzík', 'Kapicova', 'Kapitulská', 'Kapitulský dvor', + 'Kaplinská', 'Kapucínska', 'Kapušianska', 'Karadžičova', 'Karadžičova', + 'Karadžičova', 'Karadžičova', 'Karloveská', 'Karloveské rameno', + 'Karpatská', 'Karpatské námestie', 'Kašmírska', 'Kaštielska', + 'Kataríny Brúderovej', 'Kaukazská', 'Kazanská', 'Kazanská', 'Kazanská', + 'Keltská', 'Kempelenova', 'Ketelec', 'Kežmarské námestie', + 'Kladnianska', 'Klariská', 'Klásková', 'Kláštorská', 'Klatovská', + 'Klatovská', 'Klemensova', 'Klenová', 'Klimkovičova', 'Klincová', + 'Klobučnícka', 'Klokočova', 'Kľukatá', 'Kĺzavá', 'Kmeťovo námestie', + 'Knižková dolina', 'Koceľova', 'Kočánkova', 'Kohútova', 'Koľajná', + 'Kolárska', 'Kolískova', 'Kollárova', 'Kollárovo námestie', + 'Kollárovo námestie', 'Kolmá', 'Komárňanská', 'Komárnická', + 'Komárnická', 'Komárovská', 'Komenského námestie', 'Kominárska', + 'Komonicová', 'Koncová', 'Koniarkova', 'Konopná', 'Konvalinková', + 'Konventná', 'Kopanice', 'Kopčianska', 'Koperníkova', 'Koprivnická', + 'Koprivnická', 'Koprivnická', 'Korabinského', 'Kórejská', 'Koreničova', + 'Koreňová', 'Korunská', 'Korytnická', 'Kosatcová', 'Kosodrevinová', + 'Kostlivého', 'Kostolná', 'Košická', 'Košická', 'Košická', 'Kovácsova', + 'Kováčska', 'Kovorobotnícka', 'Kovová', 'Kozia', 'Koziarka', + 'Kozičova', 'Kozmonautická', 'Kožušnícka', 'Kôprová', 'Kôstková', + 'Krahulčia', 'Krajinská', 'Krajinská cesta', 'Krajná', 'Krakovská', + 'Kráľovské údolie', 'Krasinského', 'Kraskova', 'Krásna', + 'Krásnohorská', 'Krasovského', 'Kratiny', 'Krátka', 'Krčméryho', + 'Kremeľská', 'Kremencová', 'Kremnická', 'Kresánkova', 'Kríková', + 'Krivá', 'Križkova', 'Krížna', 'Krížna', 'Krížna', 'Krížna', + 'Krmanova', 'Krokusová', 'Krompašská', 'Krupinská', 'Kubačova', + 'Kubániho', 'Kubínska', 'Kudlákova', 'Kuklovská', 'Kúkoľová', + 'Kukučínova', 'Kukuričná', 'Kulíškova', 'Kultúrna', 'Kuneradská', + 'Kupeckého', 'Kúpeľná', 'Kurucova', 'Kutlíkova', 'Kútska', + 'Kutuzovova', 'Kuzmányho', 'Kvačalova', 'Kvetinárska', 'Kvetná', + 'Kýčerského', 'Kyjevská', 'Kysucká', 'Laborecká', 'Lackova', + 'Ladislava Batthyányh', 'Ladislava Dérera', 'Ladislava Sáru', 'Ľadová', + 'Ladzianskeho', 'Lachova', 'Ľaliová', 'Lamačská cesta', + 'Lamačská cesta', 'Lamačská cesta', 'Lamanského', 'Landauova', + 'Landererova', 'Langsfeldova', 'Ľanová', 'Laskomerského', 'Laténská', + 'Latorická', 'Laučekova', 'Laurinská', 'Lazaretská', 'Lazaretská', + 'Leánska', 'Lediny', 'Legerského', 'Legionárska', 'Legionárska', + 'Lehotského', 'Lehotského', 'Leknová', 'Lenardova', 'Lermontovova', + 'Lesná', 'Lesnícka', 'Leškova', 'Letecká', 'Letisko M.R.Štefánik', + 'Letná', 'Levanduľová', 'Levárska', 'Levická', 'Levočská', 'Lidická', + 'Lieskovec', 'Lieskovcová', 'Lieskovská cesta', 'Lietavská', + 'Lichardova', 'Likavská', 'Limbová', 'Linzbothova', 'Lipnicová', + 'Lipová', 'Lipského', 'Liptovská', 'Lisovňa', 'Listová', 'Líščie nivy', + 'Líščie údolie', 'Litovská', 'Lodná', 'Lombardiniho', 'Lomnická', + 'Lomonosovova', 'Longobardská', 'Lónyaiová', 'Lopenícka', 'Lotyšská', + 'Lovinského', 'Lozornianská', 'Ľubietovská', 'Ľubinská', 'Ľubľanská', + 'Ľubochnianska', 'Ľubovnianska', 'Ľubovníková', 'Ľudové námestie', + 'Ľudovíta Fullu', 'Luhačovická', 'Lužická', 'Lúčna', 'Lužná', + 'Lýcejná', 'Lykovcová', 'Lysákova', 'M. Hella', 'Madáchova', 'Maďarská', + 'Magnetová', 'Magnezitová', 'Magnóliová', 'Magurská', 'Macharova', + 'Máchova', 'Majakovského', 'Majerníkova', 'Majerská', 'Májkova', + 'Majoránová', 'Májová', 'Maková', 'Makovického', 'Malá', 'Malagová', + 'Malé pálenisko', 'Malinová', 'Malodunajská', 'Malokarpatské námest', + 'Malý Draždiak', 'Malý trh', 'Mamateyova', 'Mamateyova', 'Mandľová', + 'Mandľovníková', 'Mánesovo námestie', 'Margarétková', 'Marhuľová', + 'Mariánska', 'Marie Curie-Sklodows', 'Márie Medveďovej', 'Markova', + 'Marótyho', 'Martákovej', 'Martinčekova', 'Martinčekova', + 'Martinengova', 'Martinská', 'Mateja Bela', 'Matejkova', 'Matičná', + 'Mätová', 'Matúškova', 'Matúšova', 'Mečíkova', 'Medená', 'Medová', + 'Medovková', 'Medzierka', 'Medzilaborecká', 'Mesačná', 'Mestská', + 'Meteorová', 'Metodova', 'Mickiewiczova', 'Mierová', 'Michalská', + 'Mikovíniho', 'Mikulášska', 'Milana Marečka', 'Milana Pišúta', + 'Miletičova', 'Miletičova', 'Mišíkova', 'Mišíkova', 'Mišíkova', + 'Mládežnícka', 'Mliekárenská', 'Mlynarovičova', 'Mlynská', + 'Mlynská dolina', 'Mlynská dolina', 'Mlynská dolina', 'Mlynské luhy', + 'Mlynské nivy', 'Mlynské nivy', 'Mlynské nivy', 'Mlynské nivy', + 'Mlynské nivy', 'Modranská', 'Modricová', 'Modrý chodník', 'Mojmírova', + 'Mokráň záhon', 'Mokrohájska cesta', 'Moldavská', 'Molecova', + 'Monardová', 'Morava', 'Moravská', 'Morušova', 'Moskovská', 'Most SNP', + 'Mostná', 'Mostová', 'Mošovského', 'Motýlia', 'Moyšova', 'Moyzesova', + 'Mozartova', 'Mramorová', 'Mraziarenská', 'Mrázova', 'Mudrochova', + 'Mudroňova', 'Mudroňova', 'Mudroňova', 'Muchovo námestie', 'Muránska', + 'Murgašova', 'Murnice', 'Muškátová', 'Muštová', 'Múzejná', 'Myjavská', + 'Mýtna', 'Mýtna', 'Na Baránku', 'Na barine', 'Na Brezinách', + 'Na doline', 'Na grbe', 'Na Grunte', 'Na Holom vrchu', 'Na hrádzi', + 'Na Hrebienku', 'Na hriadkach', 'Na Kalvárii', 'Na kaštieli', + 'Na kopci', 'Na križovatkách', 'Na lánoch', 'Na medzi', 'Na mýte', + 'Na pántoch', 'Na pasekách', 'Na paši', 'Na pažiti', 'Na piesku', + 'Na Revíne', 'Na Riviére', 'Na rozhliadke', 'Na Sitine', 'Na skale', + 'Na Slanci', 'Na Slavíne', 'Na spojke', 'Na stráni', 'Na Štyridsiatku', + 'Na úvrati', 'Na varte', 'Na Vlkovkách', 'Na vrátkach', 'Na vŕšku', + 'Na vyhliadke', 'Na výslní', 'Na Zlatej nohe', 'Nábělkova', + 'Nábrežie arm. gen. L', 'Nábrežná', 'Nad Dunajom', 'Nad Gronárom', + 'Nad jazierkom', 'Nad kúriou', 'Nad lomom', 'Nad lúčkami', + 'Nad lúčkami', 'Nad ostrovom', 'Nad Sihoťou', 'Nákovná', 'Nákupná', + 'Námestie 1. mája', 'Námestie 6. apríla', 'Námestie Alexandra D', + 'Námestie Andreja Hli', 'Námestie Biely kríž', 'Námestie Hraničiarov', + 'Námestie Jána Kostru', 'Námestie Jána Pavla', 'Námestie Ľudovíta Št', + 'Námestie Martina Ben', 'Námestie Rodiny', 'Námestie slobody', + 'Námestie slobody', 'Námestie SNP', 'Námestie SNP', + 'Námestie sv. Františ', 'Námestie sv. Petra a', 'Narcisová', + 'Nedbalova', 'Nechtíková', 'Nejedlého', 'Nekrasovova', 'Nemčíkova', + 'Nerudova', 'Nevädzová', 'Nevská', 'Nezábudková', 'Nezvalova', + 'Niťová', 'Nitrianska', 'Nížinná', 'Nobelova', 'Nobelovo námestie', + 'Nová', 'Nová Bellova', 'Nová hora', 'Novackého', 'Nové pálenisko', + 'Nové záhrady I', 'Nové záhrady II', 'Nové záhrady III', + 'Nové záhrady IV', 'Nové záhrady V', 'Nové záhrady VI', + 'Nové záhrady VII', 'Novinárska', 'Novobanská', 'Novodvorská', + 'Novohorská', 'Novohradská', 'Novosadná', 'Novosvetská', 'Novosvetská', + 'Novosvetská', 'Novoveská', 'Nový záhon', 'Obežná', 'Obchodná', + 'Oblačná', 'Oblúková', 'Očovská', 'Odbojárov', 'Odborárska', + 'Odborárske námestie', 'Odborárske námestie', 'Odeská', 'Ohnicová', + 'Okánikova', 'Okružná', 'Olbrachtova', 'Oleandrová', 'Olejkárska', + 'Olivová', 'Olšová', 'Ondavská', 'Ondrejovova', 'Ondrejská', 'Opavská', + 'Opletalova', 'Oráčska', 'Oravská', 'Orechová', 'Orechová cesta', + 'Orechový rad', 'Orenburská', 'Orgovánová', 'Orchideová', 'Oriešková', + 'Ormisova', 'Osadná', 'Osiková', 'Oskorušová', 'Osloboditeľská', + 'Ostravská', 'Ostredková', 'Ostružinová', 'Osuského', 'Osvetová', + 'Otonelská', 'Ovčiarska', 'Ovocná', 'Ovručská', 'Ovsená', + 'Ovsištské námestie', 'Ožvoldíkova', 'Ôsma', 'Pajštúnska', 'Palackého', + 'Palárikova', 'Palárikova', 'Palinová', 'Palisády', 'Palisády', + 'Palisády', 'Palkovičova', 'Palmová', 'Panenská', 'Pankúchova', + 'Panónska cesta', 'Panská', 'Papánkovo námestie', 'Papraďová', + 'Parcelná', 'Páričkova', 'Parková', 'Partizánska', 'Pasienková', + 'Pasienky', 'Pastierska', 'Paulínyho', 'Pave Vukoviča', 'Pavla Blaha', + 'Pavla Horova', 'Pavlovičova', 'Pavlovova', 'Pavlovská', 'Pažického', + 'Pažítková', 'Pečnianska', 'Pekná cesta', 'Pekná cesta', 'Pekná cesta', + 'Pekná vyhliadka', 'Pekníkova', 'Pernecká', 'Perličková', + 'Pestovateľská', 'Petara Pasicha', 'Peterská', 'Petöfiho', + 'Petržalská', 'Petúniová', 'Pezinská', 'Piata', 'Pieskovcová', + 'Piesočná', 'Piešťanská', 'Pifflova', 'Pilárikova', 'Pílová', + 'Píniová', 'Pionierska', 'Pionierska', 'Pivoňková', 'Plachého', + 'Plachého', 'Planckova', 'Planét', 'Plánky', 'Platanová', 'Plátenícka', + 'Plavecká', 'Plickova', 'Pluhová', 'Plynárenská', 'Plzenská', + 'Pobrežná', 'Pod agátmi', 'Pod Bôrikom', 'Pod brehmi', 'Pod gaštanmi', + 'Pod Kalváriou', 'Pod Klepáčom', 'Pod Kobylou', 'Pod Krásnou hôrkou', + 'Pod lesom', 'Pod lipami', 'Pod Lipovým', 'Pod násypom', + 'Pod Rovnicami', 'Pod skalou', 'Pod srdcom', 'Pod Strážami', + 'Pod Vachmajstrom', 'Pod Válkom', 'Pod vinicami', 'Pod záhradami', + 'Pod záhradami', 'Pod Zečákom', 'Podbeľová', 'Podbrezovská', 'Podháj', + 'Podhorská', 'Podhorského', 'Podjavorinskej', 'Podkarpatská', + 'Podkerepušky', 'Podkolibská', 'Podkorunská', 'Podlesná', + 'Podlučinského', 'Podniková', 'Podpriehradná', 'Podtatranského', + 'Podunajská', 'Podunajská', 'Podzáhradná', 'Pohánková', 'Pohraničníkov', + 'Pohronská', 'Polárna', 'Polianky', 'Poľná', 'Poľnohospodárska', + 'Poľný mlyn', 'Poloreckého', 'Poľská', 'Poludníková', 'Poniklecová', + 'Popolná', 'Popovova', 'Popradská', 'Porubského', 'Poštová', 'Potočná', + 'Považanova', 'Považská', 'Povoznícka', 'Povraznícka', 'Povraznícka', + 'Požiarnická', 'Pračanská', 'Prasličková', 'Pražská', 'Pražská', + 'Predstaničné námesti', 'Prepoštská', 'Prešernova', 'Prešovská', + 'Prešovská', 'Prešovská', 'Pri Bielom kríži', 'Pri dvore', + 'Pri Dynamitke', 'Pri Habánskom mlyne', 'Pri hradnej studni', + 'Pri hrádzi', 'Pri kolíske', 'Pri kríži', 'Pri mlyne', 'Pri Rochu', + 'Pri seči', 'Pri Starej Prachárni', 'Pri Starom háji', + 'Pri starom letisku', 'Pri Starom Mýte', 'Pri strelnici', 'Pri Struhe', + 'Pri Suchom mlyne', 'Pri Šajbách', 'Pri tehelni', 'Pri trati', + 'Pri vinohradoch', 'Pri zvonici', 'Priama cesta', 'Pribylinská', + 'Pribinova', 'Pribinova', 'Pribinova', 'Pribišova', 'Prídanky', + 'Prídavková', 'Priečna', 'Priehradná', 'Priekopnícka', 'Priekopy', + 'Priemyselná', 'Priemyselná', 'Prievozská', 'Prievozská', 'Prievozská', + 'Príjazdná', 'Príkopova', 'Primaciálne námestie', 'Prímoravská', + 'Prípojná', 'Prístav', 'Prístavná', 'Prokofievova', 'Prokopa Veľkého', + 'Prokopova', 'Prúdová', 'Prvá', 'Prvosienková', 'Pšeničná', + 'Púchovská', 'Púpavová', 'Pustá', 'Puškinova', 'Pútnická', + 'Pyrenejská', 'Rácova', 'Račianska', 'Račianska', 'Račianska', + 'Račianska', 'Račianska', 'Račianska', 'Račianske mýto', 'Radarová', + 'Rádiová', 'Radlinského', 'Radničná', 'Radničné námestie', 'Radvanská', + 'Rajčianska', 'Rajecká', 'Rajská', 'Rajtákova', 'Raketová', 'Rákosová', + 'Rascová', 'Rascová', 'Rastislavova', 'Rastlinná', 'Rašelinová', + 'Ráztočná', 'Rázusovo nábrežie', 'Ražná', 'Rebarborová', 'Regrútska', + 'Remeselnícka', 'Repašského', 'Repíková', 'Repná', 'Rešetkova', + 'Revolučná', 'Révová', 'Revúcka', 'Rezedová', 'Riazanská', 'Riazanská', + 'Ribayová', 'Ríbezľová', 'Riečna', 'Rigeleho', 'Rímska', 'Rízlingová', + 'Riznerova', 'Robotnícka', 'Roľnícka', 'Romanova', 'Röntgenova', + 'Rosná', 'Rostovská', 'Rošického', 'Rovná', 'Rovniankova', 'Rovníková', + 'Royova', 'Rozálska', 'Rozmarínová', 'Rozvodná', 'Rožňavská', + 'Rožňavská', 'Rožňavská', 'Rubínová', 'Rubinsteinova', + 'Rudnayovo námestie', 'Rudnícka', 'Rulandská', 'Rumančeková', + 'Rumunská', 'Rusovce', 'Rusovská cesta', 'Rustaveliho', 'Ružičková', + 'Ružinovská', 'Ružinovská', 'Ružinovská', 'Ružomberská', + 'Ružová dolina', 'Ružová dolina', 'Rybárska brána', 'Rybné námestie', + 'Rybničná', 'Rybničná', 'Rybničná', 'Rýdziková', 'Rytierska', + 'Sabinovská', 'Sabinovská', 'Sad Janka Kráľa', 'Sadmelijská', 'Sadová', + 'Samova', 'Saratovská', 'Sartorisova', 'Sasanková', 'Sasinkova', + 'Savignonská', 'Seberíniho', 'Sečovská', 'Sedlárska', 'Sedmokrásková', + 'Segnáre', 'Segnerova', 'Sekulská', 'Sekurisova', 'Sekýľska', + 'Semenárska', 'Semianova', 'Semilonská', 'Senická', 'Senná', + 'Septimiova', 'Schengenská', 'Schillerova', 'Schneidera -Trnavské', + 'Schody pri starej vo', 'Sibírska', 'Siedma', 'Sienkiewiczova', + 'Silvánska', 'Sinokvetná', 'Skalická cesta', 'Skalná', 'Skerličova', + 'Sklabinská', 'Sklenárova', 'Sklenárska', 'Skoroceľová', 'Skuteckého', + 'Skýcovská', 'Sládkovičova', 'Sladová', 'Slatinská', 'Slávičie údolie', + 'Slavín', 'Slepá', 'Sliačska', 'Sliezska', 'Slivková', 'Sĺňavská', + 'Slnečná', 'Slnečnicová', 'Slovanské nábrežie', 'Slovienska', + 'Slovinec', 'Slovinská', 'Slovnaftská', 'Slovnaftská', 'Slowackého', + 'Smetanova', 'Smikova', 'Smolenická', 'Smolnícka', 'Smrečianska', + 'Smrečianska', 'Snežienková', 'Soferove schody', 'Socháňova', + 'Sochorova', 'Sokolíkova', 'Sokolská', 'Solivarská', 'Sološnická', + 'Somolického', 'Somolického', 'Sosnová', 'Sovia', 'Spádová', + 'Spätná cesta', 'Spišská', 'Spojná', 'Spoločenská', 'Sputniková', + 'Sreznevského', 'Srnčia', 'Stachanovská', 'Stálicová', 'Stanekova', + 'Staničná', 'Stará Černicová', 'Stará Ivánska cesta', 'Stará Klenová', + 'Stará Prievozská', 'Stará Stupavská', 'Stará Vajnorská', + 'Stará vinárska', 'Staré Grunty', 'Staré ihrisko', 'Staré záhrady', + 'Starhradská', 'Starohájska', 'Staromestská', 'Staromlynská', + 'Starorímska', 'Staroturský chodník', 'Stavbárska', 'Staviteľská', + 'Stepná cesta', 'Stodolova', 'Stoklasová', 'Stolárska', 'Strakova', + 'Stratená', 'Strážna', 'Strážnická', 'Strážny dom', 'Strečnianska', + 'Stredná', 'Strelecká', 'Strelkova', 'Strmá cesta', 'Strmé sady', + 'Strmý bok', 'Strmý vŕšok', 'Strojnícka', 'Stromová', 'Stropkovská', + 'Struková', 'Studená', 'Studenohorská', 'Stuhová', 'Stupavská', + 'Súbežná', 'Sudová', 'Súhvezdná', 'Suchá', 'Suché mýto', 'Suchohradská', + 'Súkennícka', 'Súľovská', 'Sumbalova', 'Súmračná', 'Súťažná', + 'Svätého Vincenta', 'Svätoplukova', 'Svätoplukova', 'Svätovojtešská', + 'Svébska', 'Svetlá', 'Svíbová', 'Svidnícka', 'Svoradova', 'Svrčia', + 'Syslia', 'Šafárikovo námestie', 'Šafárikovo námestie', 'Šafránová', + 'Šagátova', 'Šachorová', 'Šalátová', 'Šaldova', 'Šalviová', + 'Šamorínska', 'Šancová', 'Šancová', 'Šancová', 'Šancová', 'Šándorova', + 'Šarišská', 'Šášovská', 'Šaštínska', 'Ševčenkova', 'Šiesta', 'Šikmá', + 'Šinkovské', 'Šintavská', 'Šípková', 'Šípová', 'Šíravská', 'Široká', + 'Škarniclova', 'Školská', 'Škovránčia', 'Škultétyho', 'Šoltésovej', + 'Šošovicová', 'Špieszova', 'Špitálska', 'Športová', + 'Šrobárovo námestie', 'Šťastná', 'Štedrá', 'Štefana Králika', + 'Štefana Králika', 'Štefana Majera', 'Štefánikova', 'Štefánikova', + 'Štefánikova', 'Štefanovičova', 'Štefunkova', 'Štepná', 'Štetinova', + 'Štiavnická', 'Štítová', 'Štrbská', 'Štúrova', 'Štvrtá', 'Štyndlova', + 'Šulekova', 'Šulekova', 'Šulekova', 'Šumavská', 'Šuňavcova', 'Šúrska', + 'Šustekova', 'Šuty', 'Švabinského', 'Švantnerova', 'Tabaková', + 'Tablicova', 'Táborská', 'Tajovského', 'Talichova', 'Tallerova', + 'Tatranská', 'Tavaríkova osada', 'Tbiliská', 'Tehelná', 'Tehelňa', + 'Tehliarska', 'Technická', 'Tekovská', 'Tekvicová', 'Telocvičná', + 'Tematínska', 'Teplická', 'Terchovská', 'Teslova', 'Tešedíkova', + 'Tetmayerova', 'Thurzova', 'Tibenského', 'Tibériová', 'Tichá', + 'Tilgnerova', 'Timravina', 'Tobrucká', 'Tokajícka', 'Tolstého', + 'Tománkova', 'Tomanova', 'Tomášikova', 'Tomášikova', 'Tomášikova', + 'Tomášikova', 'Tomášikova', 'Toplianska', 'Topoľčianska', 'Topoľová', + 'Toryská', 'Továrenská', 'Trajánova', 'Tramínová', 'Tranovského', + 'Trávna', 'Trebišovská', 'Trebišovská', 'Trebišovská', 'Trenčianska', + 'Treskoňova', 'Tretia', 'Trhová', 'Trinásta', 'Trnavská cesta', + 'Trnavská cesta', 'Trnavská cesta', 'Trnavská cesta', 'Trnavská cesta', + 'Trnavské mýto', 'Trnková', 'Tŕňová', 'Trojdomy', 'Trojičné námestie', + 'Trstínska', 'Tučkova', 'Tuhovská', 'Tulipánová', 'Tupého', + 'Tupolevova', 'Turbínova', 'Turčianska', 'Turistická', 'Turnianska', + 'Tvarožkova', 'Tylova', 'Tymiánová', 'Tyršovo nábrežie', 'Učiteľská', + 'Údernícka', 'Údolná', 'Uhliská', 'Uhorková', 'Uhrova', 'Uhrovecká', + 'Ukrajinská', 'Ulica 1. mája', 'Ulica 29. augusta', + 'Ulica 29. augusta', 'Ulica 29. augusta', 'Ulica 29. augusta', + 'Ulica 8. mája', 'Ulica Alviano', 'Ulica Imricha Karvaš', + 'Ulica J. Valašťana D', 'Ulica Janka Alexyho', 'Ulica Jozefa Krónera', + 'Ulica Juraja Hronca', 'Ulica Karola Adlera', 'Ulica kpt. Rašu', + 'Ulica Leopoldov maje', 'Ulica Ľuda Zúbka', 'Ulica Nad Válkom', + 'Ulica padlých hrdino', 'Ulica Pri gaštanovej', 'Ulica Pri pastierni', + 'Ulica Pri Vápeníckom', 'Ulica Pri vodnej nád', 'Ulica svornosti', + 'Ulica Viktora Tegelh', 'Úprkova', 'Úradnícka', 'Uránová', 'Urbánkova', + 'Urbárska', 'Ursínyho', 'Uršulínska', 'Ušiakova', 'Úvozná', 'Uzbecká', + 'Úzka', 'Úžiny', 'V záhradách', 'Vajanského nábrežie', 'Vajnorská', + 'Vajnorská', 'Vajnorská', 'Vajnorská', 'Vajnorská', 'Vajnorská', + 'Vajnorská', 'Vajnorská', 'Vajnorská', 'Valachovej', 'Valašská', + 'Valchárska', 'Vančurova', 'Vansovej', 'Vápencová', 'Vápenka', + 'Vápenná', 'Varínska', 'Varšavská', 'Varšavská', 'Vavilovova', + 'Vavrinecká', 'Vavrínova', 'Vazovova', 'Vážska', 'Včelárska', + 'Velehradská', 'Veľké Štepnice', 'Veltlínska', 'Vendelínska', + 'Ventúrska', 'Veterná', 'Veternicová', 'Vetvárska', 'Vetvová', + 'Vidlicová', 'Viedenská cesta', 'Viedenská cesta', 'Viedenská cesta', + 'Vietnamská', 'Vígľašská', 'Vihorlatská', 'Viktorínova', 'Vilová', + 'Viničná', 'Vínna', 'Vinohradnícka', 'Višňová', 'Víťazná', 'Vlárska', + 'Vlastenecké námestie', 'Vlčie hrdlo', 'Vlčkova', 'Vlčkova', 'Vlčkova', + 'Vodné elektrárne', 'Vodný vrch', 'Vosková', 'Votrubova', 'Vrábeľská', + 'Vrakunská', 'Vrakunská cesta', 'Vrakunská cesta', 'Vrančovičova', + 'Vranovská', 'Vrbánska', 'Vrbenského', 'Vŕbová', 'Vresová', + 'Vretenová', 'Vrchná', 'Vrútocká', 'Vtáčikova', 'Vtáčnik', 'Vyhliadka', + 'Vyhnianska cesta', 'Výhonská', 'Východná', 'Vysoká', 'Vysokohorská', + 'Vyšehradská', 'Vyšná', 'Výtvarná', 'Vývojová', 'Wattova', 'Wilsonova', + 'Wolkrova', 'Za bránou', 'Za farou', 'Za Kasárňou', 'Za mlynom', + 'Za sokolovňou', 'Za Stanicou', 'Za tehelňou', 'Záborského', + 'Zadunajská cesta', 'Záhorácka', 'Záhorská', 'Záhradkárska', 'Záhradná', + 'Záhradnícka', 'Záhradnícka', 'Záhradnícka', 'Záhradnícka', 'Záhrady', + 'Záhrebská', 'Záhrebská', 'Záhumenná', 'Záhumenská', 'Zákutie', + 'Zálužická', 'Zámocká', 'Zámocké schody', 'Zámočnícka', 'Západná', + 'Západný rad', 'Záporožská', 'Záruby', 'Zátišie', 'Zátureckého', + 'Zavadilová', 'Závadská', 'Záveterná', 'Závodná', 'Závodníkova', + 'Zbrody', 'Zdravotnícka', 'Zelená', 'Zeleninová', 'Zelenohorská', + 'Zelinárska', 'Zhorínska', 'Zidiny', 'Zimná', 'Zlatá', 'Zlaté piesky', + 'Zlaté schody', 'Zlatohorská', 'Znievska', 'Zohorská', 'Zochova', + 'Zrinského', 'Zvolenská', 'Zvončeková', 'Žabí majer', 'Žabotova', + 'Žarnovická', 'Žatevná', 'Žehrianska', 'Železná', 'Železničiarska', + 'Železničná', 'Želiarska', 'Žellova', 'Žiacka', 'Žiarska', 'Židovská', + 'Žihľavová', 'Žilinská', 'Žilinská', 'Žitavská', 'Žitná', 'Živnostenská', + 'Žižkova', 'Žulová', 'Župné námestie', 'Borágova', 'Parenicová', + 'Loparová', 'Jegnešská', 'Jonatanová', 'Monardová', 'Perličková', + ) + + states = ( + 'Bratislavský kraj', 'Trnavský kraj', 'Trenčiansky kraj', + 'Nitriansky kraj', 'Žilinský kraj', 'Banskobystrický kraj', + 'Prešovský kraj', 'Košický kraj', + ) + + countries = ( + 'Afganistan', 'Afghanistanská islamská republika', 'Ålandy', + 'Albánsko', 'Albánska republika', 'Alžírsko', + 'Alžírska demokratická ľudová republika', 'Americká Samoa', 'Andorra', + 'Andorrské kniežatstvo', 'Angola', 'Angolská republika', 'Anguilla', + 'Antarktída', 'Antigua a Barbuda', 'Argentína', + 'Argentínska republika', 'Arménsko', 'Arménska republika', 'Aruba', + 'Austrália', 'Rakúsko', 'Rakúska republika', 'Azerbajdžan', + 'Azerbajdžanská republika', 'Bahamy', 'Bahamské spoločenstvo', + 'Bahrajn', 'Bahrajnské kráľovstvo', 'Bangladéš', + 'Bangladéšska ľudová republika', 'Barbados', 'Bielorusko', + 'Bieloruská republika', 'Belgicko', 'Belgické kráľovstvo', 'Belize', + 'Benin', 'Beninská republika', 'Bermudy', 'Bhután', + 'Bhutánske kráľovstvo', 'Bolívijská republika', 'Bolívijská republika', + 'Bolívia', 'Bosna a Hercegovina', 'Republika Bosny a Hercegoviny', + 'Botswana', 'Botswanská republika', 'Bouvetov ostrov', 'Brazília', + 'Brazílska federatívna republika', 'Britské indickooceánske územie', + 'Brunejsko-darussalamský štát', 'Bulharsko', 'Bulharská republika', + 'Burkina Faso', 'Burundi', 'Burundská republika', 'Kambodža', + 'Kambodžské kráľovstvo', 'Kamerun', 'Kamerunská republika', 'Kanada', + 'Kapverdy', 'Kapverdská republika', 'Kajmanie ostrovy', + 'Stredoafrická republika', 'Čad', 'Čadská republika', 'Čile', + 'Čilská republika', 'Čína', 'Čínska ľudová republika', + 'Vianočný ostrov', 'Kokosové ostrovy', 'Kolumbia', + 'Kolumbijská republika', 'Komory', 'Komorský zväz', 'Kongo', + 'Konžská republika', 'Konžská demokratická republika', + 'Cookove ostrovy', 'Kostarika', 'Kostarická republika', + 'Pobrežie Slonoviny', 'Republika Pobrežia Slonoviny', 'Chorvátsko', + 'Chorvátska republika', 'Kuba', 'Kubánska republika', 'Cyprus', + 'Cyperská republika', 'Česká republika', 'Dánsko', 'Dánske kráľovstvo', + 'Džibutsko', 'Džibutská republika', 'Dominika', + 'Dominické spoločenstvo', 'Dominikánska republika', 'Ekvádor', + 'Ekvádorská republika', 'Egypt', 'Egyptská arabská republika', + 'Salvádor', 'Salvádorská republika', 'Rovníková Guinea', + 'Republika Rovníkovej Guiney', 'Eritrea', 'Estónsko', + 'Estónska republika', 'Etiópia', + 'Etiópska federatívna demokratická republika', 'Falklandy (Malvíny)', + 'Faerské ostrovy', 'Fidži', 'Fínsko', 'Fínska republika', 'Francúzsko', + 'Francúzska republika', 'Francúzska Guyana', 'Francúzska Polynézia', + 'Francúzske južné a antarktické územia', 'Gabon', 'Gabonská republika', + 'Gambia', 'Gambijská republika', 'Gruzínsko', 'Nemecko', + 'Nemecká spolková republika', 'Ghana', 'Ghanská republika', + 'Gibraltár', 'Grécko', 'Grécka republika', 'Grónsko', 'Grenada', + 'Guadeloupe', 'Guam', 'Guatemala', 'Guatemalská republika', 'Guernsey', + 'Guinea', 'Guinejská republika', 'Guinea-Bissau', + 'Guinejsko-bissauská republika', 'Guyana', + 'Guyanská kooperatívna republika', 'Haiti', 'Haitská republika', + 'Heardov ostrov', 'Svätá stolica (Vatikánsky mestský štát)', + 'Honduras', 'Honduraská republika', 'Hongkong', + 'Osobitná administratívna oblasť Číny Hongkong', 'Maďarsko', + 'Maďarská republika', 'Island', 'Islandská republika', 'India', + 'Indická republika', 'Indonézia', 'Indonézska republika', + 'Iránska islamská republika', 'Iránska islamská republika', 'Irak', + 'Iracká republika', 'Írsko', 'Man', 'Izrael', 'Izraelský štát', + 'Taliansko', 'Talianska republika', 'Jamajka', 'Japonsko', 'Jersey', + 'Jordánsko', 'Jordánske hášimovské kráľovstvo', 'Kazachstan', + 'Kazašská republika', 'Keňa', 'Kenská republika', 'Kiribati', + 'Kiribatská republika', 'Kórejská ľudovodemokratická republika', + 'Kórejská ľudovodemokratická republika', 'Kórejská republika', + 'Kuvajt', 'Kuvajtský štát', 'Kirgizsko', 'Kirgizská republika', + 'Laoská ľudovodemokratická republika', 'Lotyšsko', + 'Lotyšská republika', 'Libanon', 'Libanonská republika', 'Lesotho', + 'Lesothské kráľovstvo', 'Libéria', 'Libérijská republika', 'Líbya', + 'Lichtenštajnsko', 'Lichtenštajnské kniežatstvo', 'Litva', + 'Litovská republika', 'Luxembursko', 'Luxemburské veľkovojvodstvo', + 'Macao', 'Osobitná administratívna oblasť Číny Macao', + 'Macedónska republika', 'Bývalá juhoslovanská republika Macedónsko', + 'Madagaskar', 'Madagaskarská republika', 'Malawi', + 'Malawijská republika', 'Malajzia', 'Maldivy', 'Maldivská republika', + 'Mali', 'Malijská republika', 'Malta', 'Maltská republika', + 'Marshallove ostrovy', 'Republika Marshallových ostrovov', 'Martinik', + 'Mauritánia', 'Mauritánska islamská republika', 'Maurícius', + 'Maurícijská republika', 'Mayotte', 'Mexiko', 'Spojené štáty mexické', + 'Mikronézske federatívne štáty', 'Mikronézske federatívne štáty', + 'Moldavská republika', 'Moldavská republika', 'Moldavsko', 'Monako', + 'Monacké kniežatstvo', 'Mongolsko', 'Čierna Hora', 'Montserrat', + 'Maroko', 'Marocké kráľovstvo', 'Mozambik', 'Mozambická republika', + 'Mjanmarsko', 'Namíbia', 'Namíbijská republika', 'Nauru', + 'Nauruská republika', 'Nepál', + 'Nepálska federatívna demokratická republika', 'Holandsko', + 'Holandské kráľovstvo', 'Nová Kaledónia', 'Nový Zéland', 'Nikaragua', + 'Nikaragujská republika', 'Niger', 'Nigerská republika', 'Nigéria', + 'Nigérijská federatívna republika', 'Niue', 'Norfolk', + 'Severné Mariány', 'Spoločenstvo Severných Marián', 'Nórsko', + 'Nórske kráľovstvo', 'Omán', 'Ománsky sultanát', 'Pakistan', + 'Pakistanská islamská republika', 'Palau', 'Palauská republika', + 'palestínske územie, Okupované', 'Okupované palestínske územie', + 'Panama', 'Panamská republika', 'Papua - Nová Guinea', 'Paraguaj', + 'Paraguajská republika', 'Peru', 'Peruánska republika', 'Filipíny', + 'Filipínska republika', 'Pitcairnove ostrovy', 'Poľsko', + 'Poľská republika', 'Portugalsko', 'Portugalská republika', + 'Portoriko', 'Katar', 'Katarský štát', 'Réunion', 'Rumunsko', + 'Ruská federácia', 'Rwanda', 'Rwandská republika', 'Svätý Bartolomej', + 'Svätá Helena, Ascension a Tristan da Cunha', 'Svätý Krištof a Nevis', + 'Svätá Lucia', 'Saint Martin', 'Saint Pierre a Miquelon', + 'Svätý Vincent a Grenadíny', 'Samoa', 'Samojský nezávislý štát', + 'San Maríno', 'Sanmarínska republika', 'Svätý Tomáš a Princov ostrov', + 'Demokratická republika Svätého Tomáša a Princovho ostrova', + 'Saudská Arábia', 'Saudskoarabské kráľovstvo', 'Senegal', + 'Senegalská republika', 'Srbsko', 'Srbská republika', 'Seychely', + 'Seychelská republika', 'Sierra Leone', 'Sierraleonská republika', + 'Singapur', 'Singapurská republika', 'Slovensko', + 'Slovenská republika', 'Slovinsko', 'Slovinská republika', + 'Šalamúnove ostrovy', 'Somálsko', 'Somálska republika', 'Južná Afrika', + 'Juhoafrická republika', 'Južná Georgia a Južné Sandwichove ostrovy', + 'Španielsko', 'Španielske kráľovstvo', 'Srí Lanka', + 'Srílanská demokratická socialistická republika', 'Sudán', + 'Sudánska republika', 'Surinam', 'Surinamská republika', + 'Svalbard a Jan Mayen', 'Svazijsko', 'Svazijské kráľovstvo', 'Švédsko', + 'Švédske kráľovstvo', 'Švajčiarsko', 'Švajčiarska konfederácia', + 'Sýrska arabská republika', 'Taiwan, provincia Číny', 'Taiwan', + 'Tadžikistan', 'Tadžická republika', 'Tanzánijská zjednotená republika', + 'Tanzánijská zjednotená republika', 'Thajsko', 'Thajské kráľovstvo', + 'Východný Timor', 'Východotimorská demokratická republika', 'Togo', + 'Togská republika', 'Tokelau', 'Tonga', 'Tongské kráľovstvo', + 'Trinidad a Tobago', 'Republika Trinidadu a Tobaga', 'Tunisko', + 'Tuniská republika', 'Turecko', 'Turecká republika', 'Turkménsko', + 'Ostrovy Turks a Caicos', 'Tuvalu', 'Uganda', 'Ugandská republika', + 'Ukrajina', 'Spojené arabské emiráty', 'Spojené kráľovstvo', + 'Spojené kráľovstvo Veľkej Británie a Severného Írska', + 'Spojené štáty', 'Spojené štáty americké', + 'Menšie odľahlé ostrovy Spojených štátov', 'Uruguaj', + 'Uruguajská východná republika', 'Uzbekistan', 'Uzbecká republika', + 'Vanuatu', 'Vanuatská republika', 'Venezuelská bolívarovská republika', + 'Venezuela', 'Vietnam', 'Vietnamská socialistická republika', + 'Panenské ostrovy, Britské', 'Britské Panenské ostrovy', + 'Panenské ostrovy, Americké', 'Panenské ostrovy Spojených štátov', + 'Wallis a Futuna', 'Západná Sahara', 'Jemen', 'Jemenská republika', + 'Zambia', 'Zambijská republika', 'Zimbabwe', 'Zimbabwianska republika', + 'Britské antarktické územie', 'Socialistická republika Barmský zväz', + 'Bieloruská sovietska socialistická republika', + 'ostrovy Canton a Enderbury', + 'Československo, Československá socialistická republika', 'Dahome', + 'Zem kráľovnej Maud', 'Východný Timor', 'Metropolitné Francúzsko', + 'Francúzske pobrežie Afarov a Isasov', + 'Francúzske južné a antarktické územia', + 'Nemecká demokratická republika', 'Nemecká spolková republika', + 'Gilbertove a lagúnové ostrovy', 'Johnston', 'Midwajské ostrovy', + 'Holandské Antily', 'neutrálne pôdy', 'Nové Hebridy', + 'Poručnícke územie tichomorských ostrovov', 'Panamská republika', + 'Panamské prieplavové pásmo', 'Rumunská socialistická republika', + 'Svätý Krištof', 'Srbsko a Čierna Hora', 'Sikkim', 'Rodézia', + 'Španielska Sahara', 'Tichomorské ostrovy pod správou USA', + 'ZSSR, Zväz sovietskych socialistických republík', + 'Republika Horná Volta', 'Vatikánsky mestský štát (Svätá stolica)', + 'Vietnamská demokratická republika', 'Wake', + 'Jemenská ľudovodemokratická republika', 'Jemenská arabská republika', + 'Socialistická federatívna republika Juhoslávia', 'Zairská republika', + ) + + def street_suffix_short(self): + return self.random_element(self.street_suffixes_short) + + def street_suffix_long(self): + return self.random_element(self.street_suffixes_long) + + def city_name(self): + return self.random_element(self.cities) + + def street_name(self): + return self.random_element(self.streets) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/sl_SI/__init__.py b/testbed/joke2k__faker/faker/providers/address/sl_SI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50ac3cbacebe11dfd2d844a08875a3713e1d2fc3 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/sl_SI/__init__.py @@ -0,0 +1,509 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + street_name_formats = ('{{street_name}}', ) + street_address_formats = ('{{street_name}} {{building_number}}', ) + address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) + + building_number_formats = ('###', '##', '#', '#a', '#b', '#c') + + postcode_formats = ('####', ) + + cities = ( + "Ajdovščina", "Bled", "Bovec", "Brežice", "Celje", "Cerknica", + "Črnomelj", "Domžale", "Dravograd", "Gornja Radgona", "Gornji Grad", + "Grosuplje", "Hrastnik", "Idrija", "Ilirska Bistrica", "Izola", + "Jesenice", "Kamnik", "Kobarid", "Kočevje", "Koper", + "Kostanjevica na Krki", "Kranj", "Krško", "Laško", + "Lenart v Slovenskih goricah", "Lendava", "Litija", "Ljubljana", + "Ljutomer", "Logatec", "Maribor", "Medvode", "Mengeš", "Metlika", + "Mežica", "Murska Sobota", "Nova Gorica", "Novo mesto", "Ormož", + "Piran", "Postojna", "Prevalje", "Ptuj", "Radeče", "Radovljica", + "Ravne na Koroškem", "Ribnica", "Rogaška Slatina", + "Ruše", "Sevnica", "Sežana", "Slovenj Gradec", "Slovenska Bistrica", + "Slovenske Konjice", "Šempeter pri Gorici", "Šentjur", "Škofja Loka", + "Šoštanj", "Tolmin", "Trbovlje", "Trebnje", "Tržič", "Turnišče", + "Velenje", "Vipava", "Vipavski Križ", "Višnja Gora", "Vrhnika", + "Zagorje ob Savi", "Žalec", "Železniki", "Žiri", + ) + + streets = ( + "Abramova ulica", "Adamičeva ulica", "Adamič-Lundrovo nabrežje", + "Ajdovščina", "Aleševa ulica", "Alešovčeva ulica", + "Aljaževa ulica", "Ambrožev trg", "Ameriška ulica", + "Andrićeva ulica", "Anžurjeva ulica", "Apihova ulica", + "Argentinska ulica", "Arharjeva cesta", "Arkova ulica", + "Artačeva ulica", "Aškerčeva cesta", "Avčinova ulica", + "Avsečeva ulica", "Avstrijska ulica", "Avšičeva cesta", + "Ažmanova ulica", "Babičeva ulica", "Badjurova ulica", + "Balinarska pot", "Baragova ulica", "Barjanska cesta", + "Bavdkova ulica", "Baznikova ulica", "Bazoviška ulica", + "Beethovnova ulica", "Belačeva ulica", "Beljaška ulica", + "Berčičeva ulica", "Berčonova pot", "Berdajsova ulica", + "Bernekerjeva ulica", "Bernikova ulica", "Betettova cesta", + "Bezenškova ulica", "Bežigrad", "Bičevje", "Bilečanska ulica", + "Bitenčeva ulica", "Bizjakova ulica", "Bizjanova ulica", + "Bizovški štradon", "Blasnikova ulica", "Blasov breg", + "Bleiweisova cesta", "Bobenčkova ulica", "Bobrova ulica", + "Bognarjeva pot", "Bohinjčeva ulica", "Bohoričeva ulica", + "Boletova ulica", "Bolgarska ulica", "Borovniška ulica", + "Borštnikov trg", "Borutova ulica", "Božičeva ulica", + "Brankova ulica", "Bratinova ulica", "Bratislavska cesta", + "Bratov Jakopičev ulica", "Bratov Kunovarjev ulica", + "Bravničarjeva ulica", "Brdnikova ulica", "Breg", "Bregarjeva ulica", + "Breznikova ulica", "Brglezov štradon", "Brilejeva ulica", + "Brodarjev trg", "Brodska cesta", "Burnikova ulica", "Cankarjev vrh", + "Cankarjevo nabrežje", "Carja Dušana ulica", "Celarčeva ulica", + "Celjska ulica", "Celovška cesta", "Cerkniška ulica", + "Cerutova ulica", "Cesta Andreja Bitenca", "Cesta Ceneta Štuparja", + "Cesta Dolomitskega odreda", "Cesta II. grupe odredov", + "Cesta Ljubljanske brigade", "Cesta na Bellevue", "Cesta na Bokalce", + "Cesta na Brinovec", "Cesta na Brod", "Cesta na Ježah", + "Cesta na Kope", "Cesta na Laze", "Cesta na Loko", "Cesta na Mesarico", + "Cesta na Ozare", "Cesta na Poljane", "Cesta na Prevoje", + "Cesta na Urh", "Cesta na Vrhovce", "Cesta slov. kmečkih uporov", + "Cesta Urške Zatlerjeve", "Cesta v Dvor", "Cesta v Gameljne", + "Cesta v Hrastje", "Cesta v hrib", "Cesta v Kleče", "Cesta v Kostanj", + "Cesta v Legarico", "Cesta v Mestni log", "Cesta v Pečale", + "Cesta v Prod", "Cesta v Rožno dolino", "Cesta v Šmartno", + "Cesta v Zeleni log", "Cesta v Zgornji log", "Cesta vstaje", + "Cesta 24. junija", "Cesta 25 talcev", "Cesta 27. aprila", + "Chengdujska cesta", "Chopinov prehod", "Cigaletova ulica", + "Cilenškova ulica", "Cimermanova ulica", "Cimpermanova ulica", + "Cizejeva ulica", "Clevelandska ulica", "Colnarjeva ulica", + "Cvetlična pot", "Čampova ulica", "Čanžekova ulica", + "Čargova ulica", "Čebelarska ulica", "Čehova ulica", + "Čepelnikova ulica", "Čepovanska ulica", "Čerinova ulica", + "Černigojeva ulica", "Černivčeva ulica", "Červanova ulica", + "Čevljarska ulica", "Čižmanova ulica", "Čopova ulica", "Črna pot", + "Črnuška cesta", "Črtomirova ulica", "Čučkova ulica", + "Dajnkova ulica", "Dalmatinova ulica", "Danile Kumarjeve ulica", + "Dečkova ulica", "Dečmanova ulica", "Delakova ulica", + "Demšarjeva cesta", "Derčeva ulica", "Dergančeva ulica", + "Dermotova ulica", "Detelova ulica", "Devinska ulica", "Devova ulica", + "Divjakova ulica", "Do proge", "Dobrajčeva ulica", "Dobrdobska ulica", + "Dolenjska cesta", "Dolgi breg", "Dolgi most", "Dolharjeva ulica", + "Dolinarjeva ulica", "Dolinškova ulica", "Dolničarjeva ulica", + "Dolomitska ulica", "Drabosnjakova ulica", "Draga", "Draveljska ulica", + "Dražgoška ulica", "Drenikov vrh", "Drenikova ulica", + "Dunajska cesta", "Dvojna ulica", "Dvorakova ulica", "Dvorni trg", + "Eipprova ulica", "Ellerjeva ulica", "Emonska cesta", + "Erbežnikova ulica", "Erjavčeva cesta", "Fabianijeva ulica", + "Fani Grumove ulica", "Ferberjeva ulica", "Filipičeva ulica", + "Flajšmanova ulica", "Flandrova ulica", "Forsterjeva ulica", + "Franketova ulica", "Frankopanska ulica", "Frenkova pot", + "Friškovec", "Funtkova ulica", "Fužinska cesta", "Gabrov trg", + "Gača", "Galičeva ulica", "Galjevica", "Gallusovo nabrežje", + "Gasilska cesta", "Gasparijeva ulica", "Gašperšičeva ulica", + "Gerbičeva ulica", "Gestrinova ulica", "Glavarjeva ulica", + "Gledališka stolba", "Glinška ulica", "Glinškova ploščad", + "Glonarjeva ulica", "Gmajnice", "Gobarska pot", "Godeževa ulica", + "Gola Loka", "Golarjeva ulica", "Goljarjeva pot", "Golouhova ulica", + "Goriška ulica", "Gorjančeva ulica", "Gorjupova ulica", + "Gornji Rudnik I", "Gornji Rudnik II", "Gornji Rudnik III", + "Gornji trg", "Goropečnikova ulica", "Gortanova ulica", + "Gospodinjska ulica", "Gosposka ulica", "Gosposvetska cesta", + "Govekarjeva ulica", "Gozdna pot", "Grablovičeva ulica", + "Gradišče", "Gradnikova ulica", "Grafenauerjeva ulica", + "Grajski drevored", "Grajzerjeva ulica", "Gramozna pot", + "Grassellijeva ulica", "Gregorčičeva ulica", "Gregorinova ulica", + "Grintovška ulica", "Grobeljca", "Grobeljska pot", "Groharjeva cesta", + "Groznikova ulica", "Grška ulica", "Grško", "Gruberjevo nabrežje", + "Grudnovo nabrežje", "Gubčeva ulica", "Gunceljska cesta", + "Gustinčarjeva ulica", "Gustinčičeva ulica", "Hacetova ulica", + "Hafnerjeva ulica", "Hajdrihova ulica", "Hauptmanca", + "Hladilniška pot", "Hladnikova cesta", "Hlebčeva ulica", + "Hotimirova ulica", "Hradeckega cesta", "Hranilniška ulica", + "Hribarjevo nabrežje", "Hribernikova ulica", "Hribovska pot", + "Hrvaška ulica", "Hrvatski trg", "Hubadova ulica", "Hudourniška pot", + "Idrijska ulica", "Igriška ulica", "Ilešičeva ulica", + "Ilovški štradon", "Industrijska cesta", "Ingličeva ulica", + "Italijanska ulica", "Izletniška ulica", "Ižanska cesta", + "Jakčeva ulica", "Jakhljeva ulica", "Jakopičev drevored", + "Jakopičevo sprehajališče", "Jakšičeva ulica", "Jalnova ulica", + "Jamova cesta", "Janežičeva cesta", "Janova ulica", "Janševa ulica", + "Jarčeva ulica", "Jarnikova ulica", "Jarše", "Jarška cesta", + "Javorškova ulica", "Jazbečeva pot", "Jelinčičeva ulica", + "Jenkova ulica", "Jensenova ulica", "Jerajeva ulica", + "Jeranova ulica", "Jesenkova ulica", "Jesihov štradon", + "Jezerska ulica", "Ježa", "Ježica", "Joškov štradon", + "Jurčičev trg", "Jurčkova cesta", "Juričeva ulica", + "Juvanova ulica", "K reaktorju", "Kadilnikova ulica", + "Kajuhova ulica", "Kalingerjeva ulica", "Kalinova ulica", + "Kaminova ulica", "Kamniška ulica", "Kamnogoriška cesta", + "Kančeva ulica", "Kanonijeva cesta", "Kantetova ulica", + "Kapusova ulica", "Kardeljeva ploščad", "Karingerjeva ulica", + "Karunova ulica", "Kastelčeva ulica", "Kašeljska cesta", + "Kavadarska cesta", "Kavčičeva ulica", "Kavškova ulica", + "Kekčeva ulica", "Kermaunerjeva ulica", "Kernova cesta", + "Kerševanova ulica", "Keržičeva ulica", "Kettejeva ulica", + "Kladezna ulica", "Klančarjeva ulica", "Kleče", + "Klemenova ulica", "Kleparska steza", "Ključavničarska ulica", + "Klunova ulica", "Kmečka pot", "Knafljev prehod", + "Knezov štradon", "Knezova ulica", "Knobleharjeva ulica", + "Koblarjeva ulica", "Kocbekova ulica", "Kocenova ulica", + "Kocjanova ulica", "Kočenska ulica", "Kodrova ulica", + "Kogojeva ulica", "Kogovškova ulica", "Kokaljeva ulica", + "Kolarjeva ulica", "Kolesarska pot", "Koleševa ulica", + "Kolinska ulica", "Kolmanova ulica", "Kolodvorska ulica", + "Komanova ulica", "Komenskega ulica", "Kongresni trg", + "Kopališka ulica", "Kopitarjeva ulica", "Kopna pot", "Koprska ulica", + "Koreninova ulica", "Koroška ulica", "Korotanska ulica", + "Kosančeva ulica", "Koseskega ulica", "Koseška cesta", + "Kosmačeva ulica", "Kosova ulica", "Kosovelova ulica", + "Koširjeva ulica", "Kotnikova ulica", "Kovačeva ulica", + "Kovaška ulica", "Kovinarska ulica", "Kozakova ulica", + "Kozinova ulica", "Kozlarjeva pot", "Koželjeva ulica", + "Krakovski nasip", "Kraljeva ulica", "Kranerjeva ulica", + "Kraška ulica", "Kratka pot", "Kratka steza", "Kregarjeva ulica", + "Kreljeva ulica", "Kremžarjeva ulica", "Krimska ulica", + "Krištofova ulica", "Kriva pot", "Krivec", "Križevniška soteska", + "Križna ulica", "Krmčeva ulica", "Krmeljeva ulica", + "Kropova ulica", "Krošljeva ulica", "Krovska ulica", "Krožna pot", + "Kržičeva ulica", "Kudrova ulica", "Kuhljeva cesta", + "Kumerdejeva ulica", "Kumerjeve ulica", "Kumrovška ulica", + "Kurilniška ulica", "Kurirska ulica", "Kusoldova ulica", + "Kuštrinova ulica", "Kuzeletova ulica", "Kuzmičeva ulica", + "Lahova pot", "Lajovčeva ulica", "Laknerjeva ulica", "Lakotence", + "Lampetova ulica", "Lamutova ulica", "Langusova ulica", "Latinski trg", + "Lavrinova ulica", "Layerjeva ulica", "Lazarjeva ulica", + "Legatova ulica", "Lemeževa ulica", "Lepi pot", "Lepodvorska ulica", + "Leskovičeva ulica", "Letališka cesta", "Levarjeva ulica", + "Levičnikova ulica", "Levstikov trg", "Levstikova ulica", + "Linhartov podhod", "Linhartova cesta", "Lipahova ulica", + "Litijska cesta", "Litostrojska cesta", "Livada", "Livarska ulica", + "Ločnikarjeva ulica", "Lončarska steza", "Lorenzova cesta", + "Lovrenčičeva ulica", "Lovska ulica", "Lovšetova ulica", + "Lubejeva ulica", "Luize Pesjakove ulica", "Lunačkova ulica", + "Mačja steza", "Mačkov kot", "Mačkova ulica", "Madžarska ulica", + "Magistrova ulica", "Maistrova ulica", "Majaronova ulica", + "Majde Vrhovnikove ulica", "Majorja Lavriča ulica", "Makucova ulica", + "Mala ulica", "Mala vas", "Malejeva ulica", "Malenškova ulica", + "Malgajeva ulica", "Mali štradon", "Mali trg", "Malnarjeva ulica", + "Marčenkova ulica", "Marentičeva ulica", "Mareška pot", + "Marice Kovačeve ulica", "Marincljeva ulica", "Marinovševa cesta", + "Maroltova ulica", "Martina Krpana ulica", "Martinčeva ulica", + "Martinova ulica", "Marušičeva ulica", "Masarykova cesta", + "Matjanova pot", "Matjaževa ulica", "Maurerjeva ulica", + "Mazovčeva pot", "Med hmeljniki", "Medarska ulica", "Medenska cesta", + "Medveščkova ulica", "Mekinčeva ulica", "Melikova ulica", + "Mencingerjeva ulica", "Merčnikova ulica", "Merosodna ulica", + "Mesesnelova ulica", "Mestni trg", "Meškova ulica", "Metelkova ulica", + "Miheličeva cesta", "Mihov štradon", "Miklavčeva ulica", + "Miklošičeva cesta", "Mikuževa ulica", "Milčetova pot", + "Mire Lenardičeve ulica", "Mirje", "Mirna pot", "Mislejeva ulica", + "Mizarska pot", "Mladinska ulica", "Mlake", "Mlinska pot", + "Močnikova ulica", "Mokrška ulica", "Molekova ulica", + "Moškričeva ulica", "Mrharjeva ulica", "Mrzelova ulica", + "Murkova ulica", "Murnikova ulica", "Murnova ulica", "Muzejska ulica", + "Na cvetači", "Na delih", "Na dolih", "Na gaju", "Na gmajni", + "Na Herši", "Na jami", "Na klančku", "Na Korošci", "Na Palcah", + "Na požaru", "Na produ", "Na Rojah", "Na Stolbi", "Na Straški vrh", + "Na Trati", "Na Žalah", "Nade Ovčakove ulica", "Nadgoriška cesta", + "Nahlikova ulica", "Nahtigalova ulica", "Nanoška ulica", + "Nazorjeva ulica", "Nebotičnikov prehod", "Nedohova ulica", + "Njegoševa cesta", "Nova ulica", "Novakova pot", "Novakova ulica", + "Novi trg", "Novinarska ulica", "Novo naselje", "Novo Polje, cesta I", + "Novo Polje, cesta III", "Novo Polje, cesta IV", + "Novo Polje, cesta V", "Novo Polje, cesta VI", "Novo Polje, cesta VII", + "Novo Polje, cesta X", "Novo Polje, cesta XI", "Novo Polje, cesta XII", + "Novo Polje, cesta XIV", "Novo Polje, cesta XIX", + "Novo Polje, cesta XVI", "Novo Polje, cesta XVII", + "Novo Polje, cesta XXI", "Novo Polje, cesta XXIII", "Novosadska ulica", + "Ob daljnovodu", "Ob dolenjski železnici", "Ob Farjevcu", + "Ob Ljubljanici", "Ob Mejašu", "Ob potoku", "Ob pristanu", "Ob Savi", + "Ob studencu", "Ob zdravstvenem domu", "Ob zeleni jami", "Ob zelenici", + "Ob žici", "Obirska ulica", "Obrežna steza", "Obrije", + "Ocvirkova ulica", "Ogrinčeva ulica", "Okiškega ulica", + "Omahnova ulica", "Omejčeva ulica", "Omersova ulica", + "Oražnova ulica", "Orlova ulica", "Osenjakova ulica", + "Osojna pot", "Osojna steza", "Osterčeva ulica", "Ovčakova ulica", + "Pahorjeva ulica", "Palmejeva ulica", "Papirniška pot", + "Park Ajdovščina", "Park Arturo Toscanini", + "Parmova ulica", "Parmska cesta", "Partizanska ulica", + "Pavlovčeva ulica", "Pavšičeva ulica", "Pečarjeva ulica", + "Pečnik", "Pečnikova ulica", "Pegamova ulica", "Perčeva ulica", + "Periška cesta", "Perkova ulica", "Peršinova cesta", + "Pesarska cesta", "Pestotnikova ulica", "Peščena pot", + "Petkova ulica", "Petkovškovo nabrežje", "Petrčeva ulica", + "Pilonova ulica", "Pionirska pot", "Pipanova pot", "Pirnatova ulica", + "Planinska cesta", "Planinškova ulica", "Plečnikov podhod", + "Plemljeva ulica", "Plešičeva ulica", "Pleteršnikova ulica", + "Pločanska ulica", "Pod akacijami", "Pod bregom", "Pod bresti", + "Pod bukvami", "Pod Debnim vrhom", "Pod gabri", "Pod gozdom", + "Pod hrasti", "Pod hribom", "Pod hruško", "Pod jelšami", + "Pod jezom", "Pod ježami", "Pod Kamno gorico", "Pod klancem", + "Pod lipami", "Pod topoli", "Pod Trančo", "Pod turnom", "Pod vrbami", + "Podgornikova ulica", "Podgorska cesta", "Podgrajska cesta", + "Podjunska ulica", "Podlimbarskega ulica", "Podmilščakova ulica", + "Podrožniška pot", "Podsmreška cesta", "Podutiška cesta", + "Pogačarjev trg", "Pohlinova ulica", "Poklukarjeva ulica", + "Polakova ulica", "Polanškova ulica", "Poljanska cesta", + "Polje", "Polje, cesta I", "Polje, cesta II", "Polje, cesta III", + "Polje, cesta VI", "Polje, cesta VIII", "Polje, cesta X", + "Polje, cesta XIV", "Polje, cesta XL", "Polje, cesta XLII", + "Polje, cesta XLVI", "Polje, cesta XVI", "Polje, cesta XVIII", + "Polje, cesta XXII", "Polje, cesta XXIV", "Polje, cesta XXVI", + "Polje, cesta XXX", "Polje, cesta XXXII", "Polje, cesta XXXIV", + "Polje, cesta XXXVIII", "Poljedelska ulica", "Poljska pot", + "Porentova ulica", "Posavskega ulica", "Postojnska ulica", + "Pot do šole", "Pot Draga Jakopiča", "Pot heroja Trtnika", + "Pot k igrišču", "Pot k ribniku", "Pot k Savi", "Pot k sejmišču", + "Pot k studencu", "Pot na Breje", "Pot na Drenikov vrh", + "Pot na Golovec", "Pot na goro", "Pot na Gradišče", "Pot na Grič", + "Pot na Labar", "Pot na mah", "Pot na most", "Pot na Orle", + "Pot na Visoko", "Pot na Zduše", "Pot Rdečega križa", + "Pot v boršt", "Pot v Čeželj", "Pot v dolino", "Pot v Goričico", + "Pot v hribec", "Pot v mejah", "Pot v Mlake", "Pot v Podgorje", + "Pot v Zeleni gaj", "Pot za Brdom", "Pot za razori", + "Potokarjeva ulica", "Potrčeva ulica", "Povšetova ulica", + "Prašnikarjeva ulica", "Praznikova ulica", "Pražakova ulica", + "Pred Savljami", "Predjamska cesta", "Predor pod Gradom", + "Preglov trg", "Prekmurska ulica", "Prelčeva ulica", "Preloge", + "Premrlova ulica", "Preradovićeva ulica", "Preserska ulica", + "Prešernov trg", "Prešernova cesta", "Pretnarjeva ulica", + "Pri borštu", "Pri brvi", "Pri malem kamnu", "Pri mostiščarjih", + "Pribinova ulica", "Prijateljeva ulica", "Primorska ulica", + "Prinčičeva ulica", "Prisojna ulica", "Prištinska ulica", "Privoz", + "Proletarska cesta", "Prule", "Prušnikova ulica", "Prvomajska ulica", + "Pšatnik", "Pšatska pot", "Ptujska ulica", "Pučnikova ulica", + "Puharjeva ulica", "Puhova ulica", "Puhtejeva ulica", + "Puterlejeva ulica", "Putrihova ulica", "Raičeva ulica", + "Rakovniška ulica", "Rakuševa ulica", "Ramovševa ulica", + "Ravbarjeva ulica", "Ravna pot", "Ravnikova ulica", + "Razgledna steza", "Reber", "Reboljeva ulica", "Rečna ulica", + "Regentova cesta", "Resljeva cesta", "Reška ulica", + "Ribičičeva ulica", "Ribji trg", "Ribniška ulica", + "Rimska cesta", "Rjava cesta", "Robbova ulica", "Robičeva ulica", + "Rodičeva ulica", "Rojčeva ulica", "Romavhova ulica", "Rosna pot", + "Rotarjeva ulica", "Rovšnikova ulica", "Rozmanova ulica", + "Rožanska ulica", "Rožičeva ulica", "Rožna dolina, cesta I", + "Rožna dolina, cesta III", "Rožna dolina, cesta IV", + "Rožna dolina, cesta V", "Rožna dolina, cesta VI", + "Rožna dolina, cesta VIII", "Rožna dolina, cesta X", + "Rožna dolina, cesta XII", "Rožna dolina, cesta XIII", + "Rožna dolina, cesta XV", "Rožna dolina, cesta XVII", + "Rožna ulica", "Rudnik I", "Rudnik II", "Rudnik III", "Runkova ulica", + "Ruska ulica", "Rutarjeva ulica", "Sadinja vas", "Sajovčeva ulica", + "Samova ulica", "Saškova ulica", "Sattnerjeva ulica", + "Savinova ulica", "Savinškova ulica", "Savlje", "Savska cesta", + "Sedejeva ulica", "Selanov trg", "Selanova ulica", + "Setnikarjeva ulica", "Seunigova ulica", "Simončičeva ulica", + "Siva pot", "Skapinova ulica", "Sketova ulica", "Skopčeva ulica", + "Skrbinškova ulica", "Slape", "Slapnikova ulica", "Slavčja ulica", + "Slomškova ulica", "Slovenčeva ulica", "Slovenska cesta", + "Smoletova ulica", "Smrekarjeva ulica", "Smrtnikova ulica", + "Snebersko nabrežje", "Snežniška ulica", "Snojeva ulica", + "Sojerjeva ulica", "Sončna pot", "Sostrska cesta", "Soška ulica", + "Soteška pot", "Soussenska ulica", "Sovretova ulica", + "Spodnji Rudnik I", "Spodnji Rudnik II", "Spodnji Rudnik III", + "Spodnji Rudnik V", "Spomeniška pot", "Srebrničeva ulica", + "Srednja pot", "Stadionska ulica", "Staničeva ulica", + "Stara Ježica", "Stara slovenska ulica", "Stare Črnuče", + "Stari trg", "Stegne", "Steletova ulica", "Sternadova ulica", + "Stiška ulica", "Stolpniška ulica", "Stoženska ulica", "Stožice", + "Stražarjeva ulica", "Streliška ulica", "Stritarjeva ulica", + "Strmeckijeva ulica", "Strmi pot", "Strniševa cesta", + "Strossmayerjeva ulica", "Strugarska ulica", "Strupijevo nabrežje", + "Suhadolčanova ulica", "Sulčja ulica", "Svetčeva ulica", + "Šarhova ulica", "Šentjakob", "Šentviška ulica", + "Šerkova ulica", "Šestova ulica", "Šibeniška ulica", + "Šinkov štradon", "Šišenska cesta", "Šivičeva ulica", + "Škerljeva ulica", "Škofova ulica", "Škrabčeva ulica", + "Šlandrova ulica", "Šlosarjeva ulica", "Šmarna gora", + "Šmartinska cesta", "Šmartno", "Španova pot", "Španska ulica", + "Štajerska cesta", "Štebijeva cesta", "Štefančeva ulica", + "Štembalova ulica", "Štepanjska cesta", "Štepanjsko nabrežje", + "Štirnova ulica", "Štradon čez Prošco", "Štrekljeva ulica", + "Študentovska ulica", "Štukljeva cesta", "Štula", + "Šturmova ulica", "Šubičeva ulica", "Šumarjeva ulica", + "Švabićeva ulica", "Švarova ulica", "Švegljeva cesta", "Tabor", + "Tacenska cesta", "Tavčarjeva ulica", "Tbilisijska ulica", + "Tesarska ulica", "Teslova ulica", "Tesna ulica", "Tesovnikova ulica", + "Tiha ulica", "Tiranova ulica", "Tischlerjeva ulica", + "Tivolska cesta", "Tkalska ulica", "Tobačna ulica", "Tolminska ulica", + "Tomačevo", "Tomačevska cesta", "Tomažičeva ulica", + "Tometova ulica", "Tominškova ulica", "Tomišeljska ulica", + "Toplarniška ulica", "Topniška ulica", "Torkarjeva ulica", + "Tratnikova ulica", "Travniška ulica", "Trbeže", "Trdinova ulica", + "Trebušakova ulica", "Trg francoske revolucije", + "Trg mladih", "Trg mladinskih delov. brigad", "Trg narodnih herojev", + "Trg prekomorskih brigad", "Trg republike", "Trg 9. maja", + "Trinkova ulica", "Trnovčeva ulica", "Trnovska ulica", + "Trpinčeva ulica", "Trstenjakova ulica", "Trtnikova ulica", + "Tržaška cesta", "Tržna ulica", "Tugomerjeva ulica", + "Turnerjeva ulica", "Turnsko nabrežje", "Udvančeva ulica", + "Ulica aktivistov", "Ulica Alme Sodnik", "Ulica Andreja Kumarja", + "Ulica Angelce Ocepkove", "Ulica Angele Ljubičeve", + "Ulica borca Petra", "Ulica borcev za severno mejo", + "Ulica bratov Bezlajev", "Ulica bratov Blanč", "Ulica bratov Jančar", + "Ulica bratov Komel", "Ulica bratov Kraljič", "Ulica bratov Martinec", + "Ulica bratov Novak", "Ulica bratov Rozmanov", "Ulica bratov Škofov", + "Ulica bratov Učakar", "Ulica bratov Židan", + "Ulica Dušana Kraigherja", "Ulica Ernesta Kramerja", + "Ulica Franca Nebca", "Ulica Francke Jerasove", "Ulica Franja Novaka", + "Ulica gledališča BTC", "Ulica Goce Delčeva", + "Ulica Gubčeve brigade", "Ulica Hermana Potočnika", + "Ulica Ivana Roba", "Ulica Ivanke Kožuh", "Ulica Ivice Pirjevčeve", + "Ulica Janeza Pavla II.", "Ulica Janeza Rožiča", + "Ulica Jožeta Jame", "Ulica Jožeta Japlja", "Ulica Jožeta Mirtiča", + "Ulica Konrada Babnika", "Ulica Koroškega bataljona", + "Ulica Lizike Jančarjeve", "Ulica Lojzeta Spacala", + "Ulica Lovre Klemenčiča", "Ulica Malči Beličeve", + "Ulica Marije Drakslerjeve", "Ulica Marije Hvaličeve", + "Ulica Marje Boršnikove", "Ulica Marka Šlajmerja", + "Ulica Milana Majcna", "Ulica Milke Kerinove", "Ulica Minke Bobnar", + "Ulica Mirka Jurce", "Ulica Mirka Tomšiča", "Ulica Miroslava Turka", + "Ulica Molniške čete", "Ulica na Grad", "Ulica Nade Čamernikove", + "Ulica Olge Mohorjeve", "Ulica padlih borcev", "Ulica Pariške komune", + "Ulica Pohorskega bataljona", "Ulica Polonce Čude", + "Ulica prvoborcev", "Ulica Rezke Dragarjeve", "Ulica Rezke Klopčič", + "Ulica Rudolfa Janežiča", "Ulica Staneta Severja", + "Ulica Štefke Zbašnikove", "Ulica talcev", + "Ulica Tončke Čečeve", "Ulica v Kokovšek", + "Ulica Vide Pregarčeve", "Ulica Vladimirja Trampuža", + "Ulica Zore Ragancinove", "Ulica Žanke Erjavec", + "Ulica 15. aprila", "Ulica 15. maja", "Ulica 24. avgusta", + "Ulica 4. julija", "Ulica 7. septembra", "Ulica 9. junija", + "Uršičev štradon", "Usnjarska ulica", "V Češnjico", "V dolini", + "V Karlovce", "V Karlovce", "V Kladeh", "V Murglah", "V Sige", + "V Varde", "V Zalar", "Vagajeva ulica", "Valjavčeva ulica", + "Valvasorjeva ulica", "Vandotova ulica", "Vaška pot", + "Večna pot", "Vegova ulica", "Velebitska ulica", + "Veliki štradon", "Velikovška ulica", "Velnarjeva ulica", + "Verovškova ulica", "Veršičeva ulica", "Veselova ulica", + "Videmska ulica", "Vidergarjeva ulica", "Vidičeva ulica", + "Vidovdanska cesta", "Vilharjev podhod", "Vilharjeva cesta", + "Vinterca", "Vipavska ulica", "Vipotnikova ulica", "Viška cesta", + "Vižmarska pot", "Vodmatska ulica", "Vodmatski trg", "Vodna steza", + "Vodnikova cesta", "Vodnikovo naselje", "Vodovodna cesta", + "Vogelna ulica", "Vojkova cesta", "Volaričeva ulica", + "Vošnjakova ulica", "Vozna pot na Grad", "Vožarski pot", + "Vrazov trg", "Vrbovec", "Vrbska ulica", "Vregova ulica", + "Vrhovci, cesta I", "Vrhovci, cesta II", "Vrhovci, cesta III", + "Vrhovci, cesta IX", "Vrhovci, cesta V", "Vrhovci, cesta VI", + "Vrhovci, cesta X", "Vrhovci, cesta XI", "Vrhovci, cesta XII", + "Vrhovci, cesta XIV", "Vrhovci, cesta XIX", "Vrhovci, cesta XV", + "Vrhovci, cesta XVII", "Vrhovci, cesta XVIII", "Vrhovci, cesta XX", + "Vrhovci, cesta XXII", "Vrhovci, cesta XXVI", "Vrhovci, cesta XXVIII", + "Vrhovci, cesta XXXII", "Vrhovčeva ulica", "Vrhovnikova ulica", + "Vrtača", "Vrtna ulica", "Vrtnarska cesta", "Vulčeva ulica", + "Vzajemna ulica", "Windischerjeva ulica", "Wolfova ulica", + "Za Garažami", "Za gasilskim domom", "Za Gradom", "Za krajem", + "Za opekarno", "Za partizanskim domom", "Za progo", "Za vasjo", + "Zadnikarjeva ulica", "Zadobrovška cesta", "Zadružna ulica", + "Zajčeva pot", "Zajčevi dvori", "Zakotnikova ulica", + "Zalaznikova ulica", "Zaletelova ulica", "Zaloška cesta", + "Zarnikova ulica", "Zasavska cesta", "Zatišje", "Zavetiška ulica", + "Završje", "Zbašnikova ulica", "Zdešarjeva cesta", + "Zelena pot", "Zelenova ulica", "Zeljarska ulica", + "Zevnikova ulica", "Zidarjev štradon", "Ziherlova ulica", + "Zlatek", "Znamenjska ulica", "Zofke Kvedrove ulica", "Zoisova cesta", + "Zupanova ulica", "Zvezda", "Zvezdarska ulica", "Zvezna ulica", + "Žabarjeva ulica", "Žabjak", "Žalska ulica", "Žaucerjeva ulica", + "Žeje", "Železna cesta", "Železnikarjeva ulica", "Žerjalova ulica", + "Židankova ulica", "Židovska steza", "Židovska ulica", + "Živaličeva ulica", "Živinozdravska ulica", "Žolgerjeva ulica", + + ) + + states = ( + 'Pomurksa', 'Podravska', 'Koroška', 'Savinjska', 'Zasavska', + 'Spodnjeposavska', 'Jugovzhodna Slovenija', 'Osrednjeslovenska', + 'Gorenjska', 'Notranjsko - kraška', 'Goriška', 'Obalno - kraška', + ) + + countries = ( + "Afganistan", "Islamska republika Afganistan", "Albanija", + "Alžirija", "Ljudska demokratična republika Alžirija", "Andora", + "Angola", "Republika Angola", "Antigva in Barbuda", "Argentina", + "Armenija", "Republika Armenija", "Avstralija", "Avstrija", + "Azerbajdžan", "Azerbajdžanska republika", "Bahami", "Zveza Bahami", + "Država Bahrajn", "Bangladeš", "Ljudska republika Bangladeš", + "Belgija", "Kraljevina Belgija", "Belize", "Belorusija", + "Benin", "Republika Benin", "Bocvana", "Republika Bocvana", + "Republika Bolgarija", "Bolivija", "Republika Bolivija", + "Brazilija", "Federativna republika Brazilija", "Brunej", + "Burkina Faso", "Burundi", "Republika Burundi", "Butan", + "Ciper", "Republika Ciper", "Čad", "Republika Čad", "Češka", + "Čile", "Republika Čile", "Črna gora", "Republika Črna gora", + "Kraljevina Danska", "Dominika", "Zveza Dominika", + "Džibuti", "Republika Džibuti", "Egipt", "Arabska republika Egipt", + "Republika Ekvador", "Ekvatorialna Gvineja", "Eritreja", + "Estonija", "Republika Estonija", "Etiopija", "Fidži", + "Filipini", "Republika Filipini", "Finska", "Republika Finska", + "Francoska republika", "Gabon", "Gabonska republika", "Gambija", + "Gana", "Republika Gana", "Grčija", "Helenska republika", "Grenada", + "Gvajana", "Republika Gvajana", "Gvatemala", "Republika Gvatemala", + "Republika Gvineja", "Gvineja Bissau", "Republika Gvineja Bissau", + "Republika Haiti", "Honduras", "Republika Honduras", "Hrvaška", + "Indija", "Republika Indija", "Indonezija", "Republika Indonezija", + "Republika Irak", "Iran", "Islamska republika Iran", "Irska", + "Republika Islandija", "Italija", "Italijanska republika", "Izrael", + "Jamajka", "Japonska", "Jemen", "Republika Jemen", "Jordanija", + "Južna Afrika", "Republika Južna Afrika", "Južna Koreja", + "Kambodža", "Kraljevina Kambodža", "Kamerun", "Republika Kamerun", + "Katar", "Država Katar", "Kazahstan", "Republika Kazahstan", "Kenija", + "Kirgizistan", "Kirgiška republika", "Kiribati", "Kitajska", + "Kolumbija", "Republika Kolumbija", "Komori", + "Kongo", "Republika Kongo", "Demokratična republika Kongo", + "Republika Kostarika", "Kuba", "Republika Kuba", "Kuvajt", + "Laos", "Laoška ljudska demokratična republika", "Latvija", + "Lesoto", "Kraljevina Lesoto", "Libanon", "Libanonska republika", + "Republika Liberija", "Libija", "Libijska arabska džamahirija", + "Lihtenštajn", "Kneževina Lihtenštajn", "Litva", "Republika Litva", + "Veliko vojvodstvo Luksemburg", "Madagaskar", "Republika Madagaskar", + "Republika Madžarska", "Makedonija", "Republika Makedonija", "Malavi", + "Maldivi", "Republika Maldivi", "Malezija", "Mali", "Republika Mali", + "Republika Malta", "Maroko", "Kraljevina Maroko", "Marshallovi otoki", + "Mauritius", "Republika Mauritius", "Mavretanija", + "Mehika", "Združene mehiške države", "Mikronezija", + "Mjanmar", "Zveza Mjanmar", "Moldavija", "Moldavija, Republika", + "Kneževina Monako", "Mongolija", "Mozambik", "Republika Mozambik", + "Republika Namibija", "Nauru", "Republika Nauru", "Nemčija", + "Nepal", "Kraljevina Nepal", "Niger", "Republika Niger", "Nigerija", + "Nikaragva", "Republika Nikaragva", "Nizozemska", + "Norveška", "Kraljevina Norveška", "Nova Zelandija", "Oman", + "Pakistan", "Islamska republika Pakistan", "Palau", "Republika Palau", + "Republika Panama", "Papua Nova Gvineja", "Paragvaj", + "Peru", "Republika Peru", "Poljska", "Republika Poljska", + "Portugalska republika", "Romunija", "Ruanda", "Republika Ruanda", + "Ruska federacija", "Saint Kitts in Nevis", "Saint Lucia", + "Salomonovi otoki", "Salvador", "Republika Salvador", "San Marino", + "Sao Tome in Principe", "Demokratična republika Sao Tome in Principe", + "Kraljevina Saudova Arabija", "Sejšeli", "Republika Sejšeli", + "Republika Senegal", "Severna Koreja", + "Sierra Leone", "Republika Sierra Leone", "Singapur", + "Sirija", "Sirska arabska republika", "Slonokoščena obala", + "Slovaška", "Slovaška republika", "Slovenija", "Republika Slovenija", + "Somalska demokratična republika", "Srbija", "Republika Srbija", + "Sudan", "Republika Sudan", "Surinam", "Republika Surinam", "Svazi", + "Španija", "Kraljevina Španija", "Šrilanka", + "Švedska", "Kraljevina Švedska", "Švica", + "Tadžikistan", "Republika Tadžikistan", "Tajska", + "Tajvan", "Tajvan, Provinca Kitajske", "Tanzanija", + "Togo", "Togoška republika", "Tonga", "Kraljevina Tonga", + "Republika Trinidad in Tobago", "Tunizija", "Republika Tunizija", + "Republika Turčija", "Turkmenistan", "Tuvalu", "Uganda", + "Ukrajina", "Urugvaj", "Vzhodna republika Urugvaj", "Uzbekistan", + "Vanuatu", "Republika Vanuatu", "Vatikan", + "Velika Britanija", "Združeno kraljestvo", + "Venezuela", "Republika Venezuela", "Vietnam", + "Vzhodni Timor", "Demokratična republika Vzhodni Timor", + "Samoa", "Neodvisna država Zahodna Samoa", "Zambija", + "Združene države Amerike", "Združene države", + "Združeni arabski emirati", "Zelenortski otoki", + ) + + def city_name(self): + return self.random_element(self.cities) + + def street_name(self): + return self.random_element(self.streets) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/sv_SE/__init__.py b/testbed/joke2k__faker/faker/providers/address/sv_SE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9548ec6dc8923952f771de72fc1068a2fccaef0e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/sv_SE/__init__.py @@ -0,0 +1,107 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + building_number_formats = ('###', '##', '#') + + street_name_formats = ('{{street_prefix}}{{street_suffix}}', ) + + street_address_formats = ('{{street_name}} {{building_number}}',) + + street_prefixes = ( + 'Björk', 'Järnvägs', 'Ring', 'Skol', 'Skogs', 'Ny', 'Gran', 'Idrotts', + 'Stor', 'Kyrk', 'Industri', 'Park', 'Strand', 'Skol', 'Trädgårds', + 'Industri', 'Ängs', 'Kyrko', 'Park', 'Villa', 'Ek', 'Kvarn', 'Stations', + 'Back', 'Furu', 'Gen', 'Fabriks', 'Åker', 'Bäck', 'Asp', + ) + + street_suffixes = ('gatan', 'gatan', 'vägen', 'vägen', + 'stigen', 'gränd', 'torget') + + address_formats = ("{{street_address}}\n{{postcode}} {{city}}", ) + + postcode_formats = ('#####', ) + + city_formats = ('{{city_name}}', ) + + cities = ( + 'Stockholm', 'Göteborg', 'Malmö', 'Uppsala', 'Västerås', 'Örebro', + 'Linköping', 'Helsingborg', 'Jönköping', 'Norrköping', 'Lund', 'Umeå', + 'Gävle', 'Borås', 'Mölndal', 'Södertälje', 'Eskilstuna', 'Karlstad', + 'Halmstad', 'Växjö', 'Sundsvall', 'Luleå', 'Trollhättan', 'Östersund', + 'Borlänge', 'Falun', 'Kalmar', 'Skövde', 'Kristianstad', 'Karlskrona', + 'Skellefteå', 'Uddevalla', 'Lidingö', 'Motala', 'Landskrona', + 'Örnsköldsvik', 'Nyköping', 'Karlskoga', 'Varberg', 'Trelleborg', + 'Lidköping', 'Alingsås', 'Piteå', 'Sandviken', 'Ängelholm', + ) + + countries = ( + 'Afghanistan', 'Albanien', 'Algeriet', 'Amerikanska Samoa', 'Andorra', + 'Angola', 'Anguilla', 'Antarktis', 'Antigua och Barbuda', 'Argentina', + 'Armenien', 'Aruba', 'Ascension', 'Australien', 'Azerbajdzjan', + 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belgien', 'Belize', + 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnien och Hercegovina', + 'Botswana', 'Brasilien', 'Brittiska Jungfruöarna', 'Brunei', + 'Bulgarien', 'Burkina Faso', 'Burma', 'Burundi', 'Caymanöarna', + 'Centralafrikanska republiken', 'Chile', 'Colombia', 'Cooköarna', + 'Costa Rica', 'Cypern', 'Danmark', 'Diego Garcia', 'Djibouti', + 'Dominica', 'Dominikanska republiken', 'Ecuador', 'Egypten', + 'Ekvatorialguinea', 'Elfenbenskusten', 'El Salvador', 'Eritrea', + 'Estland', 'Etiopien', 'England', 'Falklandsöarna', 'Fiji', + 'Filippinerna', 'Finland', 'Frankrike', 'Franska Guyana', + 'Franska Polynesien', 'Färöarna', 'Förenade Arabemiraten', 'Gabon', + 'Gambia', 'Georgien', 'Ghana', 'Gibraltar', 'Grekland', 'Grenada', + 'Grönland', 'Guadeloupe', 'Guatemala', 'Guinea', 'Guinea-Bissau', + 'Guyana', 'Haiti', 'Honduras', 'Hongkong', 'Indien', 'Indonesien', + 'Irak', 'Iran', 'Irland', 'Island', 'Israel', 'Italien', 'Jamaica', + 'Japan', 'Jemen', 'Jordanien', 'Kambodja', 'Kamerun', 'Kanada', + 'Kap Verde', 'Kazakstan', 'Kenya', 'Kina', 'Kirgizistan', 'Kiribati', + 'Komorerna', 'Kongo-Brazzaville', 'Kongo-Kinshasa', 'Kosovo', + 'Kroatien', 'Kuba', 'Kuwait', 'Laos', 'Lesotho', 'Lettland', 'Libanon', + 'Liberia', 'Libyen', 'Liechtenstein', 'Litauen', 'Luxemburg', 'Macao', + 'Madagaskar', 'Makedonien', 'Malawi', 'Malaysia', 'Maldiverna', 'Mali', + 'Malta', 'Marianerna', 'Marocko', 'Marshallöarna', 'Martinique', + 'Mauretanien', 'Mauritius', 'Mayotte', 'Mexiko', 'Midwayöarna', + 'Mikronesiens federerade stater', 'Moçambique', 'Moldavien', 'Monaco', + 'Mongoliet', 'Montenegro', 'Montserrat', 'Namibia', 'Nauru', + 'Nederländerna', 'Nederländska Antillerna', 'Nepal', + 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Nordkorea', 'Nordmarianerna', + 'Norfolkön', 'Norge', 'Nya Kaledonien', 'Nya Zeeland', 'Oman', + 'Pakistan', 'Palau', 'Palestina', 'Panama', 'Papua Nya Guinea', + 'Paraguay', 'Peru', 'Pitcairnöarna', 'Polen', 'Portugal', 'Qatar', + 'Réunion', 'Rumänien', 'Rwanda', 'Ryssland', 'Saint Kitts och Nevis', + 'Saint Lucia', 'Saint-Pierre och Miquelon', + 'Saint Vincent och Grenadinerna', 'Salomonöarna', 'Samoa', + 'Sankta Helena', 'San Marino', 'São Tomé och Príncipe', + 'Saudiarabien', 'Schweiz', 'Senegal', 'Serbien', 'Seychellerna', + 'SierraLeone', 'Singapore', 'Sint Maarten', 'Slovakien', 'Slovenien', + 'Somalia', 'Spanien', 'Sri Lanka', 'Storbritannien', 'Sudan', + 'Surinam', 'Sverige', 'Swaziland', 'Sydafrika', 'Sydkorea', 'Sydsudan', + 'Syrien', 'Tadzjikistan', 'Taiwan', 'Tanzania', 'Tchad', 'Thailand', + 'Tjeckien', 'Togo', 'Tokelauöarna', 'Tonga', 'Trinidad och Tobago', + 'Tunisien', 'Turkiet', 'Turkmenistan', 'Turks-och Caicosöarna', + 'Tuvalu', 'Tyskland', 'Uganda', 'Ukraina', 'Ungern', 'Uruguay', 'USA', + 'Uzbekistan', 'Vanuatu', 'Vatikanstaten', 'Venezuela', 'Vietnam', + 'Vitryssland', 'Wake', 'Wallis-och Futunaöarna', 'Zambia', 'Zimbabwe', + 'Österrike', 'Östtimor', + ) + + states = ( + 'Stockholms län', 'Uppsala län', 'Södermanlands län', + 'Östergötlands län', 'Jönköpings län', 'Kronobergs län', 'Kalmar län', + 'Gotlands län', 'Blekinge län', 'Skåne län', 'Hallands län', + 'Västra Götalands län', 'Värmlands län', 'Örebro län', + 'Västmanlands län', 'Dalarnas län', 'Gävleborgs län', + 'Västernorrlands län', 'Jämtlands län', 'Västerbottens län', + 'Norrbottens län', + ) + + def street_prefix(self): + return self.random_element(self.street_prefixes) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/ta_IN/__init__.py b/testbed/joke2k__faker/faker/providers/address/ta_IN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de37e2b48eb344b6bdcaedf800d6b2d19ab56999 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/ta_IN/__init__.py @@ -0,0 +1,418 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + + city_formats = ('{{city_name}}', ) + + street_name_formats = ( + '{{first_name}} {{last_name}}', + '{{last_name}}', + ) + + street_address_formats = ('{{building_number}} {{street_name}}', ) + + address_formats = ('{{street_address}}\n{{city}} {{postcode}}', + '{{street_address}}\n{{city}}-{{postcode}}') + + building_number_formats = ( + '####', '###', '##', '#', '#/#', '##/##', '##/###', '##/####') + + postcode_formats = ('######', ) + + # Source: https://ta.wikipedia.org/wiki/மக்கள்_தொகை_மிகுந்த_இந்திய_நகரங்கள் + cities = ( + 'சென்னை', + 'கோயம்புத்தூர்', + 'மதுரை', + 'திருச்சிராப்பள்ளி', + 'திருப்பூர்', + 'சேலம்', + 'ஈரோடு', + 'திருநெல்வேலி', + 'வேலூர்', + 'தூத்துக்குடி', + 'திண்டுக்கல்', + 'தஞ்சாவூர்', + 'இராணிப்பேட்டை', + 'சிவகாசி', + 'கரூர் (கரூர் மாவட்டம்)', + 'உதகமண்டலம்', + 'ஓசூர்', + 'நாகர்கோவில்', + 'காஞ்சிபுரம்', + 'குமாரபாளையம்', + 'காரைக்குடி', + 'நெய்வேலி', + 'கடலூர்', + 'கும்பகோணம்', + 'திருவண்ணாமலை', + 'பொள்ளாச்சி', + 'இராஜபாளையம், விருதுநகர் மாவட்டம்', + 'குடியாத்தம்', + 'புதுக்கோட்டை', + 'வாணியம்பாடி', + 'ஆம்பூர்', + 'நாகப்பட்டினம்', + 'மும்பை பெருநகர்', + 'தில்லி', + 'கொல்கத்தா பெருநகர்', + 'சென்னை பெருநகர்', + 'பெங்களூரு', + 'ஐதராபாத்', + 'புனே', + 'அகமதாபாத்', + 'கான்பூர்', + 'சூரத்', + 'ஜெய்ப்பூர்', + 'லக்னோ', + 'பாட்னா', + 'நாக்பூர்', + 'இந்தோர்', + 'மீரட்', + 'நாசிக்', + 'போபால்', + 'லூதியானா', + 'ஆக்ரா', + 'வதோதரா', + 'புவனேசுவர்', + 'கோயம்புத்தூர்', + 'ராஜ்கோட்', + 'கொச்சி', + 'விசாகப்பட்டினம்', + 'வாரணாசி', + 'மதுரை', + 'ஆசன்சோல்', + 'அலகாபாத்', + 'மைசூர்', + 'ஜபல்பூர்', + 'ஜம்சேத்பூர்', + 'அவுரங்கபாத்', + 'அம்ரித்சர்', + 'தன்பாத்', + 'விஜயவாடா', + 'சோலாப்பூர்', + 'பிலாய்', + 'ஸ்ரீநகர்', + 'ராஞ்சி', + 'திருவனந்தபுரம்', + 'சண்டிகர்', + 'குவஹாத்தி', + 'கோழிக்கோடு', + 'ஜோத்பூர்', + 'குவாலியர்', + 'ஜலந்தர்', + 'திருச்சிராப்பள்ளி', + 'பரேலி', + 'ஹுப்ளி-தர்வாத்', + 'அலிகார்', + 'கோட்டா', + 'மொரதாபாத்', + 'ராய்ப்பூர்', + 'தேராதூன்', + 'கோரக்பூர்', + 'ஜம்மு', + 'அமராவதி', + 'வாரங்கல்', + 'ஜாம்நகர்', + 'பிகானேர்', + 'சாங்கலி', + 'திருப்பூர்', + 'பாவ்நகர்', + 'மங்களூர்', + 'அஜ்மீர்', + 'பொகாரோ', + 'பெல்காம்', + 'புதுச்சேரி', + 'சிலிகுரி', + 'கண்ணூர்', + 'கோலாப்பூர்', + 'நான்தேட்', + 'ரூர்கேலா', + 'துர்காபூர்', + 'குல்பர்கா', + 'குண்டூர்', + 'ஜான்சி', + 'சகாரன்பூர்', + 'கரக்பூர்', + 'கயா', + 'ஜல்கான்', + 'மதுரா', + 'கொல்லம்', + 'கோர்பா', + 'பிரோசாபாத்', + 'திருநெல்வேலி', + 'உஜ்ஜைன்', + 'அகமத்நகர்', + 'நெல்லூர்', + 'ராமகுண்டம்', + 'ராஜமுந்திரி', + 'மாலேகான்', + 'உதயப்பூர்', + 'அகோலா', + 'தாவண்கரே', + 'வேலூர்', + 'திருவண்ணாமலை', + 'காஜுவாகா', + ) + + # Source: https://ta.wikipedia.org/wiki/இந்தியாவின்_மாநிலங்களும்_ஆட்சிப்பகுதிகளும் + states = ( + 'ஆந்திரப் பிரதேசம்', + 'அருணாச்சலப் பிரதேசம்', + 'அசாம்', + 'பீகார்', + 'சத்தீஸ்கர்', + 'கோவா', + 'குஜராத்', + 'அரியானா', + 'இமாச்சலப் பிரதேசம்', + 'சம்மு காசுமீர்', + 'ஜார்கண்ட்', + 'கர்நாடகா', + 'கேரளா', + 'மத்தியப் பிரதேசம்', + 'மகாராஷ்டிரா', + 'மணிப்பூர்', + 'மேகாலயா', + 'மிசோரம்', + 'நாகலாந்து', + 'ஒரிசா', + 'பஞ்சாப்', + 'ராஜஸ்தான்', + 'சிக்கிம்', + 'தமிழ்நாடு', + 'தெலுங்கானா', + 'திரிபுரா', + 'உத்தரப்பிரதேசம்', + 'உத்தரகண்ட்', + 'மேற்கு வங்கம்', + ) + + # Source: https://ta.wikipedia.org/wiki/பிறப்பு_விகித_அடிப்படையில்_நாடுகளின்_பட்டியல் + countries = ( + 'ஆப்கானித்தான்', + 'அல்பேனியா', + 'அல்ஜீரியா', + 'அந்தோரா', + 'அங்கோலா', + 'அன்டிகுவா பர்புடா', + 'அர்கெந்தீனா', + 'ஆர்மீனியா', + 'ஆத்திரேலியா', + 'ஆஸ்திரியா', + 'அசர்பைஜான்', + 'பஹமாஸ்', + 'பகுரைன்', + 'வங்காளதேசம்', + 'பார்படோசு', + 'பெலருஸ்', + 'பெல்ஜியம்', + 'பெலீசு', + 'பெனின்', + 'பூட்டான்', + 'பொலிவியா', + 'பொசுனியா எர்செகோவினா', + 'போட்சுவானா', + 'பிரேசில்', + 'புரூணை', + 'பல்கேரியா', + 'புர்க்கினா பாசோ', + 'புருண்டி', + 'கம்போடியா', + 'கமரூன்', + 'கனடா', + 'கேப் வர்டி', + 'மத்திய ஆப்பிரிக்கக் குடியரசு', + 'சாட்', + 'சிலி', + 'சீனா', + 'கொலம்பியா', + 'கொமொரோசு', + 'காங்கோ மக்களாட்சிக் குடியரசு', + 'காங்கோ மக்களாட்சிக் குடியரசு', + 'கோஸ்ட்டா ரிக்கா', + 'ஐவரி கோஸ்ட்', + 'குரோவாசியா', + 'கியூபா', + 'சைப்பிரசு', + 'செக் குடியரசு', + 'டென்மார்க்', + 'சீபூத்தீ', + 'டொமினிக்கா', + 'டொமினிக்கன் குடியரசு', + 'எக்குவடோர்', + 'எகிப்து', + 'எல் சல்வடோர', + 'எக்குவடோரியல் கினி', + 'எரித்திரியா', + 'எசுத்தோனியா', + 'எதியோப்பியா', + 'பிஜி', + 'பின்லாந்து', + 'பிரான்சு', + 'காபொன்', + 'கம்பியா', + 'சியார்சியா', + 'செருமனி', + 'கானா', + 'கிரேக்க நாடு', + 'கிரெனடா', + 'குவாத்தமாலா', + 'கினியா', + 'கினி-பிசாவு', + 'கயானா', + 'எயிட்டி', + 'ஒண்டுராசு', + 'அங்கேரி', + 'ஐசுலாந்து', + 'இந்தியா', + 'இந்தோனேசியா', + 'ஈரான்', + 'ஈராக்', + 'அயர்லாந்து', + 'இசுரேல்', + 'இத்தாலி', + 'ஜமேக்கா', + 'சப்பான்', + 'யோர்தான்', + 'கசக்கஸ்தான்', + 'கென்யா', + 'கிரிபட்டி', + 'வட கொரியா', + 'தென் கொரியா', + 'குவைத்', + 'கிர்கிசுத்தான்', + 'லாவோஸ்', + 'லாத்வியா', + 'லெபனான்', + 'லெசோத்தோ', + 'லைபீரியா', + 'லிபியா', + 'லீக்கின்ஸ்டைன்', + 'லித்துவேனியா', + 'லக்சம்பர்க்', + 'மாக்கடோனியக் குடியரசு', + 'மடகாசுகர்', + 'மலாவி', + 'மலேசியா', + 'மாலைத்தீவுகள்', + 'மாலி', + 'மால்ட்டா', + 'மார்சல் தீவுகள்', + 'மூரித்தானியா', + 'மொரிசியசு', + 'மெக்சிக்கோ', + 'மைக்குரோனீசியக் கூட்டு நாடுகள்', + 'மல்தோவா', + 'மொனாகோ', + 'மங்கோலியா', + 'மொண்டெனேகுரோ', + 'மொரோக்கோ', + 'மொசாம்பிக்', + 'மியான்மர்', + 'நமீபியா', + 'நவூரு', + 'நேபாளம்', + 'நெதர்லாந்து', + 'நியூசிலாந்து', + 'நிக்கராகுவா', + 'நைஜர்', + 'நைஜீரியா', + 'நோர்வே', + 'ஓமான்', + 'பாக்கித்தான்', + 'பலாவு', + 'பலத்தீன்', + 'பனாமா', + 'பப்புவா நியூ கினி', + 'பரகுவை', + 'பெரு', + 'பிலிப்பீன்சு', + 'போலந்து', + 'போர்த்துகல்', + 'கட்டார்', + 'உருமேனியா', + 'உருசியா', + 'ருவாண்டா', + 'செயிண்ட். கிட்ஸ் நெவிஸ்', + 'செயிண்ட். லூசியா', + 'செயின்ட் வின்செண்டு மற்றும் கிரெனடீன்கள்', + 'சமோவா', + 'சான் மரீனோ', + 'சாவோ தொமே மற்றும் பிரின்சிப்பி', + 'சவூதி அரேபியா', + 'செனிகல்', + 'செர்பியா', + 'சீசெல்சு', + 'சியேரா லியோனி', + 'சிங்கப்பூர்', + 'சிலவாக்கியா', + 'சுலோவீனியா', + 'சொலமன் தீவுகள்', + 'சோமாலியா', + 'தென்னாப்பிரிக்கா', + 'தெற்கு சூடான்', + 'எசுப்பானியா', + 'இலங்கை', + 'சூடான்', + 'சுரிநாம்', + 'சுவாசிலாந்து', + 'சுவீடன்', + 'சுவிட்சர்லாந்து', + 'சிரியா', + 'சீனக் குடியரசு', + 'தாஜிக்ஸ்தான்', + 'தன்சானியா', + 'தாய்லாந்து', + 'கிழக்குத் திமோர்', + 'டோகோ', + 'தொங்கா', + 'டிரினிடாட் மற்றும் டொபாகோ', + 'தூனிசியா', + 'துருக்கி', + 'துருக்மெனிஸ்தான்', + 'துவாலு', + 'உகாண்டா', + 'உக்ரைன்', + 'ஐக்கிய அரபு அமீரகம்', + 'ஐக்கிய இராச்சியம்', + 'ஐக்கிய அமெரிக்கா', + 'உருகுவை', + 'உஸ்பெகிஸ்தான்', + 'வனுவாட்டு', + 'வெனிசுவேலா', + 'வியட்நாம்', + 'மேற்கு சகாரா (Sahrawi)', + 'யேமன்', + 'சாம்பியா', + 'சிம்பாப்வே', + 'அங்கியுலா (UK)', + 'அரூபா (Netherlands)', + 'பெர்முடா (UK)', + 'கேமன் தீவுகள் (UK)', + 'குயெர்ன்சி (கால்வாய் தீவுகள், UK)', + 'யேர்சி (கால்வாய் தீவுகள், UK)', + 'குக் தீவுகள் (New Zealand)', + 'குராசோ (Netherlands)', + 'போக்லாந்து தீவுகள்/Malvinas', + 'பரோயே தீவுகள் (Denmark)', + 'கிப்ரல்டார் (UK)', + 'கிறீன்லாந்து (Denmark)', + 'குவாதலூப்பு (France)', + 'குவாம் (USA)', + 'பிரெஞ்சு கயானா', + 'ஆங்காங்', + 'மாண் தீவு (UK)', + 'கொசோவோ', + 'மக்காவு', + 'மர்தினிக்கு (France)', + 'மயோட்டே (France)', + 'மொன்செராட்', + ) + + def city_name(self): + return self.random_element(self.cities) + + def state(self): + return self.random_element(self.states) diff --git a/testbed/joke2k__faker/faker/providers/address/tl_PH/__init__.py b/testbed/joke2k__faker/faker/providers/address/tl_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10fd37a784a9cf241ca82695ef429bb1d06d95a0 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/tl_PH/__init__.py @@ -0,0 +1,6 @@ +from ..en_PH import Provider as EnPhAddressProvider + + +class Provider(EnPhAddressProvider): + """No difference from Address Provider for en_PH locale""" + pass diff --git a/testbed/joke2k__faker/faker/providers/address/uk_UA/__init__.py b/testbed/joke2k__faker/faker/providers/address/uk_UA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ebf720bbecfab37656715bebdebfa5f6845c10 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/uk_UA/__init__.py @@ -0,0 +1,173 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + address_formats = ['{{street_address}}, {{city}}, {{postcode}}'] + building_number_formats = ['#', '##', '###'] + city_formats = ['{{city_prefix}} {{first_name}}'] + street_address_formats = ['{{street_name}}, {{building_number}}'] + street_name_formats = ('{{street_prefix}} {{street_title}}', ) + + city_prefixes = ['місто', 'село', 'селище', 'хутір'] + countries = [ + 'Австралія', 'Австрія', 'Азербайджан', 'Албанія', 'Алжир', 'Ангола', + 'Андорра', 'Антигуа і Барбуда', 'Аргентина', 'Афганістан', + 'Багамські Острови', 'Бангладеш', 'Барбадос', 'Бахрейн', 'Беліз', + 'Бельгія', 'Бенін', 'Білорусь', 'Болгарія', 'Болівія', + 'Боснія і Герцеговина', 'Ботсвана', 'Бразилія', 'Бруней', + 'Буркіна-Фасо', 'Бурунді', 'Бутан', 'Вануату', 'Ватикан', + 'Велика Британія', 'Венесуела', 'В\'єтнам', 'Вірменія', 'Габон', + 'Гаїті', 'Гаяна', 'Гамбія', 'Гана', 'Гватемала', 'Гвінея', + 'Гвінея-Бісау', 'Гондурас', 'Гренада', 'Греція', 'Грузія', 'Данія', + 'Джибуті', 'Домініка', 'Домініканська Республіка', 'Еквадор', + 'Екваторіальна Гвінея', 'Еритрея', 'Естонія', 'Ефіопія', 'Єгипет', + 'Ємен', 'Замбія', 'Західна Сахара', 'Зімбабве', 'Ізраїль', 'Індія', + 'Індонезія', 'Ірак', 'Іран', 'Ірландія', 'Ісландія', 'Іспанія', + 'Італія', 'Йорданія', 'Кабо-Верде', 'Казахстан', 'Камбоджа', 'Камерун', + 'Канада', 'Катар', 'Кенія', 'Киргизстан', 'КНР', 'Кіпр', 'Кірибаті', + 'Колумбія', 'Коморські Острови', 'Конго', 'ДР Конго', 'Південна Корея', + 'Північна Корея', 'Косово', 'Коста-Рика', 'Кот-д\'Івуар', 'Куба', + 'Кувейт', 'Лаос', 'Латвія', 'Лесото', 'Литва', 'Ліберія', 'Ліван', + 'Лівія', 'Ліхтенштейн', 'Люксембург', 'Маврикій', 'Мавританія', + 'Мадагаскар', 'Республіка Македонія', 'Малаві', 'Малайзія', 'Малі', + 'Мальдіви', 'Мальта', 'Марокко', 'Маршаллові Острови', 'Мексика', + 'Федеративні Штати Мікронезії', 'Мозамбік', 'Молдова', 'Монако', + 'Монголія', 'М\'янма', 'Намібія', 'Науру', 'Непал', 'Нігер', 'Нігерія', + 'Нідерланди', 'Нікарагуа', 'Німеччина', 'Нова Зеландія', 'Норвегія', + 'ОАЕ', 'Оман', 'Пакистан', 'Палау', 'Палестинська держава', 'Панама', + 'Папуа Нова Гвінея', 'ПАР', 'Парагвай', 'Перу', 'Південний Судан', + 'Польща', 'Португалія', 'Росія', 'Руанда', 'Румунія', 'Сальвадор', + 'Самоа', 'Сан-Марино', 'Сан-Томе і Принсіпі', 'Саудівська Аравія', + 'Свазіленд', 'Сейшельські Острови', 'Сенегал', + 'Сент-Вінсент і Гренадини', 'Сент-Кіттс і Невіс', 'Сент-Люсія', + 'Сербія', 'Сінгапур', 'Сирія', 'Словаччина', 'Словенія', + 'Соломонові Острови', 'Сомалі', 'Судан', 'Суринам', 'Східний Тимор', + 'США', 'Сьєрра-Леоне', 'Таджикистан', 'Таїланд', 'Тайвань', 'Танзанія', + 'Того', 'Тонга', 'Тринідад і Тобаго', 'Тувалу', 'Туніс', 'Туреччина', + 'Туркменістан', 'Уганда', 'Угорщина', 'Узбекистан', 'Україна', + 'Уругвай', 'Фіджі', 'Філіппіни', 'Фінляндія', 'Франція', 'Хорватія', + 'Центральноафриканська Республіка', 'Чад', 'Чехія', 'Чилі', + 'Чорногорія', 'Швейцарія', 'Швеція', 'Шрі-Ланка', 'Ямайка', 'Японія', + ] + street_prefixes = [ + 'вулиця', 'набережна', + ] + street_suffixes = ['узвіз'] + + street_titles = [ + '40-летия Октября', + 'Академика Шлихтера', + 'Алексея Давыдова', + 'Анищенко', + 'Антонова-Овсеенко', + 'Артема', + 'Бабушкина', + 'Бакинских Комиссаров', + 'Баумана', + 'Блюхера', + 'Боженко', + 'Бонч-Бруевича', + 'Буденного', + 'Ветрова', + 'Воровского', + 'Воссоединения', + 'Гамарника', + 'Горького', + 'Дзержинского', + 'Димитрова', + 'Дубового Ивана', + 'Дундича Олеко', + 'Жданова', + 'Ивана Клименко', + 'Ивана Лепсе', + 'Иванова Андрея', + 'Ильича', + 'Калининская', + 'Киквидзе', + 'Кирова', + 'Коллективизации', + 'Коллонтай', + 'Командарма Уборевич', + 'Комиссара Рыкова', + 'Коммунистическая', + 'Комсомольская', + 'Котовского', + 'Кравченко Николая', + 'Красикова Петра', + 'Красноармейская', + 'Красногвардейская', + 'Краснопартизанская', + 'Краснофлотская', + 'Крупской', + 'Крыленко', + 'Кутузова', + 'Лазо Сергея', + 'Лайоша Гавро', + 'Ластовского', + 'Ленина', + 'Ленинская', + 'Луначарского', + 'Майорова Михаила', + 'Маршала Буденного', + 'Маршала Тухачевского', + 'Мате Залки', + 'Машина Михаила', + 'Мильчакова Александра', + 'Михаила Скрипника', + 'Московская', + 'Октябрьская', + 'Омельяна Горбачова', + 'Островского Николая', + 'Павла Дибенко', + 'Павлика Морозова', + 'Патриса Лумумбы', + 'Перспективная', + 'Петра Дегтяренко', + 'Петра Шелеста', + 'Петровского', + 'Пика Вильгельма', + 'Полупанова', + 'Примакова', + 'Профинтерна', + 'Руднева Николая', + 'Сагайдика Степана', + 'Сарафимовича', + 'Сергея Струтинского', + 'Смирнова-Ласточкина', + 'Советская', + 'Софьи Перовской', + 'Строкача Тимофея', + 'Суворова', + 'Терешковой Валентины', + 'Трутенко Онуфрия', + 'Фадеева', + 'Федько Ивана', + 'Фрунзе', + 'Фурманова', + 'Цурюпинская', + 'Чапаева', + 'Чекистов', + 'Чеслава Белинского', + 'Чудновского', + 'Шаумяна', + 'Щербакова', + 'Щорса', + 'Юрия Коцюбинского', + 'Якира', + ] + + def city_prefix(self): + return self.random_element(self.city_prefixes) + + def postcode(self): + """The code consists of five digits (01000-99999)""" + return '{}{}'.format( + self.generator.random.randint( + 0, 10), self.generator.random.randint( + 1000, 10000)) + + def street_prefix(self): + return self.random_element(self.street_prefixes) + + def street_title(self): + return self.random_element(self.street_titles) diff --git a/testbed/joke2k__faker/faker/providers/address/zh_CN/__init__.py b/testbed/joke2k__faker/faker/providers/address/zh_CN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e29017eea7132448dc94af94b97656b69789d608 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/zh_CN/__init__.py @@ -0,0 +1,87 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_suffixes = ("市", "县") + city_formats = ("{{city_name}}{{city_suffix}}", + "{{first_name}}{{city_suffix}}") + + district_formats = ("{{district}}区",) + + building_number_formats = ("?座",) + postcode_formats = ("%#####",) + + street_suffixes = ("街", "路") + street_name_formats = ("{{city_name}}{{street_suffix}}", + "{{last_name}}{{street_suffix}}") + street_address_formats = ("{{street_name}}{{building_number}}",) + + address_formats = ( + "{{province}}{{city}}{{district}}{{street_address}} {{postcode}}",) + + provinces = ( + "北京市", "上海市", "天津市", "重庆市", + "内蒙古自治区", "山西省", "河北省", "吉林省", "江苏省", "辽宁省", "黑龙江省", + "安徽省", "山东省", "浙江省", "江西省", "福建省", "湖南省", "湖北省", + "河南省", "广东省", "广西壮族自治区", "贵州省", "海南省", "四川省", "云南省", + "陕西省", "甘肃省", "宁夏回族自治区", "青海省", "新疆维吾尔自治区", "西藏自治区", + "台湾省", "香港特别行政区", "澳门特别行政区", + ) + districts = ( + "西夏", "永川", "秀英", "高港", "清城", "兴山", "锡山", "清河", + "龙潭", "华龙", "海陵", "滨城", "东丽", "高坪", "沙湾", "平山", + "城北", "海港", "沙市", "双滦", "长寿", "山亭", "南湖", "浔阳", + "南长", "友好", "安次", "翔安", "沈河", "魏都", "西峰", "萧山", + "金平", "沈北新", "孝南", "上街", "城东", "牧野", "大东", + "白云", "花溪", "吉区", "新城", "怀柔", "六枝特", "涪城", + "清浦", "南溪", "淄川", "高明", "东城", "崇文", "朝阳", "大兴", + "房山", "门头沟", "黄浦", "徐汇", "静安", "普陀", "闵行", "和平", + "蓟州", "永川", "长寿", "璧山", "合川", "梁平", "丰都", "江北", + ) + cities = ( + "北京", "上海", "天津", "重庆", "哈尔滨", "长春", "沈阳", "呼和浩特", + "石家庄", "乌鲁木齐", "兰州", "西宁", "西安", "银川", "郑州", "济南", "太原", + "合肥", "武汉", "长沙", "南京", "成都", "贵阳", "昆明", "南宁", "拉萨", + "杭州", "南昌", "广州", "福州", "台北", "海口", "香港", "澳门", "通辽", + "兴安盟", "太原", "辛集", "邯郸", "沈阳", "辽阳", "兴城", "北镇", "阜新", + "哈尔滨", "齐齐哈尔", "淮安", "张家港", "海门", "六安", "巢湖", "马鞍山", + "永安", "宁德", "嘉禾", "荆门", "潜江", "大冶", "宜都", "佛山", "深圳", + "潮州", "惠州", "汕尾", "东莞", "梧州", "柳州", "合山", "六盘水", "关岭") + countries = ( + "阿富汗", "阿拉斯加", "阿尔巴尼亚", "阿尔及利亚", "安道尔", "安哥拉", "安圭拉岛英", "安提瓜和巴布达", + "阿根廷", "亚美尼亚", "阿鲁巴岛", "阿森松", "澳大利亚", "奥地利", "阿塞拜疆", "巴林", "孟加拉国", + "巴巴多斯", "白俄罗斯", "比利时", "伯利兹", "贝宁", "百慕大群岛", "不丹", "玻利维亚", "波斯尼亚和黑塞哥维那", + "博茨瓦纳", "巴西", "保加利亚", "布基纳法索", "布隆迪", "喀麦隆", "加拿大", "加那利群岛", "佛得角", + "开曼群岛", "中非", "乍得", "智利", "圣诞岛", "科科斯岛", "哥伦比亚", "巴哈马国", "多米尼克国", "科摩罗", + "刚果", "科克群岛", "哥斯达黎加", "克罗地亚", "古巴", "塞浦路斯", "捷克", "丹麦", "迪戈加西亚岛", "吉布提", + "多米尼加共和国", "厄瓜多尔", "埃及", "萨尔瓦多", "赤道几内亚", "厄立特里亚", "爱沙尼亚", "埃塞俄比亚", "福克兰群岛", + "法罗群岛", "斐济", "芬兰", "法国", "法属圭亚那", "法属波里尼西亚", "加蓬", "冈比亚", "格鲁吉亚", "德国", "加纳", + "直布罗陀", "希腊", "格陵兰岛", "格林纳达", "瓜德罗普岛", "关岛", "危地马拉", "几内亚", "几内亚比绍", "圭亚那", + "海地", "夏威夷", "洪都拉斯", "匈牙利", "冰岛", "印度", "印度尼西亚", "伊郎", "伊拉克", "爱尔兰", "以色列", + "意大利", "科特迪瓦", "牙买加", "日本", "约旦", "柬埔塞", "哈萨克斯坦", "肯尼亚", "基里巴斯", "朝鲜", "韩国", + "科威特", "吉尔吉斯斯坦", "老挝", "拉脱维亚", "黎巴嫩", "莱索托", "利比里亚", "利比亚", "列支敦士登", "立陶宛", + "卢森堡", "马其顿", "马达加斯加", "马拉维", "马来西亚", "马尔代夫", "马里", "马耳他", "马里亚纳群岛", "马绍尔群岛", + "马提尼克", "毛里塔尼亚", "毛里求斯", "马约特岛", "墨西哥", "密克罗尼西亚", "中途岛", "摩尔多瓦", "摩纳哥", "蒙古", + "蒙特塞拉特岛", "摩洛哥", "莫桑比克", "缅甸", "纳米比亚", "瑙鲁", "尼泊尔", "荷兰", "荷属安的列斯群岛", "新喀里多尼亚群岛", + "新西兰", "尼加拉瓜", "尼日尔", "尼日利亚", "纽埃岛", "诺福克岛", "挪威", "阿曼", "帕劳", "巴拿马", "巴布亚新几内亚", + "巴拉圭", "秘鲁", "菲律宾", "波兰", "葡萄牙", "巴基斯坦", "波多黎各", "卡塔尔", "留尼汪岛", "罗马尼亚", "俄罗斯", + "卢旺达", "东萨摩亚", "西萨摩亚", "圣马力诺", "圣皮埃尔岛及密克隆岛", "圣多美和普林西比", "沙特阿拉伯", "塞内加尔", + "塞舌尔", "新加坡", "斯洛伐克", "斯洛文尼亚", "所罗门群岛", "索马里", "南非", "西班牙", "斯里兰卡", "圣克里斯托弗和尼维斯", + "圣赫勒拿", "圣卢西亚", "圣文森特岛", "苏丹", "苏里南", "斯威士兰", "瑞典", "瑞士", "叙利亚", "塔吉克斯坦", "坦桑尼亚", + "泰国", "阿拉伯联合酋长国", "多哥", "托克劳群岛", "汤加", "特立尼达和多巴哥", "突尼斯", "土耳其", "土库曼斯坦", + "特克斯和凯科斯群岛", "图瓦卢", "美国", "乌干达", "乌克兰", "英国", "乌拉圭", "乌兹别克斯坦", "瓦努阿图", + "梵蒂冈", "委内瑞拉", "越南", "维尔京群岛", "维尔京群岛和圣罗克伊", "威克岛", "瓦里斯和富士那群岛", "西撒哈拉", + "也门", "南斯拉夫", "扎伊尔", "赞比亚", "桑给巴尔", "津巴布韦", "中华人民共和国", "中国", + ) + + def building_number(self): + return self.lexify(self.random_element(self.building_number_formats)) + + def city_name(self): + return self.random_element(self.cities) + + def province(self): + return self.random_element(self.provinces) + + def district(self): + return self.random_element(self.districts) diff --git a/testbed/joke2k__faker/faker/providers/address/zh_TW/__init__.py b/testbed/joke2k__faker/faker/providers/address/zh_TW/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7202e2a8e5a890fba0f2ec9acd9934390d3984a3 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/address/zh_TW/__init__.py @@ -0,0 +1,111 @@ +from .. import Provider as AddressProvider + + +class Provider(AddressProvider): + city_formats = ("{{city_name}}", "{{city_name}}{{city_name_suffix}}") + building_number_formats = ("%號", "%#號", "%##號") + postcode_formats = ("%####", "%##") + section_formats = ("", "", "", "", "%段") + street_address_formats = ( + "{{street_name}}{{street_name_suffix}}{{section_number}}{{building_number}}", ) + address_formats = ( + "{{postcode}} {{city}}{{street_address}}{{secondary_address}}", ) + secondary_address_formats = ('#樓', '之#') + + street_names = ("中正", "中山", "民生", "中華", "和平", + "中興", "仁愛", "復興", "民族", "民權", + "忠孝", "信義", "成功", "新興", "新生", + "動物園", "淡水", "新生", "文化", "大同", + "三民", "新生", "光復", "自強", "光明", + "公園", "文山", "松山", "新店", "建國", + "西門", "古亭", "迴龍", "中山", "新莊", + "蘆洲", "永安", "四維", "大橋頭", "府中", + "福德", "大同", "文昌", "土城", "博愛", + "象山", "光華", "太平", "水源", "莒光", + "廣慈", "大仁", "中央", "大智", "林森", + "長春", "南", "劍南", "大坪", "國凱" + "八德", "天母", "東興", "勝利", "頂福州", + "東湖", "大勇", "民有", "自由", "長安", + "明德", "大安", "龍山寺", "德", "忠義", + "中和", "自由", "新埔", "永和", "延平", + "正義", "五福", "華興", "育英", "平和", + "福安", "小碧潭", "永寧", "育英", "興", + "自立", "民享", "昆陽", "民治", "關渡", + "學府", "奇岩", "紅樹林", "和街", "民富", + "關渡", "北投", "石牌", "芝山", "景美", + "士林", "劍潭", "雙連", "新北投", "萬隆") + + street_suffixes = ("路", "街", "巷") + + cities = ("基隆", "台北", "新北", "桃園", "新竹", + "新竹", "苗栗", "台中", "彰化", "南投", + "雲林", "嘉義", "桃園", "台南", "高雄", + "屏東", "台東", "花蓮", "宜蘭", "澎湖", + "金門", "連江", "太保", "朴子", "馬公", + "頭份", "臺東", "斗六", "員林", "竹北", + "平鎮", "臺中", "八德", "板橋", "大里", + "鳳山", "豐原", "蘆洲", "蘆竹", "三重", + "樹林", "太平", "新營", "新營", "汐止", + "楊梅", "永和", "永康", "中和", "中壢", + "阿里山", "白沙", "褒忠", "北斗", "北竿", + "北港", "卑南", "草屯", "梅山", "牡丹", + "橫山", "光復", "關山", "古坑", "竹田") + + city_suffixes = ("市", "縣") + + # from + countries = ("阿爾巴尼亞", "剛果共和國", "阿爾及利亞", "丹麥", + "安哥拉", "多明尼加", "安圭拉", "多米尼克", + "阿根廷", "厄瓜多爾", "亞美尼亞", "埃及", + "阿路巴", "薩爾瓦多", "澳大利亞", "厄利垂亞", + "奧地利", "愛沙尼亞", "亞塞拜然", "衣索匹亞", + "巴哈馬", "斐濟", "巴林", "芬蘭", "孟加拉", "法屬玻里尼西亞", + "法國", "巴貝多", "加彭", "白俄羅斯", "喬治亞", + "比利時", "德國", "貝里斯", "迦納", "貝南", "直布羅陀", + "百慕達", "英國", "不丹", "希臘", "玻利維亞", "格瑞那達", + "波希尼亞及赫塞哥維那", "瓜地馬拉", "波札那", "幾內亞", + "巴西", "蓋亞那", "汶萊", "海地", "保加利亞", "宏都拉斯", + "布吉納法索", "香港", "蒲隆地", "匈牙利", "柬埔寨", "冰島", + "喀麥隆", "印度", "加拿大", "印尼", "維德角島", "依朗", + "開曼群島", "伊拉克", "中非共和國", "愛爾蘭", "查德", "以色列", + "智利", "義大利", "中國大陸", "牙買加", "哥倫比亞", "日本", + "剛果", "約旦", "科克群島", "肯亞", "哥斯大黎加", "韓國", + "象牙海岸", "科威特", "克羅埃西亞", "寮國", "塞浦路斯", "拉脫維亞", + "捷克", "賴索托", "盧森堡", "聖露西亞", "澳門", "聖文森及格瑞那丁", + "馬其頓", "聖多美及普林西比", "馬達加斯加", "沙烏地阿拉伯", + "馬拉威", "塞內加爾", "馬來西亞", "塞席爾", "馬爾地夫", "獅子山", + "馬利", "新加坡", "馬爾他", "斯洛伐克", "模里西斯", "斯洛維尼亞", + "茅利塔尼亞", "索羅門群島", "墨西哥", "索馬利亞", + "摩爾多瓦", "南非", "蒙古", "西班牙", "摩洛哥", "斯里蘭卡", + "緬甸", "蘇丹", "納米比亞", "蘇利南", "諾魯", "史瓦濟蘭", + "尼泊爾", "瑞典", "荷蘭", "瑞士", "新喀里多尼亞", "敘利亞", + "紐西蘭", "坦尚尼亞", "尼日", "泰國", "奈及利亞", "多哥", + "挪威", "千里達及托貝哥", "阿曼", "突尼西亞", "巴基斯坦", "土耳其", + "巴拿馬", "烏干達", "巴布亞紐幾內亞", "烏克蘭", + "巴拉圭", "阿拉伯聯合大公國", "秘魯", "美國", "菲律賓", "烏拉圭", + "波蘭", "委內瑞拉", "葡萄牙", "越南", "卡達", "西薩摩亞", + "羅馬尼亞", "葉門", "俄羅斯", "尚比亞", "盧安達", "辛巴威", + "聖克里斯多福及尼維斯") + + def secondary_address(self): + return self.numerify( + self.random_element( + self.secondary_address_formats)) + + def building_number(self): + return self.numerify(self.random_element(self.building_number_formats)) + + def street_name(self): + return self.random_element(self.street_names) + + def street_name_suffix(self): + return self.random_element(self.street_suffixes) + + def city_name(self): + return self.random_element(self.cities) + + def city_name_suffix(self): + return self.random_element(self.city_suffixes) + + def section_number(self): + return self.numerify(self.random_element(self.section_formats)) diff --git a/testbed/joke2k__faker/faker/providers/automotive/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c65dd2015760ef8e8142f5a81e9649aa6661767 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/__init__.py @@ -0,0 +1,17 @@ +import re + +from string import ascii_uppercase + +from .. import BaseProvider + +localized = True + + +class Provider(BaseProvider): + license_formats = () + + def license_plate(self): + temp = re.sub(r'\?', + lambda x: self.random_element(ascii_uppercase), + self.random_element(self.license_formats)) + return self.numerify(temp) diff --git a/testbed/joke2k__faker/faker/providers/automotive/ar_JO/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/ar_JO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..063e67c5f8dd13ad02d4852544159edb3cbf7978 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/ar_JO/__init__.py @@ -0,0 +1,40 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # Source: + # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Jordan + license_formats = ( + '{{initials}}-####', + '{{initials}}-#####', + ) + + def initials(self): + return self.random_element([ + '1', # Ministers + '2', '3', # Parliament + '5', # General Government + + '6', # Aqaba free zone + '7', '8', # Diplomatic + '9', # Temporary + '10', '23', # Passenger cars + '38', '39', # Crew cabs + '41', '42', # Light goods vehicles + '44', # Tractors + '46', # Motorcycles and scooters + '50', # Taxi + '56', # Small buses + '58', # Coaches + '60', # HGVs + '70', # Rental Cars + '71', # Trailer + '90', # Army + '95', # Ambulance + '96', # Gendarmerie + '99', # Police + ]) + + def license_plate(self): + pattern = self.random_element(self.license_formats) + return self.numerify(self.generator.parse(pattern)) diff --git a/testbed/joke2k__faker/faker/providers/automotive/ar_PS/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/ar_PS/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c6207eaef1d0bfd4590b5c61a8ceb8555aa548f --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/ar_PS/__init__.py @@ -0,0 +1,60 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # Source: + # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Palestinian_National_Authority + license_formats = ( + # Private vehicles + '{{district}}-####-3#', + '{{district}}-####-4#', + '{{district}}-####-7#', + '{{district}}-####-9#', + # Public transport + '{{district}}-####-30', + # Authority vehicles + '####', + # New police vehicles + '####-99', + + # Gaza strip after 2012 + + # Private + '1-####-0#', + '3-####-0#', + # Commercial + '1-####-1#', + '3-####-1#', + # Public + '1-####-2#', + '3-####-2#', + # Municipal + '1-####-4#', + '3-####-4#', + # Governmental, and Governmental personal vehicles + '1-####-5#', + '3-####-5#', + ) + + def district(self): + return self.random_element([ + # Gaza Strip + '1', + '3', + + # Northern West Bank (Nablus, Tulkarm, Qalqilya, Jenin) + '4', + '7', + + # Central West Bank (Ramallah, Jerusalem, Jericho) + '5', + '6', + + # Southern West Bank (Bethlehem, Hebron) + '8', + '9', + ]) + + def license_plate(self): + pattern = self.random_element(self.license_formats) + return self.numerify(self.generator.parse(pattern)) diff --git a/testbed/joke2k__faker/faker/providers/automotive/ar_SA/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/ar_SA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6cfb1873cc9139454b4183fd2e332628ce48374 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/ar_SA/__init__.py @@ -0,0 +1,76 @@ +import re + +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # Source: + # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Saudi_Arabia + LICENSE_FORMAT_EN = '#### ???' + LICENSE_FORMAT_AR = '? ? ? ####' + + PLATE_CHARS_EN = 'ABDEGHJKLNRSTUVXZ' + PLATE_CHARS_AR = 'أبدعقهحكلنرسطوىصم' + + PLATE_MAP = { + 'A': 'ا', + 'B': 'ب', + 'D': 'د', + 'E': 'ع', + 'G': 'ق', + 'H': 'ه', + 'J': 'ح', + 'K': 'ك', + 'L': 'ل', + 'N': 'ن', + 'R': 'ر', + 'S': 'س', + 'T': 'ط', + 'U': 'و', + 'V': 'ى', + 'X': 'ص', + 'Z': 'م', + + '0': '٠', + '1': '١', + '2': '٢', + '3': '٣', + '4': '٤', + '5': '٥', + '6': '٦', + '7': '٧', + '8': '٨', + '9': '٩', + } + + def license_plate_en(self): + return self.bothify( + self.LICENSE_FORMAT_EN, letters=self.PLATE_CHARS_EN, + ) + + def license_plate_ar(self): + english_plate = self.license_plate_en() + return self._translate_license_plate(english_plate) + + def _translate_license_plate(self, license_plate): + nums = list(reversed(license_plate[0:4])) + chars = list(license_plate[5:8]) + + numerated = re.sub( + r'\#', + lambda x: self.PLATE_MAP[nums.pop()], + self.LICENSE_FORMAT_AR, + ) + ar_plate = re.sub( + r'\?', + lambda x: self.PLATE_MAP[chars.pop()], + numerated, + ) + + return ar_plate + + def license_plate(self): + en_palate = self.license_plate_en() + ar_palate = self._translate_license_plate(en_palate) + + return en_palate, ar_palate diff --git a/testbed/joke2k__faker/faker/providers/automotive/de_DE/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/de_DE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c26ef26b5a322eea06359d2bf44ca192ac5c2681 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/de_DE/__init__.py @@ -0,0 +1,43 @@ +import string + +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + + # http://berlin.de/daten/liste-der-kfz-kennzeichen/kfz-kennz-d.csv + license_plate_prefix = ( + 'A', 'AA', 'AB', 'ABI', 'ABG', 'AC', 'AE', 'AIC', 'AK', 'AM', 'AN', 'AÖ', 'AP', 'AS', 'AUR', 'AW', 'AZ', 'B', + 'BA', 'BAD', 'BAR', 'BB', 'BC', 'BD', 'BGL', 'BI', 'BIR', 'BIT', 'BK', 'BL', 'BLK', 'BM', 'BN', 'BO', 'BOR', + 'BOT', 'BP', 'BRA', 'BRB', 'BS', 'BT', 'BTF', 'BÜS', 'BW', 'BWL', 'BYL', 'BZ', 'C', 'CB', 'CE', 'CHA', 'CO', + 'COC', 'COE', 'CUX', 'CW', 'D', 'DA', 'DAH', 'DAN', 'DAU', 'DBR', 'DD', 'DE', 'DEG', 'DEL', 'DGF', 'DH', 'DL', + 'DLG', 'DN', 'Do', 'DON', 'DU', 'DÜW', 'E', 'EA', 'EB', 'EBE', 'ED', 'EE', 'EF', 'EI', 'EIC', 'EL', 'EM', 'EMD', + 'EMS', 'EN', 'ER', 'ERB', 'ERH', 'ERZ', 'ES', 'ESW', 'EU', 'F', 'FB', 'FD', 'FDS', 'FF', 'FFB', 'FG', 'FL', + 'FN', 'FO', 'FR', 'FRG', 'FRI', 'FS', 'FT', 'FÜ', 'G', 'GAP', 'GE', 'GER', 'GF', 'GG', 'GI', 'GL', 'GM', 'GÖ', + 'GP', 'GR', 'GRZ', 'GS', 'GT', 'GTH', 'GÜ', 'GZ', 'H', 'HA', 'HAL', 'HAM', 'HAS', 'HB', 'HBN', 'HD', 'HDH', + 'HE', 'HEF', 'HEI', 'HEL', 'HER', 'HF', 'HG', 'HGW', 'HH', 'HI', 'HL', 'HM', 'HN', 'HO', 'HOL', 'HOM', 'HP', + 'HR', 'HRO', 'HS', 'HSK', 'HST', 'HU', 'HVL', 'HWI', 'HX', 'HZ', 'IGB', 'IK', 'IN', 'IZ', 'J', 'JL', 'K', 'KA', + 'KB', 'KC', 'KE', 'KEH', 'KF', 'KG', 'KH', 'KI', 'KIB', 'KL', 'KLE', 'KN', 'KO', 'KR', 'KS', 'KT', 'KU', 'KÜN', + 'KUS', 'KYF', 'L', 'LA', 'LAU', 'LB', 'LD', 'LDK', 'LDS', 'LER', 'LEV', 'LG', 'LI', 'LIF', 'LIP', 'LL', 'LM', + 'LÖ', 'LOS', 'LRO', 'LSA', 'LSN', 'LU', 'LWL', 'M', 'MA', 'MB', 'MD', 'ME', 'MEI', 'MG', 'MI', 'MIL', 'MK', + 'MKK', 'MM', 'MN', 'MOL', 'MOS', 'MR', 'MS', 'MSH', 'MSP', 'MST', 'MTK', 'MÜ', 'MÜR', 'MVL', 'MYK', 'MZ', 'MZG', + 'N', 'NB', 'ND', 'NDH', 'NE', 'NEA', 'NES', 'NEW', 'NF', 'NI', 'NK', 'NL', 'NM', 'NMS', 'NOH', 'NOM', 'NR', + 'NU', 'NVP', 'NW', 'NWM', 'OA', 'OAL', 'OB', 'OD', 'OE', 'OF', 'OG', 'OH', 'OHA', 'OHV', 'OHZ', 'OL', 'OPR', + 'OS', 'OSL', 'OVP', 'P', 'PA', 'PAF', 'PAN', 'PB', 'PCH', 'PE', 'PF', 'PI', 'PIR', 'PLÖ', 'PM', 'PR', 'PS', 'R', + 'RA', 'RD', 'RE', 'REG', 'RO', 'ROS', 'ROW', 'RP', 'RPL', 'RS', 'RT', 'RÜD', 'RÜG', 'RV', 'RW', 'RZ', 'S', + 'SAD', 'SAL', 'SAW', 'SB', 'SC', 'SDL', 'SE', 'SG', 'SH', 'SHA', 'SHG', 'SHK', 'SHL', 'SI', 'SIG', 'SIM', 'SK', + 'SL', 'SLF', 'SLK', 'SLS', 'SM', 'SN', 'SO', 'SOK', 'SÖM', 'SON', 'SP', 'SPN', 'SR', 'ST', 'STA', 'STD', 'SU', + 'SÜW', 'SW', 'SZ', 'TDO', 'TBB', 'TF', 'TG', 'THL', 'THW', 'TIR', 'TÖL', 'TR', 'TS', 'TÜ', 'TUT', 'UE', 'UL', + 'UM', 'UN', 'V', 'VB', 'VEC', 'VER', 'VIE', 'VK', 'VR', 'VS', 'W', 'WAF', 'WAK', 'WB', 'WE', 'WEN', 'WES', 'WF', + 'WHV', 'WI', 'WIL', 'WL', 'WM', 'WN', 'WND', 'WO', 'WOB', 'WST', 'WT', 'WTM', 'WÜ', 'WUG', 'WUN', 'WW', 'WZ', + 'Y', 'Z', 'ZW', + ) + + license_plate_suffix = ( + '-??-%@@@', + '-?-%@@@', + ) + + def license_plate(self): + return self.random_element(self.license_plate_prefix) + \ + self.lexify(self.numerify(self.random_element(self.license_plate_suffix)), string.ascii_uppercase) diff --git a/testbed/joke2k__faker/faker/providers/automotive/en_CA/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/en_CA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed50cefa6da97aebb77a1d1f05ca409e3ef33493 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/en_CA/__init__.py @@ -0,0 +1,40 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # from + # https://www.revolvy.com/main/index.php?s=Canadian%20licence%20plate%20designs%20and%20serial%20formats + license_formats = ( + # Alberta + '???-####', + # BC + '??# ##?', + '?? ####', + # Manitoba + '??? ###', + # New Brunswick + '??? ###', + # Newfoundland and Labrador + '??? ###', + # NWT + '######', + # Nova Scotia + '??? ###', + # Nunavut + '### ###', + # Ontario + '### ???', + '???? ###', + '??# ###', + '### #??', + '?? ####', + 'GV??-###', + # PEI + '## ##??', + # Quebec + '?## ???', + # Saskatchewan + '### ???', + # Yukon + '???##', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/en_GB/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/en_GB/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b910f4c06622197ecf4691a8333708c83163d62d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/en_GB/__init__.py @@ -0,0 +1,10 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # from + # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom + license_formats = ( + '??## ???', + '??##???', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/en_NZ/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/en_NZ/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65da755df4c1b3c3e6f0330fab2b0b8e61ae9e25 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/en_NZ/__init__.py @@ -0,0 +1,26 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # See https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_New_Zealand + license_formats = ( + # Old plates + '??%##', + '??%###', + '??%###', + # Three letters since 2002 + 'A??%##', + 'B??%##', + 'C??%##', + 'D??%##', + 'E??%##', + 'F??%##', + 'G??%##', + 'H??%##', + 'J??%##', + 'K??%##', + 'L??%##', + 'M??%##', + # After 2018 + 'N??%##', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/en_PH/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/en_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..29dad62fc1953b498a2f77c8883655c9e7a9d246 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/en_PH/__init__.py @@ -0,0 +1,48 @@ +from string import ascii_uppercase + +from ... import BaseProvider + + +class Provider(BaseProvider): + """ + Provider for Philippine automotive license plates + + Vehicle registration in the Philippines has many controversies and is full of quirks. On top of that, some terms are + highly subject to interpretation or to varying definitions when applied colloquially, e.g. "motor" usually refers to + either a machine's motor or a motorcycle, "vehicles" usually means cars, SUVs, vans, and trucks but not motorcycles. + All of these, interestingly, affect how and what kind of license plates are issued. For the purposes of this + provider, the following pointers apply: + - High ranking government officials are entitled to use low numbered protocol license plates. + - Motorcycles and any improvised vehicle with a motorcycle as its base are issued motorcycle license plates. + - Cars, SUVs, vans, trucks, and other 4-wheeled civilian vehicles are considered automobiles. + - Invoking `license_plate()` will never generate protocol plates, because those are plates for specific use cases. + + Sources: + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Philippines + """ + + protocol_licenses = tuple(str(x) for x in range(1, 18) if x != 15) + motorcycle_license_formats = ( + '??####', # 1981 series + '??#####', # 2014 series + ) + automobile_license_formats = ( + '???###', # 1981 series + '???####', # 2014 series + ) + license_formats = motorcycle_license_formats + automobile_license_formats + + def _license_plate(self, license_format): + return self.bothify(self.random_element(license_format), ascii_uppercase) + + def protocol_license_plate(self): + return self.random_element(self.protocol_licenses) + + def motorcycle_license_plate(self): + return self._license_plate(self.motorcycle_license_formats) + + def automobile_license_plate(self): + return self._license_plate(self.automobile_license_formats) + + def license_plate(self): + return self._license_plate(self.license_formats) diff --git a/testbed/joke2k__faker/faker/providers/automotive/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87dd10006104b334545c7ac378ee834df14351b3 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/en_US/__init__.py @@ -0,0 +1,163 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # from + # https://en.wikipedia.org/wiki/United_States_license_plate_designs_and_serial_formats#Current_standard-issue_passenger_plate_designs_and_serial_formats + license_formats = ( + # Alabama + '#??####', + '##??###', + # Alaska + '### ???', + # American Samoa + '####', + # Arizona + '???####', + # Arkansas + '### ???', + '###???', + # California + '#???###', + # Colarado + '###-???', + '???-###', + # Conneticut + '###-???', + # Delaware + '######', + # DC + '??-####', + # Florda + '??? ?##', + '### ???', + '?## #??', + '### #??', + # Georgia + '???####', + # Guam + '?? ####', + # Hawaii + '??? ###', + 'H?? ###', + 'Z?? ###', + 'K?? ###', + 'L?? ###', + 'M?? ###', + # Idaho + '? ######', + '#? #####', + '#? ?####', + '#? ??###', + '#? #?#???', + '#? ####?', + '##? ####', + # Illinois + '?? #####', + '??# ####', + # Indiana + '###?', + '###??', + '###???', + # Iowa + '??? ###', + # Kansas + '### ???', + # Kentucky + '### ???', + # Louisiana + '### ???', + # Maine + '#### ??', + # Maryland + '#??####', + # Massachusetts + '#??? ##', + '#?? ###', + '### ??#', + '##? ?##', + # Michigan + '### ???', + '#?? ?##', + # Minnesota + '###-???', + # Mississippi + '??? ###', + # Missouri + '??# ?#?', + # Montana + '#-#####?', + '##-####?', + # Nebraska + '??? ###', + '#-?####', + '##-?###', + '##-??##', + # Nevada + '##?•###', + # New Hampshire + '### ####', + # New Jersey + '?##-???', + # New Mexico + '###-???', + '???-###', + # New York + '???-####', + # North Carolina + '###-????', + # North Dakota + '### ???', + # Nothern Mariana Islands + '??? ###', + # Ohio + '??? ####', + # Oklahoma + '???-###', + # Oregon + '### ???', + # Pennsylvania + '???-####', + # Peurto Rico + '???-###', + # Rhode Island + '###-###', + # South Carolina + '### #??', + # South Dakota + '#?? ###', + '#?? ?##', + '##? ###', + '##? ?##', + '##? ??#', + # Tennessee + '?##-##?', + # Texas + '???-####', + # Utah + '?## #??', + '?## #??', + # Vermont + '??? ###', + '##??#', + '#??##', + '###?#', + '#?###', + # US Virgin Islands + '??? ###', + # Virginia + '???-####', + # Washington + '???####', + '###-???', + # West Virginia + '#?? ###', + '??? ###', + # Wisconsin + '???-####', + '###-???', + # Wyoming + '#-#####', + '#-####?', + '##-#####', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/fil_PH/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/fil_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5ef024119405a222ff788775dc86393be6ea10 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/fil_PH/__init__.py @@ -0,0 +1,6 @@ +from ..en_PH import Provider as EnPhAutomotiveProvider + + +class Provider(EnPhAutomotiveProvider): + """No difference from Automotive Provider for en_PH locale""" + pass diff --git a/testbed/joke2k__faker/faker/providers/automotive/hu_HU/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/hu_HU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9297796b2fbac8fce0603ace0acd7580300ef7f --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/hu_HU/__init__.py @@ -0,0 +1,8 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # from https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Hungary + license_formats = ( + '???-###', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/id_ID/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/id_ID/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..61c5802710efa1abfe09fd93418f8afaccce8ba4 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/id_ID/__init__.py @@ -0,0 +1,15 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # Currently this is my own work + license_formats = ( + '? ### ??', + '? ### ???', + '?? ### ??', + '?? ### ???', + '? #### ??', + '? #### ???', + '?? #### ??', + '?? #### ???', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/pl_PL/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/pl_PL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..98147f6a1500826946b339fa6ae69d0787f49d7f --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/pl_PL/__init__.py @@ -0,0 +1,25 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # from + # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Poland + license_formats = ( + '?? #####', + '?? ####?', + '?? ###??', + '?? #?###', + '?? #??##', + '??? ?###', + '??? ##??', + '??? #?##', + '??? ##?#', + '??? #??#', + '??? ??##', + '??? #####', + '??? ####?', + '??? ###??', + ) + + def license_plate_regex_formats(self): + return [plate.replace('?', '[A-Z]').replace('#', '[0-9]') for plate in self.license_formats] diff --git a/testbed/joke2k__faker/faker/providers/automotive/pt_BR/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/pt_BR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9844747d85209ef862a44a4b9769c70f5ca3b3e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/pt_BR/__init__.py @@ -0,0 +1,8 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + + license_formats = ( + '???-####', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/pt_PT/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/pt_PT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..858e9012bcfc51a8ea5c663e9bf9b29a31e0aa3f --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/pt_PT/__init__.py @@ -0,0 +1,11 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + + # From: https://pt.wikipedia.org/wiki/Matr%C3%ADculas_de_autom%C3%B3veis_em_Portugal + license_formats = ( + '##-##-??', + '##-??-##', + '??-##-##', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9bfdd7f0443d28ab17b65d3158a77203e15bc942 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/ru_RU/__init__.py @@ -0,0 +1,246 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + + # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Russia + license_plate_letters = ('A', 'B', 'E', 'K', 'M', 'Н', 'О', 'Р', 'С', 'Т', 'У', 'Х') + # https://ru.wikipedia.org/wiki/Категории_транспортных_средств + vehicle_categories = ('M', 'A', 'A1', 'B', 'B1', 'BE', 'C', 'C1', 'C1E', 'CE', 'D', 'D1', 'DE', 'Tm', 'Tb') + + license_plate_suffix = ( + # Republic of Adygea + '01', + # Republic of Bashkortostan + '02', '102', + # Republic of Buryatia + '03', + # Altai Republic + '04', + # Republic of Dagestan + '05', + # Republic of Ingushetia + '06', + # Kabardino-Balkar Republic + '07', + # Republic of Kalmykia + '08', + # Karachay-Cherkess Republic + '09', + # Republic of Karelia + '10', + # Komi Republic + '11', + # Mari El Republic + '12', + # Republic of Mordovia + '13', '113', + # Sakha Republic + '14', + # Republic of North Ossetia–Alania + '15', + # Republic of Tatarstan + '16', '116', '716', + # Tuva Republic + '17', + # Udmurt Republic + '18', + # Republic of Khakassia + '19', + # Chechen Republic + '20', '95', + # Chuvash Republic + '21', '121', + # Altai Krai + '22', + # Krasnodar Krai + '23', '93', '123', + # Krasnoyarsk Krai + '24', '84', '88', '124', + # Primorsky Krai + '25', '125', + # Stavropol Krai + '26', '126', + # Khabarovsk Krai + '27', + # Amur Oblast + '28', + # Arkhangelsk Oblast + '29', + # Astrakhan Oblast + '30', + # Belgorod Oblast + '31', + # Bryansk Oblast + '32', + # Vladimir Oblast + '33', + # Volgograd Oblast + '34', '134', + # Vologda Oblast + '35', + # Voronezh Oblast + '36', '136', + # Ivanovo Oblast + '37', + # Irkutsk Oblast + '38', '85', '38', + # Kaliningrad Oblast + '39', '91', + # Kaluga Oblast + '40', + # Kamchatka Krai + '41', '82', + # Kemerovo Oblast + '42', '142', + # Kirov Oblast + '43', + # Kostroma Oblast + '44', + # Kurgan Oblast + '45', + # Kursk Oblast + '46', + # Leningrad Oblast + '47', + # Lipetsk Oblast + '48', + # Magadan Oblast + '49', + # Moscow Oblast + '50', '90', '150', '190', '750', + # Murmansk Oblast + '51', + # Nizhny Novgorod Oblast + '52', '152', + # Novgorod Oblast + '53', + # Novosibirsk Oblast + '54', '154', + # Omsk Oblast + '55', + # Orenburg Oblast + '56', + # Oryol Oblast + '57', + # Penza Oblast + '58', + # Perm Krai + '59', '81', '159', + # Pskov Oblast + '60', + # Rostov Oblast + '61', '161', + # Ryazan Oblast + '62', + # Samara Oblast + '63', '163', '763', + # Saratov Oblast + '64', '164', + # Sakhalin Oblast + '65', + # Sverdlovsk Oblast + '66', '96', '196', + # Smolensk Oblast + '67', + # Tambov Oblast + '68', + # Tver Oblast + '69', + # Tomsk Oblast + '70', + # Tula Oblast + '71', + # Tyumen Oblast + '72', + # Ulyanovsk Oblast + '73', '173', + # Chelyabinsk Oblast + '74', '174', + # Zabaykalsky Krai + '75', '80', + # Yaroslavl Oblast + '76', + # Moscow + '77', '97', '99', '177', '197', '199', '777', '799', + # St. Petersburg + '78', '98', '178', '198', + # Jewish Autonomous Oblast + '79', + # Agin-Buryat Okrug / "Former Buryat Autonomous District of Aginskoye" + '80', + # Komi-Permyak Okrug / "Former Komi-Permyak Autonomous District" + '81', + # Republic of Crimea / De jure part of Ukraine as Autonomous Republic. Annexed by Russia in 2014. + '82', + # Koryak Okrug / "Former Koryak Autonomous District" + '82', + # Nenets Autonomous Okrug (Nenetsia) + '83', + # Taymyr Autonomous Okrug / "Former Taymyr (Dolgan-Nenets) Autonomous District" + '84', + # Ust-Orda Buryat Okrug / "Former Buryat Autonomous District of Ust-Ordynskoy" + '85', + # Khanty-Mansi Autonomous Okrug + '86', '186', + # Chukotka Autonomous Okrug + '87', + # Evenk Autonomous Okrug / "Former Evenk Autonomous District" + '88', + # Yamalo-Nenets Autonomous Okrug + '89', + # Sevastopol / De jure part of Ukraine as City with special status. Annexed by Russia in 2014. + '92', + # Territories outside of the Russian Federation, + # served by the bodies of internal affairs of the Russian Federation, such as Baikonur + '94', + ) + + license_plate_formats = ( + # Private vehicle plate + '{{plate_letter}}{{plate_number}}{{plate_letter}}{{plate_letter}} {{plate_suffix}}', + # Public transport plate + '{{plate_letter}}{{plate_letter}}{{plate_number}} {{plate_suffix}}', + # Trailer plate + '{{plate_letter}}{{plate_letter}}{{plate_number_extra}} {{plate_suffix}}', + # Police forces vehicle plate + '{{plate_letter}}{{plate_number_extra}} {{plate_suffix}}', + # Military vehicle plate + '{{plate_number_extra}}{{plate_letter}}{{plate_letter}} {{plate_suffix}}', + # Diplomatic vehicles + '{{plate_number_special}} {{plate_suffix}}', + ) + + plate_number_formats = ( + '###', + ) + + plate_extra_formats = ( + '####', + ) + + plate_special_formats = ( + '00#CD#', '00#D###', '00#T###', + ) + + def license_plate(self): + pattern = self.random_element(self.license_plate_formats) + return self.generator.parse(pattern) + + def plate_letter(self): + return self.random_element(self.license_plate_letters) + + def plate_number(self): + return self.numerify(self.random_element(self.plate_number_formats)) + + def plate_number_extra(self): + return self.numerify(self.random_element(self.plate_extra_formats)) + + def plate_number_special(self): + return self.numerify(self.random_element(self.plate_special_formats)) + + def plate_suffix(self): + return self.random_element(self.license_plate_suffix) + + def vehicle_category(self): + return self.random_element(self.vehicle_categories) diff --git a/testbed/joke2k__faker/faker/providers/automotive/sv_SE/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/sv_SE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..99878220947c976d3afcdc141f649aa22e4d8995 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/sv_SE/__init__.py @@ -0,0 +1,12 @@ +from .. import Provider as AutomotiveProvider + + +class Provider(AutomotiveProvider): + # Source: https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Sweden + # New possible format: https://goo.gl/gSjsnV + license_formats = ( + # Classic format + '??? ###', + # New possible format + '??? ##?', + ) diff --git a/testbed/joke2k__faker/faker/providers/automotive/tl_PH/__init__.py b/testbed/joke2k__faker/faker/providers/automotive/tl_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5ef024119405a222ff788775dc86393be6ea10 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/automotive/tl_PH/__init__.py @@ -0,0 +1,6 @@ +from ..en_PH import Provider as EnPhAutomotiveProvider + + +class Provider(EnPhAutomotiveProvider): + """No difference from Automotive Provider for en_PH locale""" + pass diff --git a/testbed/joke2k__faker/faker/providers/bank/__init__.py b/testbed/joke2k__faker/faker/providers/bank/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c91567c12b232ab7fbeef51626e92f06e4e584 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/__init__.py @@ -0,0 +1,42 @@ +import re +import string + +from string import ascii_uppercase + +from .. import BaseProvider + +localized = True +default_locale = 'en_GB' + + +class Provider(BaseProvider): + """ + Provider for IBAN/BBAN: it generates valid (valid length, valid checksum) + IBAN/BBANs for the given country. But the ids of the banks are random and + not valid banks! Same for account numbers. + """ + + ALPHA = {c: str(ord(c) % 55) for c in string.ascii_uppercase} + + # see https://en.wikipedia.org/wiki/International_Bank_Account_Number + bban_format = '????#############' + country_code = 'GB' + + def bank_country(self): + return self.country_code + + def bban(self): + temp = re.sub(r'\?', + lambda x: self.random_element(ascii_uppercase), + self.bban_format) + return self.numerify(temp) + + def iban(self): + bban = self.bban() + + check = bban + self.country_code + '00' + check = int(''.join(self.ALPHA.get(c, c) for c in check)) + check = 98 - (check % 97) + check = str(check).zfill(2) + + return self.country_code + check + bban diff --git a/testbed/joke2k__faker/faker/providers/bank/de_AT/__init__.py b/testbed/joke2k__faker/faker/providers/bank/de_AT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d70af333d3cfb2a6758a2f2f15adec0f21e80f9d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/de_AT/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '################' + country_code = 'AT' diff --git a/testbed/joke2k__faker/faker/providers/bank/de_DE/__init__.py b/testbed/joke2k__faker/faker/providers/bank/de_DE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84c9474404801a0835d38dae46c60fae84b267f9 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/de_DE/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '##################' + country_code = 'DE' diff --git a/testbed/joke2k__faker/faker/providers/bank/en_GB/__init__.py b/testbed/joke2k__faker/faker/providers/bank/en_GB/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75daaf2ec059b9cc0092f311a4ebbc688f550c96 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/en_GB/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '????##############' + country_code = 'GB' diff --git a/testbed/joke2k__faker/faker/providers/bank/fi_FI/__init__.py b/testbed/joke2k__faker/faker/providers/bank/fi_FI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57a0f7fb5211a9ac8603a92f2ba527b05105d690 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/fi_FI/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '################' + country_code = 'FI' diff --git a/testbed/joke2k__faker/faker/providers/bank/fr_FR/__init__.py b/testbed/joke2k__faker/faker/providers/bank/fr_FR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0047f58dcd9eed17c44ef72bbc86a35f90e782cb --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/fr_FR/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '########################' + country_code = 'FR' diff --git a/testbed/joke2k__faker/faker/providers/bank/it_IT/__init__.py b/testbed/joke2k__faker/faker/providers/bank/it_IT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c15cec8fd51d090b4d782e2db9d3b60558ec59c3 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/it_IT/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '?######################' + country_code = 'IT' diff --git a/testbed/joke2k__faker/faker/providers/bank/nl_NL/__init__.py b/testbed/joke2k__faker/faker/providers/bank/nl_NL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a56995c7e1d3f48080a0676bc784f9e937619d7 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/nl_NL/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '????##########' + country_code = 'NL' diff --git a/testbed/joke2k__faker/faker/providers/bank/no_NO/__init__.py b/testbed/joke2k__faker/faker/providers/bank/no_NO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17b99843524afcd9bebb68558db7f439d19a075d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/no_NO/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '###########' + country_code = 'NO' diff --git a/testbed/joke2k__faker/faker/providers/bank/pl_PL/__init__.py b/testbed/joke2k__faker/faker/providers/bank/pl_PL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa318adae9bbbf3e3276398c14981aefca0005d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/pl_PL/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + bban_format = '#' * 26 + country_code = 'PL' diff --git a/testbed/joke2k__faker/faker/providers/bank/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/bank/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..affe1a9c04ee2d82f35f795fa79753d1fcc49f40 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/bank/ru_RU/__init__.py @@ -0,0 +1,156 @@ +from .. import Provider as BankProvider + + +class Provider(BankProvider): + country_code = 'RU' + + """ + See https://ru.wikipedia.org/wiki/Коды_субъектов_Российской_Федерации + """ + region_codes = ( + '01', '03', '04', '05', '07', '08', '10', '11', '12', '14', '15', '17', '18', '19', '20', '22', + '24', '25', '26', '27', '28', '29', '30', '32', '33', '34', '35', '36', '37', '38', '40', '41', + '42', '44', '45', '46', '47', '49', '50', '52', '53', '54', '56', '57', '58', '60', '61', '63', + '64', '65', '66', '67', '68', '69', '70', '71', '73', '75', '76', '77', '78', '79', '80', '81', + '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', + '98', '99', '111', '118', '7110', '718', '7114', '719', + ) + + department_code_formats = ( + '0#', '1#', '2#', '3#', ' 4#', '5#', '6#', '7#', '8#', '9#', + ) + + credit_organization_code_formats = ( + '05#', '06#', '07#', '08#', '09#', '1##', '2##', '3##', '4##', '5##', '6##', '7##', '8##', '9##', + ) + + checking_account_codes = [str(i) for i in range(102, 110)] + ['203', '204'] + [str(i) for i in range(301, 330)] + \ + [str(i) for i in range(401, 409)] + [str(i) for i in range(411, 426)] + ['430'] + \ + [str(i) for i in range(501, 527)] + + organization_codes = ( + '01', '02', '03', '04', + ) + + # See https://ru.wikipedia.org/wiki/Общероссийский_классификатор_валют + currency_codes = ( + '008', '012', '032', '036', '044', '048', '050', '051', '052', '060', '064', '068', '072', '084', '090', '096', + '104', '108', '116', '124', '132', '136', '144', '152', '156', '170', '174', '188', '191', '192', '203', '208', + '214', '222', '230', '232', '238', '242', '262', '270', '292', '320', '324', '328', '332', '340', '344', '348', + '352', '356', '360', '364', '368', '376', '388', '392', '398', '400', '404', '408', '410', '414', '417', '418', + '422', '426', '430', '434', '440', '446', '454', '458', '462', '478', '480', '484', '496', '498', '504', '512', + '516', '524', '532', '533', '548', '554', '558', '566', '578', '586', '590', '598', '600', '604', '608', '634', + '643', '646', '654', '678', '682', '690', '694', '702', '704', '706', '710', '728', '748', '752', '756', '760', + '764', '776', '780', '784', '788', '800', '807', '810', '818', '826', '834', '840', '858', '860', '882', '886', + '894', '901', '931', '932', '933', '934', '936', '937', '938', '940', '941', '943', '944', '946', '947', '948', + '949', '950', '951', '952', '953', '959', '960', '961', '962', '963', '964', '968', '969', '970', '971', '972', + '973', '975', '976', '977', '978', '980', '981', '985', '986', '997', '998', '999', + ) + + """ + The list of Russian banks is based on Central Bank of Russia statistics + See http://cbr.ru/credit/coreports/ko17012020.zip + """ + banks = ( + 'Абсолют Банк', 'Авангард', 'Аверс', 'Автоградбанк', 'Автокредитбанк', 'Автоторгбанк', 'Агора', + 'Агропромкредит', 'Агророс', 'Азиатско-Тихоокеанский Банк', 'Азия-Инвест Банк', 'Айсибиси Банк', + 'АК Барс', 'Акибанк', 'Акрополь', 'Актив Банк', 'Акцепт', 'Александровский', 'Алеф-Банк', 'Алмазэргиэнбанк', + 'Алтайкапиталбанк', 'Алтынбанк', 'Альба Альянс', 'Альтернатива', 'Альфа-Банк', 'Америкэн Экспресс Банк', + 'Апабанк', 'Аресбанк', 'Арзамас', 'Байкалинвестбанк', 'Байкалкредобанк', 'Балаково-Банк', 'Балтинвестбанк', + 'Банк "Санкт-Петербург"', 'Банк "СКС"', 'Банк 131', 'Банк Берейт', 'Банк Дом.рф', + 'Банк Жилищного Финансирования', 'Банк Зенит', 'Банк Зенит Сочи', 'Банк Интеза', 'Банк Казани', + 'Банк Корпоративного Финансирования', 'Банк Кредит Свисс (Москва)', 'Банк Оранжевый', 'Банк Оренбург', + 'Банк ПСА Финанс Рус', 'Банк Раунд', 'Банк Реалист', 'Банк РМП', 'Банк РСИ', 'Банк СГБ', + 'Банк Стандарт-Кредит', 'Банк Финам', 'Банк ЧБРР', 'ББР Банк', 'Белгородсоцбанк', 'Бест Эффортс Банк', + 'Бизнес-Сервис-Траст', 'БКС Банк', 'БМ-Банк', 'БМВ Банк', 'БНП Париба Банк', 'Братский АНКБ', 'Быстробанк', + 'Бэнк Оф Чайна', 'Вакобанк', 'Великие Луки Банк', 'Венец', 'Веста', 'Викинг', 'Витабанк', 'Вкабанк', + 'Владбизнесбанк', 'Внешфинбанк', 'Возрождение', 'Вологжанин', 'Восточный', 'ВРБ', + 'Всероссийский Банк Развития Регионов', 'ВТБ', 'Вуз-Банк', 'Вятич', 'Газнефтьбанк', 'Газпромбанк', + 'Газтрансбанк', 'Газэнергобанк', 'Гарант-Инвест', 'Генбанк', 'Геобанк', 'Гефест', 'Глобус', + 'Голдман Сакс Банк', 'Горбанк', 'Гута-Банк', 'Далена', 'Дальневосточный Банк', 'Денизбанк Москва', 'Держава', + 'Дж.П. Морган Банк Интернешнл', 'Джей Энд Ти Банк', 'Дойче Банк', 'Долинск', 'Дом-Банк', 'Донкомбанк', + 'Дон-Тексбанк', 'Дружба', 'ЕАТП Банк', 'Евразийский Банк', 'Евроазиатский Инвестиционный Банк', 'Евроальянс', + 'Еврофинанс Моснарбанк', 'Екатеринбург', 'Енисейский Объединенный Банк', 'Ермак', 'Живаго Банк', + 'Запсибкомбанк', 'Заречье', 'Заубер Банк', 'Земельный', 'Земский Банк', 'Зираат Банк (Москва)', 'Ижкомбанк', + 'ИК Банк', 'Икано Банк', 'Инбанк', 'Инвестторгбанк', 'Инг Банк (Евразия)', 'Интерпрогрессбанк', + 'Интерпромбанк', 'ИРС', 'ИС Банк', 'ИТ Банк', 'Итуруп', 'Ишбанк', 'Йошкар-Ола', 'Калуга', + 'Камский Коммерческий Банк', 'Капитал', 'Кетовский Коммерческий Банк', 'Киви Банк', 'Классик Эконом Банк', + 'Кольцо Урала', 'Коммерцбанк (Евразия)', 'Коммерческий Индо Банк', 'Консервативный Коммерческий Банк', + 'Континенталь', 'Космос', 'Костромаселькомбанк', 'Кошелев-Банк', 'Креди Агриколь Киб', 'Кредит Европа Банк', + 'Кредит Урал Банк', 'Кремлевский', 'Крокус-Банк', 'Крона-Банк', 'Кросна-Банк', 'КС Банк', 'Кубань Кредит', + 'Кубаньторгбанк', 'Кузбассхимбанк', 'Кузнецкбизнесбанк', 'Кузнецкий', 'Кузнецкий Мост', 'Курган', + 'Курскпромбанк', 'Кэб Эйчэнби Банк', 'Ланта-Банк', 'Левобережный', 'Локо-Банк', 'Майкопбанк', 'Майский', + 'Максима', 'МБА-Москва', 'МВС Банк', 'Мегаполис', 'Международный Финансовый Клуб', 'Мерседес-Бенц Банк Рус', + 'Металлинвестбанк', 'Металлург', 'Меткомбанк', 'Мидзухо Банк (Москва)', 'Мир Бизнес Банк', 'МКБ', 'Модульбанк', + 'Морган Стэнли Банк', 'Морской Банк', 'Москва-Сити', 'Московский Индустриальный Банк', + 'Московский Коммерческий Банк', 'Московский Кредитный Банк', 'Московский Нефтехимический Банк', + 'Московский Областной Банк', 'Московское Ипотечное Агентство', 'Москоммерцбанк', 'МС Банк Рус', 'МСКБ', + 'МСП Банк', 'МТИ Банк', 'МТС-Банк', 'Муниципальный Камчатпрофитбанк', 'Нальчик', 'Народный Банк', + 'Народный Банк Тувы', 'Народный Доверительный Банк', 'Натиксис Банк', 'Национальный Банк Сбережений', + 'Национальный Инвестиционно-Промышленный', 'Национальный Резервный Банк', 'Национальный Стандарт', 'НБД-Банк', + 'Невастройинвест', 'Нейва', 'Нефтепромбанк', 'НИБ', 'Нижневолжский Коммерческий Банк', 'Нико-Банк', 'НК Банк', + 'Новикомбанк', 'Новобанк', 'Новокиб', 'Новый Век', 'Новый Московский Банк', 'Нокссбанк', 'Ноосфера', + 'Норвик Банк', 'Нордеа Банк', 'НС Банк', 'НФК', 'Объединенный Банк Республики', 'Объединенный Капитал', + 'Онего', 'Оней Банк', 'Орбанк', 'Оргбанк', 'ОТП Банк', 'Первоуральскбанк', 'Первый Дортрансбанк', + 'Первый Инвестиционный Банк', 'Первый Клиентский Банк', 'Пересвет', 'Пермь', + 'Петербургский Социальный Ком. Банк', 'Платина', 'Плюс Банк', 'Пойдём!', 'Почта Банк', 'Почтобанк', + 'Приморский Территориальный', 'Приморье', 'Примсоцбанк', 'Приобье', 'Прио-Внешторгбанк', 'Прокоммерцбанк', + 'Проминвестбанк', 'Промсвязьбанк', 'Промсельхозбанк', 'Промтрансбанк', 'Профессионал Банк', + 'Профессиональный Инвестиционный Банк', 'Прохладный', 'Развитие-Столица', 'Райффайзенбанк', + 'РБА', 'Ренессанс Кредит', 'Рента-Банк', 'Ресо Кредит', 'Республиканский Кредитный Альянс', 'Ресурс-Траст', + 'РН Банк', 'Росбанк', 'Росбизнесбанк', 'Росгосстрах Банк', 'Росдорбанк', 'Роскосмосбанк', 'Россельхозбанк', + 'Российская Финансовая Корпорация', 'Российский Национальный Коммерческий Банк', 'Россита-Банк', 'Россия', + 'Ростфинанс', 'Росэксимбанк', 'Роял Кредит Банк', 'Руна-Банк', 'Руснарбанк', 'Русский Банк Сбережений', + 'Русский Региональный Банк', 'Русский Стандарт', 'Русфинанс Банк', 'Русьуниверсалбанк', 'РФИ Банк', + 'Саммит Банк', 'Санкт-Петербургский Банк Инвестиций', 'Саратов', 'Саровбизнесбанк', 'Сбербанк России', + 'Связь-Банк', 'СДМ-Банк', 'Севастопольский Морской Банк', 'Северный Морской Путь', 'Северный Народный Банк', + 'Северстройбанк', 'Севзапинвестпромбанк', 'Сельмашбанк', 'Сервис Резерв', 'Сетелем Банк', 'СИАБ', 'Сибсоцбанк', + 'Синко-Банк', 'Система', 'Сити Инвест Банк', 'Ситибанк', 'СКБ-Банк', 'Славия', 'Славянбанк', + 'Славянский Кредит', 'Снежинский', 'Собинбанк', 'Совкомбанк', 'Современные Стандарты Бизнеса', 'Соколовский', + 'Солид Банк', 'Солидарность', 'Социум-Банк', 'Союз', 'Спецстройбанк', 'Спиритбанк', 'Спутник', + 'Ставропольпромстройбанк', 'Столичный Кредит', 'Стройлесбанк', 'Сумитомо Мицуи Рус Банк', 'Сургутнефтегазбанк', + 'СЭБ Банк', 'Таврический Банк', 'Таганрогбанк', 'Тайдон', 'Тамбовкредитпромбанк', 'Татсоцбанк', 'Тексбанк', + 'Тендер-Банк', 'Тимер Банк', 'Тинькофф Банк', 'Тойота Банк', 'Тольяттихимбанк', 'Томскпромстройбанк', 'Торжок', + 'Транскапиталбанк', 'Трансстройбанк', 'Траст', 'Тэмбр-Банк', 'Углеметбанк', 'Унифондбанк', 'Уралпромбанк', + 'Уралсиб', 'Уралфинанс', 'Уральский Банк Реконструкции и Развития', 'Уральский Финансовый Дом', 'УРИ Банк', + 'Финанс Бизнес Банк', 'Финсервис', 'ФК Открытие', 'Фольксваген Банк Рус', 'Фора-Банк', 'Форбанк', 'Форштадт', + 'Фридом Финанс', 'Хакасский Муниципальный Банк', 'Химик', 'ХКФ Банк', 'Хлынов', 'Центрально-Азиатский', + 'Центр-Инвест', 'Центрокредит', 'ЦМРБанк', 'Чайна Констракшн Банк', 'Чайнасельхозбанк', 'Челиндбанк', + 'Челябинвестбанк', 'Эйч-Эс-Би-Си Банк (РР)', 'Эко-Инвест', 'Экономбанк', 'Экси-Банк', 'Экспобанк', + 'Экспресс-Волга', 'Элита', 'Эм-Ю-Эф-Джи Банк (Евразия)', 'Энергобанк', 'Энергомашбанк', 'Энерготрансбанк', + 'Эс-Би-Ай Банк', 'Ю Би Эс Банк', 'Юг-Инвестбанк', 'ЮМК Банк', 'Юникредит Банк', 'Юнистрим', 'Яринтербанк', + ) + + """ + BIC is a bank identification code that is used in Russia + See https://ru.wikipedia.org/wiki/Банковский_идентификационный_код + """ + + def bic(self): + region = self.random_element(self.region_codes) + department_code = self.numerify(self.random_element(self.department_code_formats)) + credit_organization_code = self.numerify(self.random_element(self.credit_organization_code_formats)) + return '04' + region + department_code + credit_organization_code + + """ + Correspondent account is established to handle various financial operations between financial institutions + See https://en.wikipedia.org/wiki/Корреспондентский_счёт + """ + + def correspondent_account(self): + credit_organization_code = self.numerify(self.random_element(self.credit_organization_code_formats)) + return '301' + self.numerify('#' * 14) + credit_organization_code + + """ + Checking account is used in banks to handle financial operations of clients + See https://ru.wikipedia.org/wiki/Расчётный_счёт + """ + + def checking_account(self): + account = self.random_element(self.checking_account_codes) + organization = self.random_element(self.organization_codes) + currency = self.random_element(self.currency_codes) + return account + organization + currency + self.numerify('#' * 12) + + def bank(self): + return self.random_element(self.banks) diff --git a/testbed/joke2k__faker/faker/providers/barcode/__init__.py b/testbed/joke2k__faker/faker/providers/barcode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85211bb015ee796b26df34e8008fac1fb60e1119 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/barcode/__init__.py @@ -0,0 +1,196 @@ +import re + +from .. import BaseProvider + + +class Provider(BaseProvider): + + upc_e_base_pattern = re.compile(r'^\d{6}$') + upc_ae_pattern1 = re.compile( + r'^(?P[01])' # The first digit must be 0 or 1 + r'(?=\d{11}$)' # followed by 11 digits of which + r'(?P\d{2})' # the first 2 digits make up the manufacturer code, + r'(?:(?P[012])0{4})' # if immediately followed by 00000, 10000, or 20000, + r'(?P\d{3})' # a 3-digit product code, + r'(?P\d)$', # and finally a check digit. + ) + upc_ae_pattern2 = re.compile( + r'^(?P[01])' # The first digit must be 0 or 1 + r'(?=\d{11}$)' # followed by 11 digits of which + r'(?P\d{3,4}?)' # the first 3 or 4 digits make up the manufacturer code, + r'(?:0{5})' # if immediately followed by 00000, + r'(?P\d{1,2})' # a 2-digit or single digit product code, + r'(?P\d)$', # and finally a check digit. + ) + upc_ae_pattern3 = re.compile( + r'^(?P[01])' # The first digit must be 0 or 1 + r'(?=\d{11}$)' # followed by 11 digits of which + r'(?P\d{5})' # the first 5 digits make up the manufacturer code, + r'(?:0{4}(?P[5-9]))' # if immediately followed by 0000 and a 5, 6, 7, 8, or 9, + r'(?P\d)$', # and finally a check digit. + ) + + def _ean(self, length=13, leading_zero=None): + if length not in (8, 13): + raise AssertionError("length can only be 8 or 13") + + code = [self.random_digit() for _ in range(length - 1)] + if leading_zero is True: + code[0] = 0 + elif leading_zero is False: + code[0] = self.random_int(1, 9) + + if length == 8: + weights = [3, 1, 3, 1, 3, 1, 3] + elif length == 13: + weights = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3] + + weighted_sum = sum(x * y for x, y in zip(code, weights)) + check_digit = (10 - weighted_sum % 10) % 10 + code.append(check_digit) + + return ''.join(str(x) for x in code) + + def _convert_upc_a2e(self, upc_a): + """ + Converts a 12-digit UPC-A barcode to its 8-digit UPC-E equivalent + + Not all UPC-A barcodes can be converted. + + :param upc_a: UPC-A barcode to convert + :return: UPC-E equivalent barcode + """ + if not isinstance(upc_a, str): + raise TypeError('`upc_a` is not a string') + m1 = self.upc_ae_pattern1.match(upc_a) + m2 = self.upc_ae_pattern2.match(upc_a) + m3 = self.upc_ae_pattern3.match(upc_a) + if not any([m1, m2, m3]): + raise ValueError('`upc_a` has an invalid value') + upc_e_template = '{number_system_digit}{mfr_code}{product_code}{extra}{check_digit}' + if m1: + upc_e = upc_e_template.format(**m1.groupdict()) + elif m2: + groupdict = m2.groupdict() + groupdict['extra'] = str(len(groupdict.get('mfr_code'))) + upc_e = upc_e_template.format(**groupdict) + else: + groupdict = m3.groupdict() + groupdict['product_code'] = '' + upc_e = upc_e_template.format(**groupdict) + return upc_e + + def _upc_ae(self, base=None, number_system_digit=None): + """ + Creates a 12-digit UPC-A barcode that can be converted to UPC-E + + Notes on this method: + - Please view notes on `upc_a()` and `upc_e()` first. + + :param base: A 6-digit string + :param number_system_digit: 0 or 1 + :return: 12-digit UPC-A barcode that can be converted to UPC-E + """ + if isinstance(base, str) and self.upc_e_base_pattern.match(base): + base = [int(x) for x in base] + else: + base = [self.random_int(0, 9) for _ in range(6)] + if number_system_digit not in [0, 1]: + number_system_digit = self.random_int(0, 1) + + if base[-1] <= 2: + code = base[:2] + base[-1:] + [0] * 4 + base[2:-1] + elif base[-1] <= 4: + code = base[:base[-1]] + [0] * 5 + base[base[-1]:-1] + else: + code = base[:5] + [0] * 4 + base[-1:] + + code.insert(0, number_system_digit) + weights = [3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3] + weighted_sum = sum(x * y for x, y in zip(code, weights)) + check_digit = (10 - weighted_sum % 10) % 10 + code.append(check_digit) + return ''.join(str(x) for x in code) + + def ean(self, length=13): + return self._ean(length) + + def ean8(self): + return self._ean(8) + + def ean13(self, leading_zero=None): + """ + Creates an EAN-13 barcode + + :param leading_zero: Leading digit will be 0 if True, 1-9 if False, and 0-9 otherwise + :return: An EAN-13 barcode + """ + return self._ean(13, leading_zero=leading_zero) + + def upc_a(self, upc_ae_mode=False, base=None, number_system_digit=None): + """ + Creates a 12-digit UPC-A barcode + + Notes on UPC-A barcode and this method: + - EAN-13 is a superset of UPC-A. Simply put, leading zero + UPC-A = EAN-13. + - For the lack of a concise and better term, this provider uses the term "upc_ae" to mean + that a UPC-A barcode can be converted to UPC-E. + - If `upc_ae_mode` is enabled, this method will only return UPC-A barcodes that can be + converted to UPC-E. In this mode the leading digit (number system) of the UPC-A barcode + may only start with 0 or 1. + - When `upc_ae_mode` is enabled, the `number_system_digit` may be explicitly set to 0 or 1. + If it is not set or is invalid, either values will be chosen at random. + - When `upc_ae_mode` is enabled, a 6-digit UPC-E string `base` may be explicitly set. If it + is not set or is invalid, a random 6 digit combination will be used. + - If `upc_ae_mode` is disabled, the values of `base` and `number_system_digit` are ignored. + + :param upc_ae_mode: Set to True explicitly to enable + :param base: A 6-digit string + :param number_system_digit: 0 or 1 + :return: 12-digit UPC-A barcode + """ + if upc_ae_mode is True: + return self._upc_ae(base=base, number_system_digit=number_system_digit) + else: + ean13 = self.ean13(leading_zero=True) + return ean13[1:] + + def upc_e(self, base=None, number_system_digit=None, safe_mode=True): + """ + Creates an 8-digit UPC-E barcode + + Notes on UPC-E barcode and this method: + - UPC-E barcodes can be expressed in 6, 7, or 8-digit formats, but this method uses the + 8 digit format, since it is trivial to convert to the other two formats. + - The first digit of the barcode denotes the number system used, either 0 or 1. + - The last digit is the check digit (more on that below). + - The remaining 6 digits are a bit more involved, but they are referred to as the `base` + argument elsewhere in this provider (for the lack of a concise and better term). + - Each UPC-E `base` have 2 UPC-A equivalents depending on the number system used. + - If the value of `number_system_digit` is not 0 or 1, either values will be chosen at random. + - A 6-digit string `base` may also be explicitly set. If invalid, it will be ignored, and a + new value for `base` will be generated. + - Internally, this method first generates a UPC-A barcode that can be converted to UPC-E, and + then actually performs a conversion for the result. This is because both the number + system and check digits of the UPC-E barcode are inherited from its UPC-A equivalent. + - Then there is `safe_mode`. Enabling this guarantees that every UPC-E barcode generated can + be converted to UPC-A, and that UPC-A value can be converted back again to UPC-E and still + be equal to the original value. In other words, the statement a2e(e2a(e)) == e holds True. + - As to why there is `safe_mode`, it is because there are some UPC-E values that share the + same UPC-A equivalent. For example, any UPC-E barcode of the form abc0000d, abc0003d, and + abc0004d share the same UPC-A value abc00000000d, but that UPC-A value will only convert + to abc0000d because of (a) how UPC-E is just a zero-suppressed version of UPC-A and + (b) the rules around the conversion. + + :param base: A 6-digit string + :param number_system_digit: First digit of the barcode + :param safe_mode: True or False. Guarantees that every UPC-E barcode generated can be + converted back-and-forth between UPC-A and UPC-E. + :return: 8-digit UPC-E barcode + """ + if safe_mode is not False: + upc_ae = self._upc_ae(base=base, number_system_digit=number_system_digit) + return self._convert_upc_a2e(upc_ae) + else: + upc_ae = self._upc_ae(base=base, number_system_digit=number_system_digit) + return upc_ae[0] + ''.join(str(x) for x in base) + upc_ae[-1] diff --git a/testbed/joke2k__faker/faker/providers/barcode/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/barcode/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17932797513d9281f5da9e742d2018baf305d04c --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/barcode/en_US/__init__.py @@ -0,0 +1,5 @@ +from .. import Provider as BarCodeProvider + + +class Provider(BarCodeProvider): + pass diff --git a/testbed/joke2k__faker/faker/providers/color/__init__.py b/testbed/joke2k__faker/faker/providers/color/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2239c03d5dfcdc1d83f011d7efbb76dfc48757d1 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/__init__.py @@ -0,0 +1,196 @@ +from collections import OrderedDict + +from .. import BaseProvider +from .color import RandomColor + +localized = True + + +class Provider(BaseProvider): + all_colors = OrderedDict(( + ("AliceBlue", "#F0F8FF"), + ("AntiqueWhite", "#FAEBD7"), + ("Aqua", "#00FFFF"), + ("Aquamarine", "#7FFFD4"), + ("Azure", "#F0FFFF"), + ("Beige", "#F5F5DC"), + ("Bisque", "#FFE4C4"), + ("Black", "#000000"), + ("BlanchedAlmond", "#FFEBCD"), + ("Blue", "#0000FF"), + ("BlueViolet", "#8A2BE2"), + ("Brown", "#A52A2A"), + ("BurlyWood", "#DEB887"), + ("CadetBlue", "#5F9EA0"), + ("Chartreuse", "#7FFF00"), + ("Chocolate", "#D2691E"), + ("Coral", "#FF7F50"), + ("CornflowerBlue", "#6495ED"), + ("Cornsilk", "#FFF8DC"), + ("Crimson", "#DC143C"), + ("Cyan", "#00FFFF"), + ("DarkBlue", "#00008B"), + ("DarkCyan", "#008B8B"), + ("DarkGoldenRod", "#B8860B"), + ("DarkGray", "#A9A9A9"), + ("DarkGreen", "#006400"), + ("DarkKhaki", "#BDB76B"), + ("DarkMagenta", "#8B008B"), + ("DarkOliveGreen", "#556B2F"), + ("DarkOrange", "#FF8C00"), + ("DarkOrchid", "#9932CC"), + ("DarkRed", "#8B0000"), + ("DarkSalmon", "#E9967A"), + ("DarkSeaGreen", "#8FBC8F"), + ("DarkSlateBlue", "#483D8B"), + ("DarkSlateGray", "#2F4F4F"), + ("DarkTurquoise", "#00CED1"), + ("DarkViolet", "#9400D3"), + ("DeepPink", "#FF1493"), + ("DeepSkyBlue", "#00BFFF"), + ("DimGray", "#696969"), + ("DodgerBlue", "#1E90FF"), + ("FireBrick", "#B22222"), + ("FloralWhite", "#FFFAF0"), + ("ForestGreen", "#228B22"), + ("Fuchsia", "#FF00FF"), + ("Gainsboro", "#DCDCDC"), + ("GhostWhite", "#F8F8FF"), + ("Gold", "#FFD700"), + ("GoldenRod", "#DAA520"), + ("Gray", "#808080"), + ("Green", "#008000"), + ("GreenYellow", "#ADFF2F"), + ("HoneyDew", "#F0FFF0"), + ("HotPink", "#FF69B4"), + ("IndianRed", "#CD5C5C"), + ("Indigo", "#4B0082"), + ("Ivory", "#FFFFF0"), + ("Khaki", "#F0E68C"), + ("Lavender", "#E6E6FA"), + ("LavenderBlush", "#FFF0F5"), + ("LawnGreen", "#7CFC00"), + ("LemonChiffon", "#FFFACD"), + ("LightBlue", "#ADD8E6"), + ("LightCoral", "#F08080"), + ("LightCyan", "#E0FFFF"), + ("LightGoldenRodYellow", "#FAFAD2"), + ("LightGray", "#D3D3D3"), + ("LightGreen", "#90EE90"), + ("LightPink", "#FFB6C1"), + ("LightSalmon", "#FFA07A"), + ("LightSeaGreen", "#20B2AA"), + ("LightSkyBlue", "#87CEFA"), + ("LightSlateGray", "#778899"), + ("LightSteelBlue", "#B0C4DE"), + ("LightYellow", "#FFFFE0"), + ("Lime", "#00FF00"), + ("LimeGreen", "#32CD32"), + ("Linen", "#FAF0E6"), + ("Magenta", "#FF00FF"), + ("Maroon", "#800000"), + ("MediumAquaMarine", "#66CDAA"), + ("MediumBlue", "#0000CD"), + ("MediumOrchid", "#BA55D3"), + ("MediumPurple", "#9370DB"), + ("MediumSeaGreen", "#3CB371"), + ("MediumSlateBlue", "#7B68EE"), + ("MediumSpringGreen", "#00FA9A"), + ("MediumTurquoise", "#48D1CC"), + ("MediumVioletRed", "#C71585"), + ("MidnightBlue", "#191970"), + ("MintCream", "#F5FFFA"), + ("MistyRose", "#FFE4E1"), + ("Moccasin", "#FFE4B5"), + ("NavajoWhite", "#FFDEAD"), + ("Navy", "#000080"), + ("OldLace", "#FDF5E6"), + ("Olive", "#808000"), + ("OliveDrab", "#6B8E23"), + ("Orange", "#FFA500"), + ("OrangeRed", "#FF4500"), + ("Orchid", "#DA70D6"), + ("PaleGoldenRod", "#EEE8AA"), + ("PaleGreen", "#98FB98"), + ("PaleTurquoise", "#AFEEEE"), + ("PaleVioletRed", "#DB7093"), + ("PapayaWhip", "#FFEFD5"), + ("PeachPuff", "#FFDAB9"), + ("Peru", "#CD853F"), + ("Pink", "#FFC0CB"), + ("Plum", "#DDA0DD"), + ("PowderBlue", "#B0E0E6"), + ("Purple", "#800080"), + ("Red", "#FF0000"), + ("RosyBrown", "#BC8F8F"), + ("RoyalBlue", "#4169E1"), + ("SaddleBrown", "#8B4513"), + ("Salmon", "#FA8072"), + ("SandyBrown", "#F4A460"), + ("SeaGreen", "#2E8B57"), + ("SeaShell", "#FFF5EE"), + ("Sienna", "#A0522D"), + ("Silver", "#C0C0C0"), + ("SkyBlue", "#87CEEB"), + ("SlateBlue", "#6A5ACD"), + ("SlateGray", "#708090"), + ("Snow", "#FFFAFA"), + ("SpringGreen", "#00FF7F"), + ("SteelBlue", "#4682B4"), + ("Tan", "#D2B48C"), + ("Teal", "#008080"), + ("Thistle", "#D8BFD8"), + ("Tomato", "#FF6347"), + ("Turquoise", "#40E0D0"), + ("Violet", "#EE82EE"), + ("Wheat", "#F5DEB3"), + ("White", "#FFFFFF"), + ("WhiteSmoke", "#F5F5F5"), + ("Yellow", "#FFFF00"), + ("YellowGreen", "#9ACD32"), + )) + + safe_colors = ( + 'black', 'maroon', 'green', 'navy', 'olive', + 'purple', 'teal', 'lime', 'blue', 'silver', + 'gray', 'yellow', 'fuchsia', 'aqua', 'white', + ) + + def color_name(self): + return self.random_element(self.all_colors.keys()) + + def safe_color_name(self): + return self.random_element(self.safe_colors) + + def hex_color(self): + return "#{}".format( + ("%x" % + self.random_int( + 1, 16777215)).ljust( + 6, '0')) + + def safe_hex_color(self): + color = ("%x" % self.random_int(0, 255)).ljust(3, '0') + return "#{0}{0}{1}{1}{2}{2}".format(*color) + + def rgb_color(self): + return ','.join(map(str, (self.random_int(0, 255) for _ in range(3)))) + + def rgb_css_color(self): + return 'rgb(%s)' % ','.join( + map(str, (self.random_int(0, 255) for _ in range(3)))) + + def color(self, hue=None, luminosity=None, color_format='hex'): + """ + Creates a color in specified format + + :param hue: monochrome, red, orange, yellow, green, blue, purple, pink, a number + from 0 to 360, or a tuple/list of 2 numbers from 0 to 360 + :param luminosity: bright, dark, light, or random + :param color_format: hsv, hsl, rgb, or hex with hex being default + :return: color in the specified format + """ + + return RandomColor(self.generator).generate( + hue=hue, luminosity=luminosity, color_format=color_format, + ) diff --git a/testbed/joke2k__faker/faker/providers/color/ar_PS/__init__.py b/testbed/joke2k__faker/faker/providers/color/ar_PS/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..71acaac06d62bd9f3bd8547c24e010d991ff2394 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/ar_PS/__init__.py @@ -0,0 +1,154 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + + +class Provider(ColorProvider): + all_colors = OrderedDict(( + ("أزرق أليس", "#F0F8FF"), + ("أبيض عتيق", "#FAEBD7"), + ("مائي", "#00FFFF"), + ("زبرجدي", "#7FFFD4"), + ("لازوردي", "#F0FFFF"), + ("صوفي", "#F5F5DC"), + ("حسائي", "#FFE4C4"), + ("أسود", "#000000"), + ("لوزي", "#FFEBCD"), + ("أزرق", "#0000FF"), + ("بنفسجي مزرق", "#8A2BE2"), + ("بني", "#A52A2A"), + ("خشبية", "#DEB887"), + ("أزرق كاديتي", "#5F9EA0"), + ("كرتوزي", "#7FFF00"), + ("شوكولاتيّ", "#D2691E"), + ("مرجاني", "#FF7F50"), + ("قنطريوني", "#6495ED"), + ("حرير الذرة", "#FFF8DC"), + ("قرمزي", "#DC143C"), + ("سيان", "#00FFFF"), + ("أزرق داكن", "#00008B"), + ("سيان داكن", "#008B8B"), + ("عصا الدهب الغامق", "#B8860B"), + ("رمادي داكن", "#A9A9A9"), + ("أخضر داكن", "#006400"), + ("خاكي داكن", "#BDB76B"), + ("ماجنتا داكن", "#8B008B"), + ("أخضر زيتوني داكن", "#556B2F"), + ("برتقالي داكن", "#FF8C00"), + ("أوركيدي داكن", "#9932CC"), + ("أحمر داكن", "#8B0000"), + ("سلموني داكن", "#E9967A"), + ("أخضر بحري داكن", "#8FBC8F"), + ("أزرق أردوازي داكن", "#483D8B"), + ("رمادي لازوردي داكن", "#2F4F4F"), + ("تركوازي داكن", "#00CED1"), + ("بنفسج داكن", "#9400D3"), + ("زهري غامق", "#FF1493"), + ("أزرق سماوي غامق", "#00BFFF"), + ("رمادي خافت", "#696969"), + ("أزرق فريق دودجر", "#1E90FF"), + ("الطوب شمت", "#B22222"), + ("أبيض وردي", "#FFFAF0"), + ("أخضر الغابت", "#228B22"), + ("فوشي", "#FF00FF"), + ("رمادي باهت", "#DCDCDC"), + ("أبيض شبحي", "#F8F8FF"), + ("ذهبي", "#FFD700"), + ("ذهبي", "#DAA520"), + ("رمادي", "#808080"), + ("أخضر", "#008000"), + ("أصفر مخضر", "#ADFF2F"), + ("عسلي", "#F0FFF0"), + ("وردي فاقع", "#FF69B4"), + ("قسطلي", "#CD5C5C"), + ("نيلي", "#4B0082"), + ("سكري", "#FFFFF0"), + ("خاكي", "#F0E68C"), + ("لاڤندر", "#E6E6FA"), + ("أحمر اللافندر", "#FFF0F5"), + ("أخضر عشبي", "#7CFC00"), + ("ليمون شيفوني", "#FFFACD"), + ("أزرق فاتح", "#ADD8E6"), + ("مرجاني فاتح", "#F08080"), + ("أزرق طفولي", "#E0FFFF"), + ("أصفر ذهبي فاتح ", "#FAFAD2"), + ("رمادي فاتح", "#D3D3D3"), + ("أخضر فاتح", "#90EE90"), + ("وردي فاتح", "#FFB6C1"), + ("سلموني فاتح", "#FFA07A"), + ("أخضر بحري فاتح", "#20B2AA"), + ("سماوي فاتح", "#87CEFA"), + ("أزرق أردوازي فاتح", "#778899"), + ("أزرق معدني فاتح", "#B0C4DE"), + ("أصفر فاتح", "#FFFFE0"), + ("ليمي", "#00FF00"), + ("أخضر ليموني", "#32CD32"), + ("كتاني", "#FAF0E6"), + ("فوشيا", "#FF00FF"), + ("كستنائي", "#800000"), + ("زبرجدي متوسط", "#66CDAA"), + ("أزرق متوسط", "#0000CD"), + ("أوركيدي متوسط", "#BA55D3"), + ("فوشي متوسط", "#9370DB"), + ("أخضر بحري متوسط", "#3CB371"), + ("أزرق أردوازي متوسط", "#7B68EE"), + ("أخضر ربيعي متوسط", "#00FA9A"), + ("ترموازي متوسط", "#48D1CC"), + ("أحمر بنفسجي", "#C71585"), + ("الأزرق متوسط", "#191970"), + ("نعناعي كريمي", "#F5FFFA"), + ("الوردي الضبابي", "#FFE4E1"), + ("موكاسيني", "#FFE4B5"), + ("أبيض نافاجو", "#FFDEAD"), + ("كحلي", "#000080"), + ("رباطي قديم", "#FDF5E6"), + ("زيتوني", "#808000"), + ("زيتوني رمادي", "#6B8E23"), + ("برتقالي", "#FFA500"), + ("أحمر برتقالي", "#FF4500"), + ("أوركيدي", "#DA70D6"), + ("ذهبي باهت", "#EEE8AA"), + ("أخضر باهت", "#98FB98"), + ("تركوازي باهت", "#AFEEEE"), + ("أحمر بنفسجي باهت", "#DB7093"), + ("بابايا", "#FFEFD5"), + ("حنطي", "#FFDAB9"), + ("بيرو", "#CD853F"), + ("زهري", "#FFC0CB"), + ("برقوقي", "#DDA0DD"), + ("أزرق مسحوقي", "#B0E0E6"), + ("أرجواني", "#800080"), + ("أحمر", "#FF0000"), + ("بني وردي", "#BC8F8F"), + ("أزرق ملكي", "#4169E1"), + ("بني السرج", "#8B4513"), + ("سالموني", "#FA8072"), + ("بني رملي", "#F4A460"), + ("أخضر بحري", "#2E8B57"), + ("صدفي", "#FFF5EE"), + ("سيينا", "#A0522D"), + ("فضي", "#C0C0C0"), + ("أزرق سماي", "#87CEEB"), + ("أزرق أردوازي", "#6A5ACD"), + ("رمادي معدني", "#708090"), + ("ثلجي", "#FFFAFA"), + ("أخضر ربيعي", "#00FF7F"), + ("أزرق معدني", "#4682B4"), + ("نطي", "#D2B48C"), + ("حذفي", "#008080"), + ("أرجواني", "#D8BFD8"), + ("طماطمي", "#FF6347"), + ("تركواز", "#40E0D0"), + ("بنفسجي", "#EE82EE"), + ("قمحي", "#F5DEB3"), + ("أبيض", "#FFFFFF"), + ("دخاني قمحي", "#F5F5F5"), + ("أصفر", "#FFFF00"), + ("أصفر مخضر", "#9ACD32"), + )) + + safe_colors = ( + 'أسود', 'كستنائي', 'أخضر', 'كحلي', 'زيتوني', + 'أرجواني', 'حذفي', 'ليمي', 'أزرق', 'فضي', + 'رمادي', 'أصفر', 'فوشي', 'مائي', 'أبيض', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/color.py b/testbed/joke2k__faker/faker/providers/color/color.py new file mode 100644 index 0000000000000000000000000000000000000000..8be2bed593c4953b40284ac56d77f86a419a44e2 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/color.py @@ -0,0 +1,277 @@ +""" +Code adapted from: +- https://github.com/davidmerfield/randomColor (CC0) +- https://github.com/kevinwuhoo/randomcolor-py (MIT License) + +Additional reference from: +- https://en.wikipedia.org/wiki/HSL_and_HSV +""" + +import colorsys +import math +import random +import sys + +COLOR_MAP = { + 'monochrome': { + 'hue_range': [0, 0], + 'lower_bounds': [ + [0, 0], [100, 0], + ], + }, + 'red': { + 'hue_range': [-26, 18], + 'lower_bounds': [ + [20, 100], [30, 92], [40, 89], + [50, 85], [60, 78], [70, 70], + [80, 60], [90, 55], [100, 50], + ], + }, + 'orange': { + 'hue_range': [19, 46], + 'lower_bounds': [ + [20, 100], [30, 93], [40, 88], [50, 86], + [60, 85], [70, 70], [100, 70], + ], + }, + 'yellow': { + 'hue_range': [47, 62], + 'lower_bounds': [ + [25, 100], [40, 94], [50, 89], [60, 86], + [70, 84], [80, 82], [90, 80], [100, 75], + ], + }, + 'green': { + 'hue_range': [63, 178], + 'lower_bounds': [ + [30, 100], [40, 90], [50, 85], [60, 81], + [70, 74], [80, 64], [90, 50], [100, 40], + ], + }, + 'blue': { + 'hue_range': [179, 257], + 'lower_bounds': [ + [20, 100], [30, 86], [40, 80], + [50, 74], [60, 60], [70, 52], + [80, 44], [90, 39], [100, 35], + ], + }, + 'purple': { + 'hue_range': [258, 282], + 'lower_bounds': [ + [20, 100], [30, 87], [40, 79], + [50, 70], [60, 65], [70, 59], + [80, 52], [90, 45], [100, 42], + ], + }, + 'pink': { + 'hue_range': [283, 334], + 'lower_bounds': [ + [20, 100], [30, 90], [40, 86], [60, 84], + [80, 80], [90, 75], [100, 73], + ], + }, +} + + +class RandomColor: + + def __init__(self, generator=None, seed=None): + self.colormap = COLOR_MAP + + # Option to specify a seed was not removed so this class + # can still be tested independently w/o generators + if generator: + self.random = generator.random + else: + self.seed = seed if seed else random.randint(0, sys.maxsize) + self.random = random.Random(self.seed) + + for color_name, color_attrs in self.colormap.items(): + lower_bounds = color_attrs['lower_bounds'] + s_min = lower_bounds[0][0] + s_max = lower_bounds[-1][0] + + b_min = lower_bounds[-1][1] + b_max = lower_bounds[0][1] + + self.colormap[color_name]['saturation_range'] = [s_min, s_max] + self.colormap[color_name]['brightness_range'] = [b_min, b_max] + + def generate(self, hue=None, luminosity=None, color_format='hex'): + # First we pick a hue (H) + h = self.pick_hue(hue) + + # Then use H to determine saturation (S) + s = self.pick_saturation(h, hue, luminosity) + + # Then use S and H to determine brightness (B). + b = self.pick_brightness(h, s, luminosity) + + # Then we return the HSB color in the desired format + return self.set_format([h, s, b], color_format) + + def pick_hue(self, hue): + hue_range = self.get_hue_range(hue) + hue = self.random_within(hue_range) + + # Instead of storing red as two separate ranges, + # we group them, using negative numbers + if hue < 0: + hue += 360 + + return hue + + def pick_saturation(self, hue, hue_name, luminosity): + if luminosity == 'random': + return self.random_within([0, 100]) + + if hue_name == 'monochrome': + return 0 + + saturation_range = self.get_saturation_range(hue) + + s_min = saturation_range[0] + s_max = saturation_range[1] + + if luminosity == 'bright': + s_min = 55 + elif luminosity == 'dark': + s_min = s_max - 10 + elif luminosity == 'light': + s_max = 55 + + return self.random_within([s_min, s_max]) + + def pick_brightness(self, h, s, luminosity): + b_min = self.get_minimum_brightness(h, s) + b_max = 100 + + if luminosity == 'dark': + b_max = b_min + 20 + elif luminosity == 'light': + b_min = (b_max + b_min) / 2 + elif luminosity == 'random': + b_min = 0 + b_max = 100 + + return self.random_within([b_min, b_max]) + + def set_format(self, hsv, color_format): + if color_format == 'hsv': + color = 'hsv({}, {}, {})'.format(*hsv) + + elif color_format == 'hsl': + hsl = self.hsv_to_hsl(hsv) + color = 'hsl({}, {}, {})'.format(*hsl) + + elif color_format == 'rgb': + rgb = self.hsv_to_rgb(hsv) + color = 'rgb({}, {}, {})'.format(*rgb) + + else: + rgb = self.hsv_to_rgb(hsv) + color = '#{:02x}{:02x}{:02x}'.format(*rgb) + + return color + + def get_minimum_brightness(self, h, s): + lower_bounds = self.get_color_info(h)['lower_bounds'] + + for i in range(len(lower_bounds) - 1): + s1 = lower_bounds[i][0] + v1 = lower_bounds[i][1] + + s2 = lower_bounds[i + 1][0] + v2 = lower_bounds[i + 1][1] + + if s1 <= s <= s2: + m = (v2 - v1) / (s2 - s1) + b = v1 - m * s1 + + return m * s + b + + return 0 + + def get_hue_range(self, color_input): + if isinstance(color_input, (int, float)) and 0 <= color_input <= 360: + color_input = int(color_input) + return [color_input, color_input] + + elif isinstance(color_input, str) and color_input in self.colormap: + return self.colormap[color_input]['hue_range'] + + elif color_input is None: + return [0, 360] + + try: + v1, v2 = color_input + v1 = int(v1) + v2 = int(v2) + except (ValueError, TypeError): + msg = 'Hue must be a valid string, numeric type, or a tuple/list of 2 numeric types.' + raise TypeError(msg) + else: + if v2 < v1: + v1, v2 = v2, v1 + if v1 < 0: + v1 = 0 + if v2 > 360: + v2 = 360 + return [v1, v2] + + def get_saturation_range(self, hue): + return self.get_color_info(hue)['saturation_range'] + + def get_color_info(self, hue): + # Maps red colors to make picking hue easier + if 334 <= hue <= 360: + hue -= 360 + + for color_name, color in self.colormap.items(): + if color['hue_range'][0] <= hue <= color['hue_range'][1]: + return self.colormap[color_name] + else: + raise ValueError('Value of hue `%s` is invalid.' % hue) + + def random_within(self, r): + return self.random.randint(int(r[0]), int(r[1])) + + @classmethod + def hsv_to_rgb(cls, hsv): + """ + Converts HSV to RGB + + :param hsv: 3-tuple of h, s, and v values + :return: 3-tuple of r, g, and b values + """ + h, s, v = hsv + h = 1 if h == 0 else h + h = 359 if h == 360 else h + + h = float(h)/360 + s = float(s)/100 + v = float(v)/100 + + rgb = colorsys.hsv_to_rgb(h, s, v) + return (int(c * 255) for c in rgb) + + @classmethod + def hsv_to_hsl(cls, hsv): + """ + Converts HSV to HSL + + :param hsv: 3-tuple of h, s, and v values + :return: 3-tuple of h, s, and l values + """ + h, s, v = hsv + + s = float(s)/100 + v = float(v)/100 + l = 0.5 * v * (2 - s) # noqa: E741 + + if l in [0, 1]: + s = 0 + else: + s = v * s / (1 - math.fabs(2 * l - 1)) + return (int(c) for c in [h, s * 100, l * 100]) diff --git a/testbed/joke2k__faker/faker/providers/color/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/color/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8edf3372ca4eadb7e939f41805d47cf9514778f1 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/en_US/__init__.py @@ -0,0 +1,5 @@ +from .. import Provider as ColorProvider + + +class Provider(ColorProvider): + pass diff --git a/testbed/joke2k__faker/faker/providers/color/fr_FR/__init__.py b/testbed/joke2k__faker/faker/providers/color/fr_FR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..261201b10d299093ec9104823166c1f0939c0e03 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/fr_FR/__init__.py @@ -0,0 +1,153 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + +localized = True + + +class Provider(ColorProvider): + all_colors = OrderedDict(( + ("Noir", "#000000"), + ("Gris mat", "#696969"), + ("Gris", "#808080"), + ("Gris foncé (Acier)", "#A9A9A9"), + ("Gris argent", "#C0C0C0"), + ("Gris clair", "#D3D3D3"), + ("Gris gainsboro (Etain)", "#DCDCDC"), + ("Blanc fumée", "#F5F5F5"), + ("Blanc spectral", "#F8F8FF"), + ("Blanc", "#FFFFFF"), + ("Ivoire", "#FFFFF0"), + ("Blanc floral", "#FFFAF0"), + ("Blanc coquillage", "#FFF5EE"), + ("Blanc lavande", "#FFF0F5"), + ("Blanc dentelle", "#FDF5E6"), + ("Blanc Lin", "#FAF0E6"), + ("Rose brumeux", "#FFE4E1"), + ("Rose", "#FFC0CB"), + ("Rose clair", "#FFB6C1"), + ("Rose Passion", "#FF69B4"), + ("Rose profond", "#FF1493"), + ("Violet pâle", "#DB7093"), + ("Fushia (Magenta)", "#FF00FF"), + ("Violet moyen", "#C71585"), + ("Violet chardon", "#D8BFD8"), + ("Prune", "#DDA0DD"), + ("Violet", "#EE82EE"), + ("Violet orchidée", "#DA70D6"), + ("Violet orchidée moyen", "#BA55D3"), + ("Violet orchidée foncé", "#9932CC"), + ("Violet foncé", "#9400D3"), + ("Bleu violet", "#8A2BE2"), + ("Indigo", "#4B0082"), + ("Bleu ardoise moyen", "#7B68EE"), + ("Bleu ardoise", "#6A5ACD"), + ("Bleu ardoise foncé", "#483D8B"), + ("Pourpre moyen", "#9370DB"), + ("Magenta foncé", "#8B008B"), + ("Pourpre", "#800080"), + ("Brun rosé", "#BC8F8F"), + ("Corail clair", "#F08080"), + ("Corail", "#FF7F50"), + ("Tomate", "#FF6347"), + ("Orangé", "#FF4500"), + ("Rouge", "#FF0000"), + ("Rouge cramoisi", "#DC143C"), + ("Saumon clair", "#FFA07A"), + ("Saumon Foncé", "#E9967A"), + ("Saumon", "#FA8072"), + ("Rouge Indien", "#CD5C5C"), + ("Rouge brique", "#B22222"), + ("Brun", "#A52A2A"), + ("Rouge foncé", "#8B0000"), + ("Bordeaux", "#800000"), + ("Beige", "#F5F5DC"), + ("Beige antique", "#FAEBD7"), + ("Beige papaye", "#FFEFD5"), + ("Amande", "#FFEBCD"), + ("Bisque", "#ffe4c4"), + ("Beige pêche", "#FFDAB9"), + ("Beige mocassin", "#FFE4B5"), + ("Jaune blanc navaro", "#FFDEAD"), + ("Jaune blé", "#F5DEB3"), + ("Brun bois rustique", "#DEB887"), + ("Brun roux", "#D2B48C"), + ("Brun sable", "#F4A460"), + ("Orange", "#FFA500"), + ("Orange foncé", "#FF8C00"), + ("Chocolat", "#D2691E"), + ("Brun pérou", "#CD853F"), + ("Terre de Sienne", "#A0522D"), + ("Brun cuir", "#8B4513"), + ("Jaune clair", "#FFFFE0"), + ("Jaune maïs doux", "#FFF8DC"), + ("Jaune doré clair", "#FAFAD2"), + ("Beige citron soie", "#FFFACD"), + ("Jaune doré pâle", "#EEE8AA"), + ("Brun kaki", "#F0E68C"), + ("Jaune", "#FFFF00"), + ("Or", "#FFD700"), + ("Jaune doré", "#DAA520"), + ("Jaune doré foncé", "#B8860B"), + ("Brun kaki foncé", "#BDB76B"), + ("Jaune vert", "#9ACD32"), + ("Kaki", "#6B8E23"), + ("Olive", "#808000"), + ("Vert olive foncé", "#556B2F"), + ("Vert jaune", "#ADFF2F"), + ("Chartreuse", "#7FFF00"), + ("Vert prairie", "#7CFC00"), + ("Citron vert", "#00FF00"), + ("Citron vert foncé", "#32CD32"), + ("Blanc menthe", "#F5FFFA"), + ("Miellat", "#F0FFF0"), + ("Vert pâle", "#98FB98"), + ("Vert clair", "#90EE90"), + ("Vert printemps", "#00FF7F"), + ("Vert printemps moyen", "#00FA9A"), + ("Vert forêt", "#228B22"), + ("Vert", "#008000"), + ("Vert foncé", "#006400"), + ("Vert océan foncé", "#8FBC8F"), + ("Vert océan moyen", "#3CB371"), + ("Vert océan", "#2E8B57"), + ("Gris ardoise clair", "#778899"), + ("Gris ardoise", "#708090"), + ("Gris ardoise foncé", "#2F4F4F"), + ("Bleu alice", "#F0F8FF"), + ("Bleu azur", "#F0FFFF"), + ("Cyan clair", "#E0FFFF"), + ("Azurin", "#AFEEEE"), + ("Aigue-marine", "#7FFFD4"), + ("Aigue-marine moyen", "#66CDAA"), + ("Cyan", "#00FFFF"), + ("Turquoise", "#40E0D0"), + ("Turquoise moyen", "#48D1CC"), + ("Turquoise foncé", "#00CED1"), + ("Vert marin clair", "#20B2AA"), + ("Cyan foncé", "#008B8B"), + ("Vert sarcelle", "#008080"), + ("Bleu pétrole", "#5F9EA0"), + ("Bleu poudre", "#B0E0E6"), + ("Bleu clair", "#ADD8E6"), + ("Bleu azur clair", "#87CEFA"), + ("Bleu azur", "#87CEEB"), + ("Bleu azur profond", "#00BFFF"), + ("Bleu toile", "#1E90FF"), + ("Bleu lavande", "#E6E6FA"), + ("Bleu acier clair", "#B0C4DE"), + ("Bleuet", "#6495ED"), + ("Bleu acier", "#4682B4"), + ("Bleu royal", "#4169E1"), + ("Bleu", "#0000FF"), + ("Bleu moyen", "#0000CD"), + ("Bleu foncé", "#00008B"), + ("Bleu marin", "#000080"), + ("Bleu de minuit", "#191970"), + )) + + safe_colors = ( + 'noir', 'bordeaux', 'vert', 'rouge', + 'violet', 'sarcelle', 'bleu', 'argent', + 'gris', 'jaune', 'fuchsia', 'cyan', 'blanc', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/hr_HR/__init__.py b/testbed/joke2k__faker/faker/providers/color/hr_HR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17540e99e899c4e459f48ed9fa07084ec6c1fe3a --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/hr_HR/__init__.py @@ -0,0 +1,156 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + +localized = True + + +class Provider(ColorProvider): + all_colors = OrderedDict(( + ('Akvamarin', '#7FFFD4'), + ('Antikna bijela', '#FAEBD7'), + ('Azurna', '#F0FFFF'), + ('Bež', '#F5F5DC'), + ('Bijela', '#FFFFFF'), + ('Bijelo bilje', '#FFFAF0'), + ('Bjelokost', '#FFFFF0'), + ('Blijeda kudelja', '#EEE8AA'), + ('Blijedi badem', '#FFEBCD'), + ('Blijedoljubičasta', '#DB7093'), + ('Blijedotirkizna', '#AFEEEE'), + ('Blijedozelena', '#98FB98'), + ('Breskva', '#FFDAB9'), + ('Brončana', '#D2B48C'), + ('Čeličnoplava', '#4682B4'), + ('Čičak', '#D8BFD8'), + ('Cijan', '#00FFFF'), + ('Čipka', '#FDF5E6'), + ('Čokoladna', '#D2691E'), + ('Crna', '#000000'), + ('Crvena', '#FF0000'), + ('Dim', '#F5F5F5'), + ('Dodger plava', '#1E90FF'), + ('Duboko ružičasta', '#FF1493'), + ('Fuksija', '#FF00FF'), + ('Gainsboro', '#DCDCDC'), + ('Grimizna', '#DC143C'), + ('Indigo', '#4B0082'), + ('Jelenska koža', '#FFE4B5'), + ('Kadetski plava', '#5F9EA0'), + ('Kestenjasta', '#800000'), + ('Koraljna', '#FF7F50'), + ('Kraljevski plava', '#4169E1'), + ('Kudelja', '#DAA520'), + ('Lan', '#FAF0E6'), + ('Lavanda', '#E6E6FA'), + ('Limun', '#FFFACD'), + ('Lipa', '#00FF00'), + ('Ljubičasta', '#EE82EE'), + ('Magenta', '#FF00FF'), + ('Maslinasta', '#808000'), + ('Medljika', '#F0FFF0'), + ('Menta', '#F5FFFA'), + ('Modro nebo', '#00BFFF'), + ('Modrozelena', '#008080'), + ('Mornarska', '#000080'), + ('Morskozelena', '#2E8B57'), + ('Mračno siva', '#696969'), + ('Narančasta', '#FFA500'), + ('Narančastocrvena', '#FF4500'), + ('Narančastoružičasta', '#FA8072'), + ('Noćno plava', '#191970'), + ('Orhideja', '#DA70D6'), + ('Papaja', '#FFEFD5'), + ('Peru', '#CD853F'), + ('Plava', '#0000FF'), + ('Plavi prah', '#B0E0E6'), + ('Plavi škriljevac', '#6A5ACD'), + ('Plavkasta', '#F0F8FF'), + ('Plavo cvijeće', '#6495ED'), + ('Plavo nebo', '#87CEEB'), + ('Plavoljubičasta', '#8A2BE2'), + ('Porculanska', '#FFE4C4'), + ('Prljavomaslinasta', '#6B8E23'), + ('Proljetnozelena', '#00FF7F'), + ('Prozirno bijela', '#F8F8FF'), + ('Pšenica', '#F5DEB3'), + ('Purpurna', '#800080'), + ('Rajčica', '#FF6347'), + ('Rumena lavanda', '#FFF0F5'), + ('Ružičasta', '#FFC0CB'), + ('Ružičastosmeđa', '#BC8F8F'), + ('Siva', '#808080'), + ('Sivi škriljevac', '#708090'), + ('Sivožuta', '#F0E68C'), + ('Smeđa', '#A52A2A'), + ('Smeđe sedlo', '#8B4513'), + ('Smeđi pijesak', '#F4A460'), + ('Smeđkasto bijela', '#FFDEAD'), + ('Snijeg', '#FFFAFA'), + ('Srebrna', '#C0C0C0'), + ('Srednja akvamarin', '#66CDAA'), + ('Srednja crvenoljubičasta', '#C71585'), + ('Srednja morskozelena', '#3CB371'), + ('Srednja orhideja', '#BA55D3'), + ('Srednja plava', '#0000CD'), + ('Srednja proljetnozelena', '#00FA9A'), + ('Srednja purpurna', '#9370DB'), + ('Srednja tirkizna', '#48D1CC'), + ('Srednje plavi škriljevac', '#7B68EE'), + ('Svijetla čeličnoplava', '#B0C4DE'), + ('Svijetla narančastoružičasta', '#FFA07A'), + ('Svijetli cijan', '#E0FFFF'), + ('Svijetlo drvo', '#DEB887'), + ('Svijetlokoraljna', '#F08080'), + ('Svijetlomorskozelena', '#20B2AA'), + ('Svijetloplava', '#ADD8E6'), + ('Svijetloružičasta', '#FFB6C1'), + ('Svijetlosiva', '#D3D3D3'), + ('Svijetlosivi škriljevac', '#778899'), + ('Svijetlozelena', '#90EE90'), + ('Svijetložuta kudelja', '#FAFAD2'), + ('Svijetložuta', '#FFFFE0'), + ('Šamotna opeka', '#B22222'), + ('Školjka', '#FFF5EE'), + ('Šljiva', '#DDA0DD'), + ('Tamna kudelja', '#B8860B'), + ('Tamna magenta', '#8B008B'), + ('Tamna narančastoružičasta', '#E9967A'), + ('Tamna orhideja', '#9932CC'), + ('Tamna sivožuta', '#BDB76B'), + ('Tamni cijan', '#008B8B'), + ('Tamno zelena', '#006400'), + ('Tamnocrvena', '#8B0000'), + ('Tamnoljubičasta', '#9400D3'), + ('Tamnomaslinasta', '#556B2F'), + ('Tamnonarančasta', '#FF8C00'), + ('Tamnoplava', '#00008B'), + ('Tamnoplavi škriljevac', '#483D8B'), + ('Tamnosiva', '#A9A9A9'), + ('Tamnosivi škriljevac', '#2F4F4F'), + ('Tamnotirkizna', '#00CED1'), + ('Tamnozelena', '#8FBC8F'), + ('Tirkizna', '#40E0D0'), + ('Topla ružičasta', '#FF69B4'), + ('Vedro nebo', '#87CEFA'), + ('Voda', '#00FFFF'), + ('Zelena lipa', '#32CD32'), + ('Zelena šuma', '#228B22'), + ('Zelena tratina', '#7CFC00'), + ('Zelena', '#008000'), + ('Zeleni liker', '#7FFF00'), + ('Zelenožuta', '#ADFF2F'), + ('Zlatna', '#FFD700'), + ('Žućkastocrvena zemlja', '#CD5C5C'), + ('Žućkastoružičasta', '#FFE4E1'), + ('Žućkastosmeđa glina', '#A0522D'), + ('Žuta svila', '#FFF8DC'), + ('Žuta', '#FFFF00'), + ('Žutozelena', '#9ACD32'), + )) + + safe_colors = ( + 'crna', 'kestenjasta', 'zelena', 'mornarska', 'maslinasta', + 'purpurna', 'modrozelena', 'lipa', 'plava', 'srebrna', + 'siva', 'žuta', 'fuksija', 'voda', 'bijela', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/hu_HU/__init__.py b/testbed/joke2k__faker/faker/providers/color/hu_HU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0b604adddfb8ca85b363ef68367ab1e8c71b05 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/hu_HU/__init__.py @@ -0,0 +1,10 @@ +from faker.providers import BaseProvider + + +class Provider(BaseProvider): + + safe_colors = ( + 'fekete', 'bordó', 'zöld', 'királykék', 'oliva', + 'bíbor', 'kékeszöld', 'citromzöld', 'kék', 'ezüst', + 'szürke', 'sárga', 'mályva', 'akvamarin', 'fehér', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/hy_AM/__init__.py b/testbed/joke2k__faker/faker/providers/color/hy_AM/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2dfa2cdba61b960bdf09c28a8911465361d0780d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/hy_AM/__init__.py @@ -0,0 +1,153 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + + +class Provider(ColorProvider): + + all_colors = OrderedDict(( + ("Ալիսի կապույտ", "#F0F8FF"), + ("Անանուխի կրեմ", "#F5FFFA"), + ("Անտառային կանաչ", "#228B22"), + ("Արծաթագույն", "#C0C0C0"), + ("Արքայական կապույտ", "#4169E1"), + ("Բաց դեղին", "#FFFFE0"), + ("Բաց դեղնաոսկեգույն", "#FAFAD2"), + ("Բաց երկնագույն", "#87CEFA"), + ("Բաց ծովային կանաչ", "#20B2AA"), + ("Բաց կաթնագույն", "#FFFFF0"), + ("Բաց կանաչ", "#90EE90"), + ("Բաց կապույտ", "#ADD8E6"), + ("Բաց կապտականաչ", "#E0FFFF"), + ("Բաց կորալ", "#F08080"), + ("Բաց մանուշակագույն", "#EE82EE"), + ("Բաց մոխրագույն թերթաքար", "#778899"), + ("Բաց մոխրագույն", "#D3D3D3"), + ("Բաց նշագույն", "#FFEBCD"), + ("Բաց պողպատե կապույտ", "#B0C4DE"), + ("Բաց սաղմոնագույն", "#FFA07A"), + ("Բաց վարդագույն", "#FFB6C1"), + ("Բեժ", "#F5F5DC"), + ("Բոսորագույն", "#DC143C"), + ("Գարնանային կանաչ", "#00FF7F"), + ("Գեյնսբորրո", "#DCDCDC"), + ("Գունատ կանաչ", "#98FB98"), + ("Գունատ կարմիր մանուշակագույն", "#DB7093"), + ("Գունատ ոսկեգույն", "#EEE8AA"), + ("Գունատ փիրուզագույն", "#AFEEEE"), + ("Գրասենյակային կանաչ", "#008000"), + ("Դարչնագույն ավազ", "#F4A460"), + ("Դարչնագույն", "#964b00"), + ("Դեղին", "#FFFF00"), + ("Դեղձի կրեմ", "#FFDAB9"), + ("Դեղնականաչ", "#9ACD3"), + ("Դոդջերս կապույտ", "#1E90FF"), + ("Եգիպտացորենի մազիկներ", "#FFF8DC"), + ("Երկնագույն մառախուղ", "#F0FFFF"), + ("Երկնագույն", "#87CEEB"), + ("Զինվորական կանաչ", "#6B8E23"), + ("Թամբի դարչնագույն", "#8B4513"), + ("Թեժ վարդագույն", "#FF69B4"), + ("Թուխ", "#D2B48C"), + ("Ինդիգո", "#4B0082"), + ("Լայմի կանաչ", "#32CD32"), + ("Լավանդ", "#E6E6FA"), + ("Լոլիկ", "#FF6347"), + ("Խակի", "#F0E68C"), + ("Խոլորձագույն", "#DA70D6"), + ("Ծխագույն", "#F5F5F5"), + ("Ծովախեցի", "#FFF5EE"), + ("Ծովակնագույն", "#7FFFD4"), + ("Ծովային կանաչ", "#2E8B57"), + ("Կադետների կապույտ", "#5F9EA0"), + ("Կաթնագույն", "#FFFAF0"), + ("Կակաոյի դարչնագույն", "#D2691E"), + ("Կանաչ", "#00FF00"), + ("Կանաչադեղին", "#ADFF2F"), + ("Կապույտ թերթաքար", "#6A5ACD"), + ("Կապույտ մանուշակագույն", "#8A2BE2"), + ("Կապույտ փոշի", "#B0E0E6"), + ("Կապույտ", "#0000FF"), + ("Կապտականաչ", "#00FFFF"), + ("Կարմիր դարչնագույն", "#A52A2A"), + ("Կարմիր լավանդ", "#FFF0F5"), + ("Կարմիր մանուշակագույն", "#C71585"), + ("Կարմիր", "#FF0000"), + ("Կեսգիշերային կապույտ", "#191970"), + ("Կիտրոնի շիֆոն", "#FFFACD"), + ("Կորալ", "#FF7F50"), + ("Հարած պապայա", "#FFEFD5"), + ("Հին ժանյակ", "#FDF5E6"), + ("Հնաոճ սպիտակ", "#FAEBD7"), + ("Հնդկական կարմիր", "#CD5C5C"), + ("Հրակայուն աղյուս", "#B22222"), + ("Ձիթապտղի գույն", "#808000"), + ("Ձյունաճերմակ", "#FFFAFA"), + ("Մանուշակագույն", "#800080"), + ("Մեղրացող սեխ", "#F0FFF0"), + ("Միջին գարնանային կանաչ", "#00FA9A"), + ("Միջին խոլորձագույն", "#BA55D3"), + ("Միջին ծովակնագույն", "#66CDAA"), + ("Միջին ծովային կանաչ", "#3CB371"), + ("Միջին կապույտ թերթաքար", "#7B68EE"), + ("Միջին կապույտ", "#0000CD"), + ("Միջին կապտականաչ", "#9370DB"), + ("Միջին փիրուզագույն", "#48D1CC"), + ("Մոխրագույն թերթաքար", "#708090"), + ("Մոխրագույն", "#808080"), + ("Մոկասին", "#FFE4B5"), + ("Մուգ երկնագույն", "#00BFFF"), + ("Մուգ խակի", "#BDB76B"), + ("Մուգ խոլորձագույն", "#9932CC"), + ("Մուգ ծովային կանաչ", "#8FBC8F"), + ("Մուգ կանաչ", "#006400"), + ("Մուգ կապույտ թերթաքար", "#483D8B"), + ("Մուգ կապույտ", "#00008B"), + ("Մուգ կապտականաչ", "#008080"), + ("Մուգ կարմիր", "#8B0000"), + ("Մուգ ձիթապտղի կանաչ", "#556B2F"), + ("Մուգ մանուշակագույն", "#9400D3"), + ("Մուգ մոխրագույն թերթաքար", "#2F4F4F"), + ("Մուգ մոխրագույն", "#696969"), + ("Մուգ մոխրագույն", "#A9A9A9"), + ("Մուգ նարնջագույն", "#FF8C00"), + ("Մուգ ոսկեգույն", "#B8860B"), + ("Մուգ սաղմոնագույն", "#E9967A"), + ("Մուգ վառ մանուշակագույն", "#8B008B"), + ("Մուգ վարդագույն", "#FF1493"), + ("Մուգ փիրուզագույն", "#00CED1"), + ("Նավահո սպիտակ", "#FFDEAD"), + ("Նավատորմի կապույտ", "#000080"), + ("Նարնջագույն կարմիր", "#FF4500"), + ("Նարնջագույն", "#FFA500"), + ("Նշագույն", "#FFE4C4"), + ("Շագանակագույն", "#800000"), + ("Շարտրուզ", "#7FFF00"), + ("Ոսկեգույն ձող", "#DAA520"), + ("Ոսկեգույն", "#FFD700"), + ("Պերու", "#CD853F"), + ("Պողպատե կապույտ", "#4682B4"), + ("Սալոր", "#DDA0DD"), + ("Սաղմոնագույն", "#FA8072"), + ("Սիենա", "#A0522D"), + ("Սիզամարգի կանաչ", "#7CFC00"), + ("Սպիտակ ստվեր", "#F8F8FF"), + ("Սպիտակ", "#FFFFFF"), + ("Սև", "#000000"), + ("Վառ մանուշակագույն", "#FF00FF"), + ("Վարդագույն", "#FFC0CB"), + ("Վարդագույն", "#FFE4E1"), + ("Վարդադարչնագույն", "#BC8F8F"), + ("Վուշ", "#FAF0E6"), + ("Տատասկ", "#D8BFD8"), + ("Տերեփուկի կապույտ", "#6495ED"), + ("Ցորենագույն", "#F5DEB3"), + ("Փիրուզագույն", "#40E0D0"), + ("Փխրուն փայտ", "#DEB887"), + )) + + safe_colors = ( + 'սև', 'շագանակագույն', 'կանաչ', 'նավատորմի կապույտ', 'ձիթապտղի գույն', + 'մանուշակագույն', 'մուգ կապտականաչ', 'լայմ', 'կապույտ', 'արծաթագույն', + 'մոխրագույն', 'դեղին', 'վառ մանուշակագույն', 'կապտականաչ', 'սպիտակ', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/pt_BR/__init__.py b/testbed/joke2k__faker/faker/providers/color/pt_BR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a2d949bc2b7dbaa19271863eb0299d7e4e0afb --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/pt_BR/__init__.py @@ -0,0 +1,244 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + +localized = True + + +class Provider(ColorProvider): + all_colors = OrderedDict(( + ("Açafrão", "#F4C430"), + ("Água-marinha média", "#66CDAA"), + ("Água-marinha", "#7FFFD4"), + ("Água", "#00FFFF"), + ("Alizarina", "#E32636"), + ("Amarelo brasilis", "#ECDB00"), + ("Amarelo claro", "#FFFFE0"), + ("Amarelo creme", "#ECD690"), + ("Amarelo escuro", "#F2B73F"), + ("Amarelo esverdeado", "#9ACD32"), + ("Amarelo esverdeado", "#ADFF2F"), + ("Amarelo ouro claro", "#FAFAD2"), + ("Amarelo queimado", "#EEAD2D"), + ("Amarelo", "#FFFF00"), + ("Âmbar", "#FFBF00"), + ("Ameixa", "#DDA0DD"), + ("Amêndoa", "#FFEBCD"), + ("Ametista", "#9966CC"), + ("Aspargo", "#7BA05B"), + ("Azul aço claro", "#B0C4DE"), + ("Azul aço", "#4682B4"), + ("Azul alice", "#F0F8FF"), + ("Azul ardósia claro", "#8470FF"), + ("Azul ardósia escuro", "#483D8B"), + ("Azul ardósia médio", "#7B68EE"), + ("Azul ardósia", "#6A5ACD"), + ("Azul areado", "#B8CAD4"), + ("Azul brasilis brilhante", "#09ACDB"), + ("Azul brasilis", "#00BDCE"), + ("Azul cadete", "#5F9EA0"), + ("Azul camarada", "#054F77"), + ("Azul celeste brilhante", "#007FFF"), + ("Azul celeste pernambucano", "#00A4CD"), + ("Azul celeste", "#F0FFFF"), + ("Azul céu claro", "#87CEFA"), + ("Azul céu profundo", "#00BFFF"), + ("Azul céu", "#87CEEB"), + ("Azul claro", "#ADD8E6"), + ("Azul cobalto", "#0047AB"), + ("Azul escuro", "#00008B"), + ("Azul flor de milho", "#6495ED"), + ("Azul força aérea", "#5D8AA8"), + ("Azul furtivo", "#1E90FF"), + ("Azul manteiga", "#a6aa3e"), + ("Azul marinho", "#120A8F"), + ("Azul médio", "#0000CD"), + ("Azul meia-noite", "#191970"), + ("Azul petróleo", "#084D6E"), + ("Azul pólvora", "#B0E0E6"), + ("Azul real", "#0000DD"), + ("Azul taparuere", "#248EFF"), + ("Azul turquesa brilhante", "#00DDFF"), + ("Azul turquesa", "#00CCEE"), + ("Azul violeta", "#8A2BE2"), + ("Azul", "#0000FF"), + ("Bege", "#F5F5DC"), + ("Bordô", "#800000"), + ("Borgonha", "#900020"), + ("Branco antigo", "#FAEBD7"), + ("Branco fantasma", "#F8F8FF"), + ("Branco floral", "#FFFAF0"), + ("Branco fumaça", "#F5F5F5"), + ("Branco navajo", "#FFDEAD"), + ("Branco", "#FFFFFF"), + ("Brasil", "#A7F432"), + ("Bronze", "#CD7F32"), + ("Caqui escuro", "#BDB76B"), + ("Caqui", "#F0E68C"), + ("Caramelo", "#8B5742"), + ("Cardo", "#D8BFD8"), + ("Carmesim", "#DC143C"), + ("Carmim carnáceo", "#960018"), + ("Carmim clássico", "#992244"), + ("Carmim", "#712F26"), + ("Castanho avermelhado", "#8B0000"), + ("Castanho claro", "#D2B48C"), + ("Cenoura", "#ED9121"), + ("Cereja Hollywood", "#F400A1"), + ("Cereja", "#DE3163"), + ("Chocolate", "#D2691E"), + ("Ciano claro", "#E0FFFF"), + ("Ciano escuro", "#008B8B"), + ("Ciano", "#00FFFF"), + ("Cinza ardósia claro", "#778899"), + ("Cinza ardósia escuro", "#2F4F4F"), + ("Cinza ardósia", "#708090"), + ("Cinza claro", "#D3D3D3"), + ("Cinza escuro", "#A9A9A9"), + ("Cinza fosco", "#696969"), + ("Cinza médio", "#DCDCDC"), + ("Cinza", "#808080"), + ("Cobre", "#B87333"), + ("Concha", "#FFF5EE"), + ("Coral claro", "#F08080"), + ("Coral", "#FF7F50"), + ("Couro", "#F0DC82"), + ("Creme de marisco", "#FFE4C4"), + ("Creme de menta", "#F5FFFA"), + ("Creme", "#FFFDD0"), + ("Dourado escuro", "#B8860B"), + ("Dourado pálido", "#EEE8AA"), + ("Dourado", "#DAA520"), + ("Ébano", "#555D50"), + ("Eminência", "#6C3082"), + ("Escarlate", "#FF2400"), + ("Esmeralda", "#50C878"), + ("Eucalipto", "#44D7A8"), + ("Fandango", "#B53389"), + ("Feldspato", "#FDD5B1"), + ("Ferrugem", "#B7410E"), + ("Flerte", "#A2006D"), + ("Fúcsia", "#FF00FF"), + ("Fuligem", "#3D2B1F"), + ("Glicínia", "#C9A0DC"), + ("Glitter", "#E6E8FA"), + ("Grená", "#831D1C"), + ("Heliotrópio", "#DF73FF"), + ("Herbal", "#2E8B57"), + ("Independência", "#4C516D"), + ("Índigo", "#4B0082"), + ("Iris", "#5A4FCF"), + ("Jade", "#00A86B"), + ("Jambo", "#FF4500"), + ("Jasmine", "#F8DE7E"), + ("Kiwi", "#8EE53F"), + ("Laranja claro", "#FFB84D"), + ("Laranja escuro", "#FF8C00"), + ("Laranja", "#FFA500"), + ("Lavanda avermelhada", "#FFF0F5"), + ("Lavanda", "#E6E6FA"), + ("Lilás", "#C8A2C8"), + ("Lima", "#FDE910"), + ("Limão", "#00FF00"), + ("Linho", "#FAF0E6"), + ("Madeira", "#DEB887"), + ("Magenta escuro", "#8B008B"), + ("Magenta", "#FF00FF"), + ("Malva", "#E0B0FF"), + ("Mamão batido", "#FFEFD5"), + ("Maná", "#F0FFF0"), + ("Marfim", "#FFFFF0"), + ("Marrom amarelado", "#F4A460"), + ("Marrom claro", "#A52A2A"), + ("Marrom rosado", "#BC8F8F"), + ("Marrom sela", "#8B4513"), + ("Marrom", "#964b00"), + ("Milho Claro", "#FFF8DC"), + ("Milho", "#FBEC5D"), + ("Mocassim", "#FFE4B5"), + ("Mostarda", "#FFDB58"), + ("Naval", "#000080"), + ("Neve", "#FFFAFA"), + ("Nyanza", "#E9FFDB"), + ("Ocre", "#CC7722"), + ("Oliva escura", "#556B2F"), + ("Oliva parda", "#6B8E23"), + ("Oliva", "#808000"), + ("Orquídea escura", "#9932CC"), + ("Orquídea média", "#BA55D3"), + ("Orquídea", "#DA70D6"), + ("Ouro", "#FFD700"), + ("Pardo escuro", "#CC6600"), + ("Pardo", "#CD853F"), + ("Pêssego", "#FFDAB9"), + ("Prata", "#C0C0C0"), + ("Preto", "#000000"), + ("Púrpura média", "#9370DB"), + ("Púrpura", "#800080"), + ("Quantum", "#111111"), + ("Quartzo", "#51484F"), + ("Renda antiga", "#FDF5E6"), + ("Rosa amoroso", "#CD69CD"), + ("Rosa brilhante", "#FF007F"), + ("Rosa Choque", "#FC0FC0"), + ("Rosa claro", "#FFB6C1"), + ("Rosa danação", "#DA69A1"), + ("Rosa embaçado", "#FFE4E1"), + ("Rosa forte", "#FF69B4"), + ("Rosa profundo", "#FF1493"), + ("Rosa", "#FFCBDB"), + ("Roxo brasilis", "#8A008A"), + ("Roxo", "#993399"), + ("Rútilo", "#6D351A"), + ("Salmão claro", "#FFA07A"), + ("Salmão escuro", "#E9967A"), + ("Salmão", "#FA7F72"), + ("Sépia", "#705714"), + ("Siena", "#FF8247"), + ("Tangerina", "#F28500"), + ("Terracota", "#E2725B"), + ("Tijolo refratário", "#B22222"), + ("Tomate", "#FF6347"), + ("Triássico", "#FF2401"), + ("Trigo", "#F5DEB3"), + ("Turquesa escura", "#00CED1"), + ("Turquesa média", "#48D1CC"), + ("Turquesa pálida", "#AFEEEE"), + ("Turquesa", "#40E0D0"), + ("Urucum", "#EC2300"), + ("Verde amarelado", "#9ACD32"), + ("Verde claro", "#90EE90"), + ("Verde escuro", "#006400"), + ("Verde espectro", "#00FF00"), + ("Verde floresta", "#228B22"), + ("Verde fluorescente", "#CCFF33"), + ("Verde grama", "#7CFC00"), + ("Verde lima", "#32CD32"), + ("Verde mar claro", "#20B2AA"), + ("Verde mar escuro", "#8FBC8F"), + ("Verde mar médio", "#3CB371"), + ("Verde militar", "#78866B"), + ("Verde pálido", "#98FB98"), + ("Verde Paris", "#7FFF00"), + ("Verde primavera médio", "#00FA9A"), + ("Verde primavera", "#00FF7F"), + ("Verde-azulado", "#008080"), + ("Verde", "#008000"), + ("Vermelho enegrecido", "#550000"), + ("Vermelho escuro", "#8B0000"), + ("Vermelho indiano", "#CD5C5C"), + ("Vermelho violeta médio", "#C71585"), + ("Vermelho violeta pálido", "#DB7093"), + ("Vermelho violeta", "#D02090"), + ("Vermelho", "#FF0000"), + ("Violeta claro", "#F8CBF8"), + ("Violeta escuro", "#9400D3"), + ("Violeta", "#EE82EE"), + ("Zinco", "#E2DDF0"), + )) + + safe_colors = ( + 'preto', 'marrom', 'verde', 'azul escuro', 'verde escuro', + 'roxo', 'laranja', 'verde claro', 'azul', 'rosa', 'violeta', + 'cinza', 'amarelo', 'magenta', 'ciano', 'branco', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/color/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd32944c5beaa72ed7019ac48b26d916b80ff0c4 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/ru_RU/__init__.py @@ -0,0 +1,72 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + +localized = True + + +class Provider(ColorProvider): + all_colors = OrderedDict(( + ("Античный Белый", "#FAEBD7"), + ("Аквамарин", "#7FFFD4"), + ("Лазурный", "#F0FFFF"), + ("Бежевый", "#F5F5DC"), + ("Черный", "#000000"), + ("Синий", "#0000FF"), + ("Сине-фиолетовый", "#8A2BE2"), + ("Коричневый", "#A52A2A"), + ("Шоколадный", "#D2691E"), + ("Коралловый", "#FF7F50"), + ("Васильковый", "#6495ED"), + ("Малиновый", "#DC143C"), + ("Темно-синий", "#00008B"), + ("Темно-голубой", "#008B8B"), + ("Темно-серый", "#A9A9A9"), + ("Темно-зеленый", "#006400"), + ("Темный хаки", "#BDB76B"), + ("Темно-оранжевый", "#FF8C00"), + ("Темно-красный", "#8B0000"), + ("Темно-бирюзовый", "#00CED1"), + ("Темно-фиолетовый", "#9400D3"), + ("Темно-розовый", "#FF1493"), + ("Тусклый серый", "#696969"), + ("Фуксия", "#FF00FF"), + ("Золотой", "#FFD700"), + ("Серый", "#808080"), + ("Зеленый", "#008000"), + ("Желто-зеленый", "#ADFF2F"), + ("Ярко-розовый", "#FF69B4"), + ("Индиго", "#4B0082"), + ("Слоновая кость", "#FFFFF0"), + ("Хаки", "#F0E68C"), + ("Розовато-лавандовый", "#FFF0F5"), + ("Светло-синий", "#ADD8E6"), + ("Светло-голубой", "#E0FFFF"), + ("Светло-серый", "#D3D3D3"), + ("Светло-зеленый", "#90EE90"), + ("Светло-розовый", "#FFB6C1"), + ("Светло-голубой", "#87CEFA"), + ("Светло-желтый", "#FFFFE0"), + ("Каштановый", "#800000"), + ("Оранжевый", "#FFA500"), + ("Оранжево-красный", "#FF4500"), + ("Бледно-зеленый", "#98FB98"), + ("Бледно-Бирюзовый", "#AFEEEE"), + ("Розовый", "#FFC0CB"), + ("Сливовый", "#DDA0DD"), + ("Пурпурный", "#800080"), + ("Красный", "#FF0000"), + ("Цвет морской волны", "#2E8B57"), + ("Серебряный", "#C0C0C0"), + ("Бирюзовый", "#40E0D0"), + ("Фиолетовый", "#EE82EE"), + ("Белый", "#FFFFFF"), + ("Желтый", "#FFFF00"), + ("Желто-зеленый", "#9ACD32"), + )) + + safe_colors = ( + 'черный', 'бордовый', 'зеленый', 'оливковый', + 'пурпурный', 'teal', 'lime', 'синий', 'серебряный', + 'серый', 'желтый', 'фуксия', 'белый', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/th_TH/__init__.py b/testbed/joke2k__faker/faker/providers/color/th_TH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa82289d9707047fda4ff0f0aa832ef9e70c78f5 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/th_TH/__init__.py @@ -0,0 +1,38 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + +localized = True + + +# Reference +# https://th.wikipedia.org/wiki/รายชื่อสี +# on 2019-10-20 +class Provider(ColorProvider): + all_colors = OrderedDict(( + ('สีดำ', '#000000'), + ('สีน้ำเงินเขียว', '#0095B6'), + ('สีน้ำเงินม่วง', '#8A2BE2'), + ('สีทองแดง', '#CD7F32'), + ('สีน้ำตาล', '#964B00'), + ('สีกาแฟ', '#6F4E37'), + ('สีทอง', '#FFD700'), + ('สีเทา', '#808080'), + ('สีเขียว', '#00FF00'), + ('สีหยก', '#00A86B'), + ('สีส้ม', '#FFA500'), + ('สีส้มแดง', '#FF4500'), + ('สีออร์คิด', '#DA70D6'), + ('สีชมพู', '#FFC0CB'), + ('สีม่วง', '#800080'), + ('สีแดง', '#FF0000'), + ('สีเงิน', '#C0C0C0'), + ('สีขาว', '#FFFFFF'), + ('สีเหลือง', '#FFFF00'), + )) + + safe_colors = ( + 'สีดำ', 'สีน้ำตาล', 'สีทอง', 'สีเขียว', + 'สีส้ม', 'สีชมพู', 'สีม่วง', 'สีเงิน', 'สีแดง', + 'สีเงิน', 'สีขาว', 'สีเหลือง', + ) diff --git a/testbed/joke2k__faker/faker/providers/color/uk_UA/__init__.py b/testbed/joke2k__faker/faker/providers/color/uk_UA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d90262eed78f67e1136f534e410c730709d4e02 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/color/uk_UA/__init__.py @@ -0,0 +1,215 @@ +from collections import OrderedDict + +from .. import Provider as ColorProvider + + +class Provider(ColorProvider): + # Source: uk.wikipedia.org/wiki/Список_кольорів + all_colors = OrderedDict(( + ('Абрикосовий', '#FBCEB1'), + ('Аквамариновий', '#7FFFD4'), + ('Алізариновий червоний', '#E32636'), + ('Амарантовий', '#E52B50'), + ('Амарантово-рожевий', '#F19CBB'), + ('Аметистовий', '#9966CC'), + ('Андроїдний зелений', '#A4C639'), + ('Арсеновий', '#3B444B'), + ('Атомний мандаріновий', '#FF9966'), + ('Багряний', '#FF2400'), + ('Баклажановий', '#990066'), + ('Барвінковий', '#CCCCFF'), + ('Бежевий', '#F5F5DC'), + ('Берлінська лазур', '#003153'), + ('Блаватний', '#6495ED'), + ('Блакитний', '#AFEEEE'), + ('Блакитний Брандейса', '#0070FF'), + ('Блакитно-зелений', '#00DDDD'), + ('Блакитно-фіолетовий', '#8A2BE2'), + ('Блідий рожево-ліловий', '#996666'), + ('Блідо-брунатний', '#987654'), + ('Блідо-волошковий', '#ABCDEF'), + ('Блідо-карміновий', '#AF4035'), + ('Блідо-каштановий', '#DDADAF'), + ('Блідо-пурпуровий', '#F984E5'), + ('Блідо-пісочний', '#DABDAB'), + ('Блідо-рожевий', '#FADADD'), + ('Болотний', '#ACB78E'), + ('Бронзовий', '#CD7F32'), + ('Брунатний', '#964B00'), + ('Брунато-малиновий', '#800000'), + ('Будяковий', '#D8BFD8'), + ('Бузковий', '#C8A2C8'), + ('Бургундський', '#900020'), + ('Бурий', '#755A57'), + ('Бурштиновий', '#FFBF00'), + ('Білий', '#FFFFFF'), + ('Білий навахо', '#FFDEAD'), + ('Бірюзовий', '#30D5C8'), + ('Бістр', '#3D2B1F'), + ('Вода пляжа Бонді', '#0095B6'), + ('Вохра', '#CC7722'), + ('Відбірний жовтий', '#FFBA00'), + ('Візантійський', '#702963'), + ('Гарбуз', '#FF7518'), + ('Гарячо-рожевий', '#FC0FC0'), + ('Геліотроп', '#DF73FF'), + ('Глибокий фіолетовий', '#423189'), + ('Глицінія', '#C9A0DC'), + ('Грушевий', '#D1E231'), + ('Гумігут', '#E49B0F'), + ('Гірчичний', '#FFDB58'), + ('Дерева', '#79443B'), + ('Джинсовий', '#1560BD'), + ('Діамантово-рожевий', '#FF55A3'), + ('Жовтий', '#FFFF00'), + ('Жовто-зелений', '#ADFF2F'), + ('Жовто-персиковий', '#FADFAD'), + ('Захисний синій', '#1E90FF'), + ('Зелена весна', '#00FF7F'), + ('Зелена мʼята', '#98FF98'), + ('Зелена сосна', '#01796F'), + ('Зелене море', '#2E8B57'), + ('Зелений', '#00FF00'), + ('Зелений армійський', '#4B5320'), + ('Зелений мох', '#ADDFAD'), + ('Зелений папороть', '#4F7942'), + ('Зелений чай', '#D0F0C0'), + ('Зелено-сірий чай', '#CADABA'), + ('Зеленувато-блакитний', '#008080'), + ('Золотаво-березовий', '#DAA520'), + ('Золотий', '#FFD700'), + ('Золотисто-каштановий', '#6D351A'), + ('Індиго', '#4B0082'), + ('Іржавий', '#B7410E'), + ('Кардинал (колір)', '#C41E3A'), + ('Карміновий', '#960018'), + ('Каштановий', '#CD5C5C'), + ('Кобальтовий', '#0047AB'), + ('Колір жовтого шкільного автобуса', '#FFD800'), + ('Колір засмаги', '#D2B48C'), + ('Колір морської піни', '#FFF5EE'), + ('Колір морської хвилі', '#00FFFF'), + ('Кораловий', '#FF7F50'), + ('Королівський синій', '#4169E1'), + ('Кремовий', '#FFFDD0'), + ('Кукурудзяний', '#FBEC5D'), + ('Кіновар', '#FF4D00'), + ('Лавандний', '#E6E6FA'), + ('Лазуровий', '#007BA7'), + ('Лазурово-синій', '#2A52BE'), + ('Лайм', '#CCFF00'), + ('Латунний', '#B5A642'), + ('Лимонний', '#FDE910'), + ('Лимонно-кремовий', '#FFFACD'), + ('Лляний', '#EEDC82'), + ('Лляний', '#FAF0E6'), + ('Лососевий', '#FF8C69'), + ('Ліловий', '#DB7093'), + ('Малахітовий', '#0BDA51'), + ('Малиновий', '#DC143C'), + ('Мандариновий', '#FFCC00'), + ('Мисливський', '#004225'), + ('Морквяний', '#ED9121'), + ('Мідний', '#B87333'), + ('Міжнародний помаранчевий', '#FF4F00'), + ('Нефритовий', '#00A86B'), + ('Ніжно-блакитний', '#E0FFFF'), + ('Ніжно-оливковий', '#6B8E23'), + ('Ніжно-рожевий', '#FB607F'), + ('Оливковий', '#808000'), + ('Опівнічно-синій', '#003366'), + ('Орхідея', '#DA70D6'), + ('Палена сіена', '#E97451'), + ('Палений оранжевий', '#CC5500'), + ('Панг', '#C7FCEC'), + ('Паросток папаї', '#FFEFD5'), + ('Пастельно-зелений', '#77DD77'), + ('Пастельно-рожевий', '#FFD1DC'), + ('Персиковий', '#FFE5B4'), + ('Перський синій', '#6600FF'), + ('Помаранчевий', '#FFA500'), + ('Помаранчево-персиковий', '#FFCC99'), + ('Помаранчево-рожевий', '#FF9966'), + ('Пурпурний', '#FF00FF'), + ('Пурпуровий', '#660099'), + ('Пшеничний', '#F5DEB3'), + ('Пісочний колір', '#F4A460'), + ('Рожевий', '#FFC0CB'), + ('Рожевий Маунтбеттена', '#997A8D'), + ('Рожево-лавандний', '#FFF0F5'), + ('Рожево-ліловий', '#993366'), + ('Салатовий', '#7FFF00'), + ('Сангрія', '#92000A'), + ('Сапфіровий', '#082567'), + ('Світло-синій', '#007DFF'), + ('Сепія', '#704214'), + ('Сиваво-зелений', '#ACE1AF'), + ('Сигнально-помаранчевий', '#FF9900'), + ('Синя пил', '#003399'), + ('Синя сталь', '#4682B4'), + ('Сині яйця малинівки', '#00CCCC'), + ('Синій', '#0000FF'), + ('Синій (RYB)', '#0247FE'), + ('Синій (пігмент)', '#333399'), + ('Синій ВПС', '#5D8AA8'), + ('Синій Клейна', '#3A75C4'), + ('Сливовий', '#660066'), + ('Смарагдовий', '#50C878'), + ('Спаржевий', '#7BA05B'), + ('Срібний', '#C0C0C0'), + ('Старе золото', '#CFB53B'), + ('Сіра спаржа', '#465945'), + ('Сірий', '#808080'), + ('Сірий шифер', '#708090'), + ('Темний весняно-зелений', '#177245'), + ('Темний жовто-брунатний', '#918151'), + ('Темний зелений чай', '#BADBAD'), + ('Темний пастельно-зелений', '#03C03C'), + ('Темний хакі', '#BDB76B'), + ('Темний індиго', '#310062'), + ('Темно-аспідний сірий', '#2F4F4F'), + ('Темно-брунатний', '#654321'), + ('Темно-бірюзовий', '#116062'), + ('Темно-зелений', '#013220'), + ('Темно-зелений хакі', '#78866B'), + ('Темно-золотий', '#B8860B'), + ('Темно-карміновий', '#560319'), + ('Темно-каштановий', '#986960'), + ('Темно-кораловий', '#CD5B45'), + ('Темно-лазурний', '#08457E'), + ('Темно-лососевий', '#E9967A'), + ('Темно-мандариновий', '#FFA812'), + ('Темно-оливковий', '#556832'), + ('Темно-персиковий', '#FFDAB9'), + ('Темно-рожевий', '#E75480'), + ('Темно-синій', '#000080'), + ('Ультрамариновий', '#120A8F'), + ('Умбра', '#734A12'), + ('Умбра палена', '#8A3324'), + ('Фуксія', '#FF00FF'), + ('Фіолетовий', '#8B00FF'), + ('Фіолетово-баклажановий', '#991199'), + ('Фіолетово-червоний', '#C71585'), + ('Хакі', '#C3B091'), + ('Цинамоновий', '#7B3F00'), + ('Циннвальдит', '#EBC2AF'), + ('Ціан (колір)', '#00FFFF'), + ('Ціано-блакитний', '#F0F8FF'), + ('Червоний', '#FF0000'), + ('Червоно-буро-помаранчевий', '#CD5700'), + ('Червоновато-брунатний', '#CC8899'), + ('Чорний', '#000000'), + ('Шафрановий', '#F4C430'), + ('Шкіра буйвола', '#F0DC82'), + ('Шоколадний', '#D2691E'), + ('Яскраво-бурштиновий', '#FF7E00'), + ('Яскраво-бірюзовий', '#08E8DE'), + ('Яскраво-зелений', '#66FF00'), + ('Яскраво-зелений', '#40826D'), + ('Яскраво-рожевий', '#FF007F'), + ('Яскраво-фіолетовий', '#CD00CD'), + ('Ясно-брунатний', '#CD853F'), + ('Ясно-вишневий', '#DE3163'), + ('Ясно-лазуровий', '#007FFF'), + ('Ясно-лазуровий (веб)', '#F0FFFF'), + )) diff --git a/testbed/joke2k__faker/faker/providers/company/__init__.py b/testbed/joke2k__faker/faker/providers/company/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d539990b56672ab032abdc244747344f6ca0fdd --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/__init__.py @@ -0,0 +1,524 @@ +from .. import BaseProvider + +localized = True + + +class Provider(BaseProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}}-{{last_name}}', + '{{last_name}}, {{last_name}} and {{last_name}}', + ) + + company_suffixes = ('Inc', 'and Sons', 'LLC', 'Group', 'PLC', 'Ltd') + + catch_phrase_words = ( + ('Adaptive', + 'Advanced', + 'Ameliorated', + 'Assimilated', + 'Automated', + 'Balanced', + 'Business-focused', + 'Centralized', + 'Cloned', + 'Compatible', + 'Configurable', + 'Cross-group', + 'Cross-platform', + 'Customer-focused', + 'Customizable', + 'Decentralized', + 'De-engineered', + 'Devolved', + 'Digitized', + 'Distributed', + 'Diverse', + 'Down-sized', + 'Enhanced', + 'Enterprise-wide', + 'Ergonomic', + 'Exclusive', + 'Expanded', + 'Extended', + 'Face-to-face', + 'Focused', + 'Front-line', + 'Fully-configurable', + 'Function-based', + 'Fundamental', + 'Future-proofed', + 'Grass-roots', + 'Horizontal', + 'Implemented', + 'Innovative', + 'Integrated', + 'Intuitive', + 'Inverse', + 'Managed', + 'Mandatory', + 'Monitored', + 'Multi-channeled', + 'Multi-lateral', + 'Multi-layered', + 'Multi-tiered', + 'Networked', + 'Object-based', + 'Open-architected', + 'Open-source', + 'Operative', + 'Optimized', + 'Optional', + 'Organic', + 'Organized', + 'Persevering', + 'Persistent', + 'Phased', + 'Polarized', + 'Pre-emptive', + 'Proactive', + 'Profit-focused', + 'Profound', + 'Programmable', + 'Progressive', + 'Public-key', + 'Quality-focused', + 'Reactive', + 'Realigned', + 'Re-contextualized', + 'Re-engineered', + 'Reduced', + 'Reverse-engineered', + 'Right-sized', + 'Robust', + 'Seamless', + 'Secured', + 'Self-enabling', + 'Sharable', + 'Stand-alone', + 'Streamlined', + 'Switchable', + 'Synchronized', + 'Synergistic', + 'Synergized', + 'Team-oriented', + 'Total', + 'Triple-buffered', + 'Universal', + 'Up-sized', + 'Upgradable', + 'User-centric', + 'User-friendly', + 'Versatile', + 'Virtual', + 'Visionary', + 'Vision-oriented'), + ('24hour', + '24/7', + '3rdgeneration', + '4thgeneration', + '5thgeneration', + '6thgeneration', + 'actuating', + 'analyzing', + 'asymmetric', + 'asynchronous', + 'attitude-oriented', + 'background', + 'bandwidth-monitored', + 'bi-directional', + 'bifurcated', + 'bottom-line', + 'clear-thinking', + 'client-driven', + 'client-server', + 'coherent', + 'cohesive', + 'composite', + 'context-sensitive', + 'contextually-based', + 'content-based', + 'dedicated', + 'demand-driven', + 'didactic', + 'directional', + 'discrete', + 'disintermediate', + 'dynamic', + 'eco-centric', + 'empowering', + 'encompassing', + 'even-keeled', + 'executive', + 'explicit', + 'exuding', + 'fault-tolerant', + 'foreground', + 'fresh-thinking', + 'full-range', + 'global', + 'grid-enabled', + 'heuristic', + 'high-level', + 'holistic', + 'homogeneous', + 'human-resource', + 'hybrid', + 'impactful', + 'incremental', + 'intangible', + 'interactive', + 'intermediate', + 'leadingedge', + 'local', + 'logistical', + 'maximized', + 'methodical', + 'mission-critical', + 'mobile', + 'modular', + 'motivating', + 'multimedia', + 'multi-state', + 'multi-tasking', + 'national', + 'needs-based', + 'neutral', + 'next generation', + 'non-volatile', + 'object-oriented', + 'optimal', + 'optimizing', + 'radical', + 'real-time', + 'reciprocal', + 'regional', + 'responsive', + 'scalable', + 'secondary', + 'solution-oriented', + 'stable', + 'static', + 'systematic', + 'systemic', + 'system-worthy', + 'tangible', + 'tertiary', + 'transitional', + 'uniform', + 'upward-trending', + 'user-facing', + 'value-added', + 'web-enabled', + 'well-modulated', + 'zero administration', + 'zero-defect', + 'zero tolerance'), + ('ability', + 'access', + 'adapter', + 'algorithm', + 'alliance', + 'analyzer', + 'application', + 'approach', + 'architecture', + 'archive', + 'artificial intelligence', + 'array', + 'attitude', + 'benchmark', + 'budgetary management', + 'capability', + 'capacity', + 'challenge', + 'circuit', + 'collaboration', + 'complexity', + 'concept', + 'conglomeration', + 'contingency', + 'core', + 'customer loyalty', + 'database', + 'data-warehouse', + 'definition', + 'emulation', + 'encoding', + 'encryption', + 'extranet', + 'firmware', + 'flexibility', + 'focus group', + 'forecast', + 'frame', + 'framework', + 'function', + 'functionalities', + 'Graphic Interface', + 'groupware', + 'Graphical User Interface', + 'hardware', + 'help-desk', + 'hierarchy', + 'hub', + 'implementation', + 'info-mediaries', + 'infrastructure', + 'initiative', + 'installation', + 'instruction set', + 'interface', + 'Internet solution', + 'intranet', + 'knowledge user', + 'knowledgebase', + 'Local Area Network', + 'leverage', + 'matrices', + 'matrix', + 'methodology', + 'middleware', + 'migration', + 'model', + 'moderator', + 'monitoring', + 'moratorium', + 'neural-net', + 'open architecture', + 'open system', + 'orchestration', + 'paradigm', + 'parallelism', + 'policy', + 'portal', + 'pricing structure', + 'process improvement', + 'product', + 'productivity', + 'project', + 'projection', + 'protocol', + 'secured line', + 'service-desk', + 'software', + 'solution', + 'standardization', + 'strategy', + 'structure', + 'success', + 'superstructure', + 'support', + 'synergy', + 'system engine', + 'task-force', + 'throughput', + 'time-frame', + 'toolset', + 'utilization', + 'website', + 'workforce')) + + bsWords = ( + ('implement', + 'utilize', + 'integrate', + 'streamline', + 'optimize', + 'evolve', + 'transform', + 'embrace', + 'enable', + 'orchestrate', + 'leverage', + 'reinvent', + 'aggregate', + 'architect', + 'enhance', + 'incentivize', + 'morph', + 'empower', + 'envisioneer', + 'monetize', + 'harness', + 'facilitate', + 'seize', + 'disintermediate', + 'synergize', + 'strategize', + 'deploy', + 'brand', + 'grow', + 'target', + 'syndicate', + 'synthesize', + 'deliver', + 'mesh', + 'incubate', + 'engage', + 'maximize', + 'benchmark', + 'expedite', + 're-intermediate', + 'whiteboard', + 'visualize', + 'repurpose', + 'innovate', + 'scale', + 'unleash', + 'drive', + 'extend', + 'engineer', + 'revolutionize', + 'generate', + 'exploit', + 'transition', + 'e-enable', + 'iterate', + 'cultivate', + 'matrix', + 'productize', + 'redefine', + 're-contextualize'), + ('clicks-and-mortar', + 'value-added', + 'vertical', + 'proactive', + 'robust', + 'revolutionary', + 'scalable', + 'leading-edge', + 'innovative', + 'intuitive', + 'strategic', + 'e-business', + 'mission-critical', + 'sticky', + 'one-to-one', + '24/7', + 'end-to-end', + 'global', + 'B2B', + 'B2C', + 'granular', + 'frictionless', + 'virtual', + 'viral', + 'dynamic', + '24/365', + 'best-of-breed', + 'killer', + 'magnetic', + 'bleeding-edge', + 'web-enabled', + 'interactive', + 'dot-com', + 'sexy', + 'back-end', + 'real-time', + 'efficient', + 'front-end', + 'distributed', + 'seamless', + 'extensible', + 'turn-key', + 'world-class', + 'open-source', + 'cross-platform', + 'cross-media', + 'synergistic', + 'bricks-and-clicks', + 'out-of-the-box', + 'enterprise', + 'integrated', + 'impactful', + 'wireless', + 'transparent', + 'next-generation', + 'cutting-edge', + 'user-centric', + 'visionary', + 'customized', + 'ubiquitous', + 'plug-and-play', + 'collaborative', + 'compelling', + 'holistic', + 'rich'), + ('synergies', + 'web-readiness', + 'paradigms', + 'markets', + 'partnerships', + 'infrastructures', + 'platforms', + 'initiatives', + 'channels', + 'eyeballs', + 'communities', + 'ROI', + 'solutions', + 'e-tailers', + 'e-services', + 'action-items', + 'portals', + 'niches', + 'technologies', + 'content', + 'vortals', + 'supply-chains', + 'convergence', + 'relationships', + 'architectures', + 'interfaces', + 'e-markets', + 'e-commerce', + 'systems', + 'bandwidth', + 'info-mediaries', + 'models', + 'mindshare', + 'deliverables', + 'users', + 'schemas', + 'networks', + 'applications', + 'metrics', + 'e-business', + 'functionalities', + 'experiences', + 'web services', + 'methodologies')) + + def company(self): + """ + :example 'Acme Ltd' + """ + pattern = self.random_element(self.formats) + return self.generator.parse(pattern) + + def company_suffix(self): + """ + :example 'Ltd' + """ + return self.random_element(self.company_suffixes) + + def catch_phrase(self): + """ + :example 'Robust full-range hub' + """ + result = [] + for word_list in self.catch_phrase_words: + result.append(self.random_element(word_list)) + + return " ".join(result) + + def bs(self): + """ + :example 'integrate extensible convergence' + """ + result = [] + for word_list in self.bsWords: + result.append(self.random_element(word_list)) + + return " ".join(result) diff --git a/testbed/joke2k__faker/faker/providers/company/bg_BG/__init__.py b/testbed/joke2k__faker/faker/providers/company/bg_BG/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b584714a8c8a41488251560b5994cb2586ba8fe0 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/bg_BG/__init__.py @@ -0,0 +1,21 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + ) + + company_suffixes = ( + 'АД', 'AD', + 'ADSITz', 'АДСИЦ', + 'EAD', 'ЕАД', + 'EOOD', 'ЕООД', + 'ET', 'ET', + 'OOD', 'ООД', + 'KD', 'КД', + 'KDA', 'КДА', + 'SD', 'СД', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/cs_CZ/__init__.py b/testbed/joke2k__faker/faker/providers/company/cs_CZ/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7eb83fe5497f27ed52d3757f28fda1a97e4996 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/cs_CZ/__init__.py @@ -0,0 +1,13 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + ) + + company_suffixes = ( + 's.r.o.', 'o.s.', 'a.s.', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/de_DE/__init__.py b/testbed/joke2k__faker/faker/providers/company/de_DE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9cdb27054571777ed4bd52f72bd00feeebc07592 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/de_DE/__init__.py @@ -0,0 +1,17 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + ) + + company_suffixes = ( + 'AG', 'AG', 'AG', 'AG', 'AG & Co. KG', 'AG & Co. KGaA', 'AG & Co. OHG', + 'GbR', 'GbR', 'GmbH', 'GmbH', 'GmbH', 'GmbH', 'GmbH & Co. KG', + 'GmbH & Co. KG', 'GmbH & Co. KGaA', 'GmbH & Co. OHG', 'KG', 'KG', 'KG', + 'KGaA', 'OHG mbH', 'Stiftung & Co. KG', 'Stiftung & Co. KGaA', 'e.G.', + 'e.V.', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/en_PH/__init__.py b/testbed/joke2k__faker/faker/providers/company/en_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b528ca31af094d8b98f99229b15803503a77fdee --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/en_PH/__init__.py @@ -0,0 +1,131 @@ +from collections import OrderedDict + +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + """ + Provider for company names for en_PH locale + + Company naming scheme and probabilities are inspired by and/or based on existing companies in the Philippines. + + Sources: + - https://en.wikipedia.org/wiki/List_of_companies_of_the_Philippines + - https://www.pse.com.ph/stockMarket/listedCompanyDirectory.html + """ + + formats = OrderedDict([ + ('{{random_company_adjective}} {{random_company_noun_chain}} {{company_type}} {{company_suffix}}', 0.24), + ('{{random_company_acronym}} {{random_company_noun_chain}} {{company_type}} {{company_suffix}}', 0.24), + ('{{last_name}} {{random_company_noun_chain}} {{company_type}} {{company_suffix}}', 0.16), + ('{{random_company_adjective}} {{company_type}} {{company_suffix}}', 0.12), + ('{{random_company_acronym}} {{company_type}} {{company_suffix}}', 0.12), + ('{{last_name}} {{company_type}} {{company_suffix}}', 0.09), + ('National {{random_company_product}} Corporation of the Philippines', 0.03), + ]) + company_suffixes = OrderedDict([ + ('Inc.', 0.45), + ('Corporation', 0.45), + ('Limited', 0.1), + ]) + company_types = ( + 'Bank', + 'Banking', + 'Capital', + 'Company', + 'Construction', + 'Development', + 'Enterprise', + 'Equities', + 'Finance', + 'Foods', + 'Group', + 'Holdings', + 'Hotel', + 'Manufacturing', + 'Mining', + 'Properties', + 'Resorts', + 'Resources', + 'Services', + 'Shipping', + 'Solutions', + 'Technologies', + 'Trust', + 'Ventures', + ) + company_products = ( + 'Bottle', + 'Coconut', + 'Computer', + 'Electricity', + 'Flour', + 'Furniture', + 'Glass', + 'Newspaper', + 'Pillow', + 'Water', + ) + company_nouns = ( + 'Century', + 'City', + 'Crown', + 'Dragon', + 'Empire', + 'Genesis', + 'Gold', + 'King', + 'Liberty', + 'Millennium', + 'Morning', + 'Silver', + 'Star', + 'State', + 'Summit', + 'Sun', + 'Union', + 'World', + ) + company_adjectives = ( + 'Advanced', + 'Rising', + 'Double', + 'Triple', + 'Quad', + 'Allied', + 'Cyber', + 'Sovereign', + 'Great', + 'Far', + 'Northern', + 'Southern', + 'Eastern', + 'Western', + 'First', + 'Filipino', + 'Grand', + 'Manila', + 'Mega', + 'Metro', + 'Global', + 'Pacific', + 'Oriental', + 'Philippine', + 'Prime', + ) + + def company_type(self): + return self.random_element(self.company_types) + + def random_company_adjective(self): + return self.random_element(self.company_adjectives) + + def random_company_noun_chain(self): + return ' '.join(self.random_elements(self.company_nouns, length=self.random_int(1, 2), unique=True)) + + def random_company_product(self): + return self.random_element(self.company_products) + + def random_company_acronym(self): + letters = self.random_letters(self.random_int(2, 4)) + return ''.join(letters).upper() diff --git a/testbed/joke2k__faker/faker/providers/company/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/company/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..995221b71078555f43c879a1add3de9d5ce84eae --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/en_US/__init__.py @@ -0,0 +1,5 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + pass diff --git a/testbed/joke2k__faker/faker/providers/company/es_MX/__init__.py b/testbed/joke2k__faker/faker/providers/company/es_MX/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a260be1b77717b2cef1e99074d0e4b270f0fd01e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/es_MX/__init__.py @@ -0,0 +1,168 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}}-{{last_name}}', + '{{company_prefix}} {{last_name}}-{{last_name}}', + '{{company_prefix}} {{last_name}} y {{last_name}}', + '{{company_prefix}} {{last_name}}, {{last_name}} y {{last_name}}', + '{{last_name}}-{{last_name}} {{company_suffix}}', + '{{last_name}}, {{last_name}} y {{last_name}}', + '{{last_name}} y {{last_name}} {{company_suffix}}', + ) + + catch_phrase_words = ( + ( + "habilidad", "acceso", "adaptador", "algoritmo", "alianza", + "analista", "aplicación", "enfoque", "arquitectura", + "archivo", "inteligencia artificial", "array", "actitud", + "medición", "gestión presupuestaria", "capacidad", "desafío", + "circuito", "colaboración", "complejidad", "concepto", + "conglomeración", "contingencia", "núcleo", "fidelidad", + "base de datos", "data-warehouse", "definición", "emulación", + "codificar", "encriptar", "extranet", "firmware", + "flexibilidad", "focus group", "previsión", "base de trabajo", + "función", "funcionalidad", "interfaz gráfica", "groupware", + "interfaz gráfico de usuario", "hardware", "soporte", "jerarquía", + "conjunto", "implementación", "infraestructura", "iniciativa", + "instalación", "conjunto de instrucciones", "interfaz", + "intranet", "base del conocimiento", "red de area local", + "aprovechar", "matrices", "metodologías", "middleware", + "migración", "modelo", "moderador", "monitorizar", + "arquitectura abierta", "sistema abierto", "orquestar", + "paradigma", "paralelismo", "política", "portal", + "estructura de precios", "proceso de mejora", + "producto", "productividad", "proyecto", "proyección", + "protocolo", "línea segura", "software", "solución", + "estandarización", "estrategia", "estructura", "éxito", + "superestructura", "soporte", "sinergia", "mediante", + "marco de tiempo", "caja de herramientas", "utilización", + "website", "fuerza de trabajo"), + ( + "24 horas", "24/7", "3ra generación", "4ta generación", + "5ta generación", "6ta generación", "analizada", + "asimétrica", "asíncrona", "monitorizada por red", + "bidireccional", "bifurcada", "generada por el cliente", + "cliente-servidor", "coherente", "cohesiva", "compuesto", + "sensible al contexto", "basado en el contexto", + "basado en contenido", "dedicada", + "generado por la demanda", "didáctica", "direccional", + "discreta", "dinámica", "potenciada", "acompasada", + "ejecutiva", "explícita", "tolerante a fallos", + "innovadora", "amplio abanico", "global", "heurística", + "alto nivel", "holística", "homogénea", "híbrida", + "incremental", "intangible", "interactiva", "intermedia", + "local", "logística", "maximizada", "metódica", + "misión crítica", "móvil", "modular", "motivadora", + "multimedia", "multiestado", "multitarea", "nacional", + "basado en necesidades", "neutral", "nueva generación", + "no-volátil", "orientado a objetos", "óptima", "optimizada", + "radical", "tiempo real", "recíproca", "regional", + "escalable", "secundaria", "orientada a soluciones", + "estable", "estática", "sistemática", "sistémica", + "tangible", "terciaria", "transicional", "uniforme", + "valor añadido", "vía web", "defectos cero", "tolerancia cero", + ), + ( + 'adaptativo', 'avanzado', 'asimilado', 'automatizado', + 'balanceado', 'enfocado al negocio', + 'centralizado', 'clonado', 'compatible', 'configurable', + 'multiplataforma', 'enfocado al cliente', 'personalizable', + 'descentralizado', 'digitalizado', 'distribuido', 'diverso', + 'mejorado', 'en toda la empresa', 'ergonómico', 'exclusivo', + 'expandido', 'extendido', 'cara a cara', 'enfocado', + 'de primera línea', 'totalmente configurable', + 'basado en funcionalidad', 'fundamental', 'horizontal', + 'implementado', 'innovador', 'integrado', 'intuitivo', + 'inverso', 'administrado', 'mandatorio', 'monitoreado', + 'multicanal', 'multilateral', 'multi-capas', 'en red', + 'basado en objetos', 'de arquitectura abierta', + 'open-source', 'operativo', 'optimizado', 'opcional', + 'orgánico', 'organizado', 'perseverante', 'persistente', + 'polarizado', 'preventivo', 'proactivo', 'enfocado a ganancias', + 'programable', 'progresivo', 'llave pública', + 'enfocado a la calidad', 'reactivo', 'realineado', + 'recontextualizado', 'reducido', 'con ingeniería inversa', + 'de tamaño adecuado', 'robusto', 'seguro', 'compartible', + 'sincronizado', 'orientado a equipos', 'total', + 'universal', 'actualizable', 'centrado en el usuario', + 'versátil', 'virtual', 'visionario', + ), + ) + + bsWords = ( + ( + 'implementa', 'utiliza', 'integra', 'optimiza', + 'evoluciona', 'transforma', 'abraza', 'habilita', + 'orquesta', 'reinventa', 'agrega', 'mejora', 'incentiva', + 'modifica', 'empodera', 'monetiza', 'fortalece', + 'facilita', 'sinergiza', 'crea marca', 'crece', + 'sintetiza', 'entrega', 'mezcla', 'incuba', 'compromete', + 'maximiza', 'visualiza', 'innova', + 'escala', 'libera', 'maneja', 'extiende', 'revoluciona', + 'genera', 'explota', 'transiciona', 'itera', 'cultiva', + 'redefine', 'recontextualiza', + ), + ( + 'sinergias', 'paradigmas', 'marcados', 'socios', + 'infraestructuras', 'plataformas', 'iniciativas', + 'canales', 'communidades', 'ROI', 'soluciones', + 'portales', 'nichos', 'tecnologías', 'contenido', + 'cadena de producción', 'convergencia', 'relaciones', + 'arquitecturas', 'interfaces', 'comercio electrónico', + 'sistemas', 'ancho de banda', 'modelos', 'entregables', + 'usuarios', 'esquemas', 'redes', 'aplicaciones', 'métricas', + 'funcionalidades', 'experiencias', 'servicios web', + 'metodologías', + ), + ( + 'valor agregado', 'verticales', 'proactivas', 'robustas', + 'revolucionarias', 'escalables', 'de punta', 'innovadoras', + 'intuitivas', 'estratégicas', 'e-business', 'de misión crítica', + 'uno-a-uno', '24/7', 'end-to-end', 'globales', 'B2B', 'B2C', + 'granulares', 'sin fricciones', 'virtuales', 'virales', + 'dinámicas', '24/365', 'magnéticas', 'listo para la web', + 'interactivas', 'punto-com', 'sexi', 'en tiempo real', + 'eficientes', 'front-end', 'distribuidas', 'extensibles', + 'llave en mano', 'de clase mundial', 'open-source', + 'plataforma cruzada', 'de paquete', 'empresariales', + 'integrado', 'impacto total', 'inalámbrica', 'transparentes', + 'de siguiente generación', 'lo último', 'centrado al usuario', + 'visionarias', 'personalizado', 'ubicuas', 'plug-and-play', + 'colaborativas', 'holísticas', 'ricas', + ), + ) + + company_preffixes = ('Despacho', 'Grupo', 'Corporacin', 'Club', + 'Industrias', 'Laboratorios', 'Proyectos') + + company_suffixes = ('A.C.', 'S.A.', 'S.A. de C.V.', 'S.C.', + 'S. R.L. de C.V.', 'e Hijos', 'y Asociados') + + def company_prefix(self): + """ + Ejemplo: Grupo + """ + return self.random_element(self.company_preffixes) + + def catch_phrase(self): + """ + :example 'Robust full-range hub' + """ + result = [] + for word_list in self.catch_phrase_words: + result.append(self.random_element(word_list)) + + return " ".join(result) + + def bs(self): + """ + :example 'integrate extensible convergence' + """ + result = [] + for word_list in self.bsWords: + result.append(self.random_element(word_list)) + + return " ".join(result) diff --git a/testbed/joke2k__faker/faker/providers/company/fa_IR/__init__.py b/testbed/joke2k__faker/faker/providers/company/fa_IR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..267aedf6056d996f34051a492348078176751112 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/fa_IR/__init__.py @@ -0,0 +1,1114 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + + company_names = [ + 'گروه سیمان', + 'گروه فلزات اساسي', + 'ایران گچ', + 'آلومتك', + 'ساروج بوشهر', + 'آلومينيوم ايران', + 'سيمان  ساوه', + 'ایران ذوب', + 'سيمان اردبيل و آهك آذرشهر', + 'پارس مولیبدن', + 'سيمان اروميه', + 'ذوب روی اصفهان', + 'سيمان اصفهان', + 'صنايع مس شهيد باهنر', + 'سيمان ايلام', + 'صنایع خالص سازان روی زنجان', + 'سيمان بجنورد', + 'صنعتی و سرمایه گذاری سپنتا', + 'سيمان بهبهان', + 'كالسيمين', + 'سيمان تهران', + 'گروه كارخانه هاي توليدي نورد آلومينيوم', + 'سيمان خاش', + 'ملي سرب و روي ايران', + 'سيمان خزر', + 'ملی صنایع مس ایران', + 'سيمان داراب', + 'آلومراد', + 'سيمان دورود', + 'آلومينيوم المهدي', + 'سيمان سفيدني ريز', + 'آلومينيوم پارس', + 'سيمان شاهرود', + 'کارخانجات تولیدی مواد الومینیوم', + 'سيمان شرق', + 'مجتمع ذوب و احیای روی قشم', + 'سيمان شمال', + 'مجتمع صنايع الومينيوم جنوب', + 'سيمان صوفيان', + 'مس تکنار', + 'سيمان غرب', + 'گروه کانی های فلزی', + 'سيمان فارس', + 'آلوميناي ايران', + 'سيمان قاين', + 'تهيه و توليد مواد اوليه فولاد خراسان', + 'سيمان كارون', + 'سنگ آهن مركزي ايران', + 'سيمان كرمان', + 'هرمز انرژی', + 'سيمان مازندران', + 'واحد طلای موته', + 'سيمان هرمزگان', + 'واحد پیربکران', + 'سيمان هگمتان', + 'واحد فسفات اسفردی', + 'سیمان خوزستان', + 'واحد نخلک', + 'سیمان دشتستان', + 'ويتانا', + 'سیمان زابل', + 'گروه صنایع غذایی', + 'سیمان فارس نو', + 'کشاورزی و تحقیقاتی نوین زعفران', + 'سیمان لار سبزوار', + 'گلستان', + 'سیمان لارستان', + 'آرد زر', + 'سیمان لامرد', + 'اروم آدا', + 'سیمان مجد خواف', + 'ایران گلاب مرغوب', + 'سیمان ممتازان کرمان', + 'بيسكوئيت گرجي', + 'فراورده سیمان شرق', + 'تحول چاشنی توس', + 'گچ ماشيني فارس', + 'تهیه و بسته بندی خشکبار آرات', + 'سیمان آذر آبادگان خوی', + 'توسعه کشت ذرت', + 'سیمان بوهروک یزد', + 'تولیدی آرد البرز', + 'سیمان جوین', + 'تولیدی زعفران سحرخیز', + 'سیمان قشم', + 'خوراك دام پارس', + 'سیمان کردستان', + 'دشت مرغاب', + 'گچ تهران', + 'روغن نباتي پارس', + 'گروه فولاد', + 'روغن نباتي جهان', + 'پلی ران اتصال', + 'روغن نباتی گلناز', + 'توليدی لوله هاي پلي اتيلن دوجداره بوشهر', + 'روغنکشی خرمشهر', + 'تولید لوله و پوشش سلفچگان', + 'زر ماکارون', + 'سلفچگان', + 'سالمين', + 'ذوب آهن اصفهان', + 'سپتیکو', + 'ساخته های فلزی اصفهان', + 'سحر همدان', + 'صنايع فرو آلياژ ايران', + 'سقزسازی کردستان', + 'صنايع گالوانيزه فجر سپاهان', + 'شاد گل نیشابور', + 'صنایع فولاد آلياژي يزد', + 'شهد ايران', + 'فولاد اکسین خوزستان', + 'صنایع غذایی مینو شرق', + 'فولاد آلیاژی ایران', + 'صنعتي  پارس مينو', + 'فولاد خوزستان', + 'صنعتي مينو خرم دره', + 'فولاد صنعت مهدی', + 'فراورده های سیب زمینی پریس اصفهان', + 'فولاد مباركه اصفهان', + 'فرآورده های گوشتی تهران', + 'کارخانجات نورد لوله یاران', + 'كشت و صنعت پياذر', + 'کاوه کشاورز', + 'كيوان', + 'گروه صنعتي سپاهان', + 'کشت و صنعت اشراق', + 'لوله و پروفیل سپنتا تهران', + 'کشت و صنعت قطران گل ایران', + 'لوله و ماشين سازي ايران', + 'کشت وصنعت روژین تاک', + 'مجتمع فولاد خراسان', + 'کشتارگاه صنعتی طیور سپیدان آمل', + 'میراب پروفیل', + 'گروه توليدي مهرام', + 'نورد و توليد قطعات فولادي', + 'گلوكوزان', + 'نورد و لوله صفا', + 'مارگارين', + 'نوین آلیاژسمنان', + 'مجتمع صنایع غذایی بهپودر اصفهان', + 'فولاد آذربايجان', + 'مجتمع كشت و صنعت چين چين', + 'فولاد افزا سپاهان', + 'مجتمع کارخانجات سوربن شمال', + 'گروه ملي صنعتي فولاد ايران', + 'مرغ اجداد زربال', + 'پروفيل صنعت جنوب', + 'شوكو پارس', + 'صبا فولاد خلیج فارس', + 'آرد تجارت', + 'فولاد تربت حیدریه', + 'بهپاك', + 'لوله و تجهيزات سديد', + 'پيچك', + 'نورد لوله اهواز', + 'توسعه کشت و صنعت ملی ( كشت و صنعت گرگان )', + 'نورد و پروفيل پارس', + 'فراورده هاي غذائي مشهد', + 'گروه پیمانکاری صنعتی', + 'گروه معادن', + 'احداث صنعت', + 'معدن کاران انگوران', + 'گروه ساخت قطعات خودرو', + 'باما', + 'تولید موتور های دیزل ایران', + 'تامين ماسه ريخته گري', + 'اگزوز خودرو خراسان', + 'تامین مواد اولیه فولاد صبا نور', + 'الكتريك خودرو شرق', + 'توسعه معادن روي ايران', + 'آهنگري تراكتورسازي ايران', + 'توليد فروموليبدن كرمان', + 'اورند پلاستیک', + 'تولیدی آذر سنگ سرخ', + 'ايران دوچرخ', + 'جهاد نصر سیرجان', + 'پلاسكو كار سايپا', + 'حفاری ایراندشت کاشان', + 'توليد محورخودرو', + 'ذوب وروی بافق', + 'توليدي قطعات محوري خراسان', + 'زرین معدن آسیا', + 'تولیدی صنعتی لنت پارس', + 'زغال سنگ نگين طبس', + 'چرخشگر', + 'زنجان برنز', + 'رادياتور ايران', + 'سرمایه گذاری توسعه معادن کوثر', + 'ريخته گري تراكتورسازي ايران', + 'سنگ آهن شرق', + 'رينگ سازي مشهد', + 'سنگ آهن گل گهر', + 'ریخته گری آلومینیوم ایران خودرو', + 'سنگاب آذرشهر', + 'ساخت و نصب صنعتی البرز', + 'سنگاب همدان', + 'سازه پويش', + 'سوژميران', + 'سايپا آذين', + 'سولفاتيک', + 'سایپا پرس', + 'شن سازان هراز', + 'سیبا موتور', + 'صنعت روی زنگان', + 'شمیم پژوهش', + 'صنعتي و معدني شمال شرق شاهرود', + 'صنايع ريخته گري ايران', + 'فراوري مواد معدني ايران', + 'صنایع ریخته گری پرلیت آسیا', + 'فرو سيليس ايران', + 'صنایع نوید موتور', + 'مجتمع معادن سنگ چینی نی ریز', + 'صنعتي نيرو محركه', + 'معادن بافق', + 'صنعتی صبوران پلیمر', + 'معادن سنگ اهن احیاء سپاهان', + 'فنر سازی زر گلپايگان', + 'معادن منگنز ايران', + 'فنرسازي خاور', + 'معدن کار باختر', + 'فنرسازي زر', + 'معدني دماوند', + 'كاربراتور ايران', + 'معدني و صنعتي چادرملو', + 'كارخانجات كمك فنر ايندامين سايپا', + 'معدنی و فرآوری سرمه فیروزآباد', + 'کابل خودرو سبزوار', + 'ندای رهاوی', + 'کلاچ سازی شایان صنعت', + 'زغال سنگ البرز شرقی', + 'گیربکس سایپا', + 'زغال سنگ البرز مرکزی', + 'لنت ترمز ايران', + 'زغال سنگ کرمان', + 'ماشین سازی فراگیر سپنتا', + 'فرآوري معدني اپال کاني پارس', + 'مجتمع صنعتی سپاهان باطری', + 'گروه توسعه معادن روی ایران', + 'محورسازان ايران خودرو', + 'گروه قند و شکر', + 'مهركام پارس', + 'سهامی عام شهد – قند خوی', + 'مهندسي نصير ماشين', + 'شکر شاهرود', + 'موتورسازان تراكتورسازي ايران', + 'صنعتی کشاورزی شیرین خراسان', + 'نیروسازاراک‎', + 'فرآورد ه هاي غذايي و قند پيرانشهر', + 'یسکو', + 'فراورده هاي غذايي و قند تربت جام', + 'گروه انتشار، چاپ و تكثير', + 'فرآورده هاي غذايي و قند چهارمحال', + 'افست', + 'قند اصفهان', + 'گروه خدمات فنی و مهندسی', + 'قند ثابت خراسان', + 'ملی ساختمان', + 'قند شيروان قوچان وبجنورد', + 'مهندسی فرا نیرو', + 'قند قهستان', + 'آبادراهان پارس', + 'قند لرستان', + 'احداث تاسیسات انتقال نیرو – اتانیر', + 'قند مرودشت', + 'آذرپاسیلو', + 'قند نقش جهان', + 'ارسا ساختمان', + 'قند نيشابور', + 'آفرینه طوس', + 'قند هكمتان', + 'اهرام فناوری قدرت', + 'کارخانجات قند قزوین', + 'ایریتک', + 'قند بيستون', + 'بازرسي مهندسي و صنعتي ايران', + 'قند پارس', + 'تجهیزات و خدمات صنایع آب و برق ایران – صانیر', + 'گروه رایانه و فعالیتهای وابسته به آن', + 'تکنیک', + 'ایران ارقام', + 'توسعه ساخت و نصب صنايع بتني و فلزي گسترش مانا ساز آبيک', + 'تجارت الكترونيك پارسيان', + 'جنرال مکانیک', + 'توسعه سازه پایه فن آوا', + 'حفاری شمال', + 'توسعه فناوری اطلاعات خوارزمی', + 'خدمات مهندسی ساختمان تاسیسات راه آهن', + 'تینا سامانه', + 'خدماتي تجهيزات سنگين همگام', + 'داده پردازي خوارزمي', + 'راهبران فولاد اصفهان', + 'داده پردازی ایران', + 'راهسازی و ساختمانی 115', + 'داده پردازی فن آوا', + 'ره  گستر نفت', + 'داده سامانه فن آوا', + 'صنعتی دریایی ایران – صدرا', + 'فن آوا کارت', + 'فراب', + 'کارت اعتباری ایران کیش', + 'کیسون', + 'گسترش الکترونیک مبین ایران', + 'معماران پارس صنعت', + 'خدمات انفورماتیک', + 'مهام شرق', + 'گروه وسايل اندازه گيري، پزشكي و اپتيكي', + 'مهندسان مشاور سازه', + 'مهندسی فرسار تجارت', + 'مهندسي و نصب فيرمکو پارس', + 'پویندگان راه سعادت', + 'مهندسي وتحقيقاتي فلزات غيرآهنی', + 'كنتور سازي ايران', + 'مهندسی و پشتیبانی نیروگاهی البرز توربین', + 'گروه ماشين آلات و تجهيزات', + 'موننکو ایران', + 'مارال صنعت جاوید', + 'نصب نیرو', + 'ماشین رول', + 'خدمات ماشینی کشتیرانی', + 'افرند کالا سازه', + 'گسترش صنايع وخدمات', + 'آلفا پاک ایران', + 'گروه لوازم خانگي', + 'بلبرينگ ايران', + 'لعران', + 'بهسازان غلطک فولاد اصفهان', + 'ارج', + 'پارس بوشونگ', + 'آیسان خزر', + 'پاریزان صنعت', + 'پارس خزر', + 'پمپ سمنان انرژی', + 'تولیدی و صنعتی نیک کالا', + 'تراكتور سازي ايران', + 'صنايع سرماآفرين قشم', + 'تراکتور سازی کردستان', + 'صنعتي جنرال', + 'تسهیل ماشین صنعت', + 'كارخانجات آبسال', + 'توليد تجهيزات سنگين هپكو', + 'كارخانجات لوازم خانگي پارس', + 'توليدي پمپ پارس', + 'کارخانجات پارس ماشین', + 'توليدي تجهيزات ايمني راهها', + 'گروه صنعتي بوتان', + 'تیراژه ماشین', + 'لوازم خانگی نانیوا', + 'دلتا راه ماشین', + 'توليدي كولر گازي ايران', + 'رهشاد سپاهان', + 'جام جهان نما', + 'ساخت تجهيزات سپاهان', + 'كارخانجات صنعتي آزمايش', + 'سوت ماشین', + 'گروه پلاستيك', + 'صنايع پمپ سازي ايران', + 'یزد بسپار', + 'صنايع سرما آفرين', + 'آرتا پلاست', + 'صنایع پمپ ابارا', + 'پلاستيران', + 'صنعتی هلی خودرو', + 'پلاستيکهاي مهندسي درخشان ساز', + 'طراحي مهندسي وساخت تجهيزات وابزارآلات سايپا', + 'توليدي پلاستيك شاهين', + 'فولادريزي قائم سپهر سپاهان', + 'توليدي گاز لوله', + 'کالای پمپ', + 'توليدي و صنعتي درخشان تهران', + 'ماشين سازي اراك', + 'جوی گستر نفت', + 'ماشين سازي نیرو محركه', + 'صنايع لاستيك سهند', + 'مهندسي تكنو تار', + 'كارخانجات توليدي تهران', + 'مهندسي و توليد ماشين آلات راهسازي و معدني کشاورزي هپکو اراک', + 'توليدي وصنعتي ايران وغرب', + 'مهندسي و ساختمان ماشين سازي اراک', + 'لوله سازي اهواز', + 'مهندسي و قطعات ماشين آلات راه سازي ايران', + 'گروه مبلمان و مصنوعات ديگر', + 'مهندسی فیروزا', + 'عايق پلاستيك', + 'مهندسی و ساخت بویلر مپنا', + 'تجهيزات مدارس ايران', + 'هوا ابزار تهران', + 'صنعتی جهان چیدمان-جلیس', + 'اشتهاد موتورز', + 'گروه محصولات شيميايي', + 'كارخانجات صنعتي  و توليدي اتمسفر', + 'احسان شیمی استهبان', + 'كمپر سور سازي ايران', + 'آریا رزین', + 'ليفتراك سازي سهند', + 'الکترو زر سازه', + 'فرتاک ماشین', + 'ایمن تاش سپاهان', + 'کمباین سازی ایران', + 'بردار شیب', + 'ماشين آلات صنعتي تراكتور سازي ايران', + 'بين المللي محصولات پارس', + 'صنايع توليدي اشتاد ايران', + 'بين المللي سارنگ تدارك', + 'پروفيل و يخچال ايران پويا', + 'پارس زئولايت', + 'توليدي بهمن', + 'پارسیان پارت پاسارگاد', + 'گروه محصولات كاغذي', + 'پاكسان', + 'بسته بندي پارس', + 'پاکنام', + 'صنايع كاغذ سازي كاوه', + 'پالایش قطران ذغالسنگ اصفهان', + 'صنایع چوب و کاغذ مازندران', + 'توکا رنگ فولاد سپاهان', + 'كارتن البرز', + 'تولي پرس', + 'كارتن ايران', + 'توليد سموم علف كش', + 'کارتن مشهد', + 'تولید مواد اولیه الیاف مصنوعی', + 'محصولات کاغذی لطیف', + 'تولیدی و صنعتی  فراسان', + 'كارتن پارس', + 'تولیدی و صنعتی سامد', + 'گروه منسوجات', + 'تولیدی وصنعتی خودرنگ', + 'ايران برك', + 'حباب کف توس', + 'توليدي بافت آزادي', + 'داروئي ارايشي وبهداشتي مينو', + 'وطن اصفهان', + 'دنیای آرایش', + 'ريسندگي و با فندگي كاشان', + 'دوده صنعتي پارس', + 'ريسندگي و بافندگي پاكريس', + 'رزیتان', + 'ريسندگي و بافندگي ري', + 'ریف ایران', + 'فرش پارس', + 'سامان شیمی', + 'گردباف يزد', + 'سرمايه گذاري صنايع شيميايي ايران', + 'گروه صنعتي نقش ايران', + 'شيمي بافت', + 'نساجي بابكان', + 'شيميايي پارس پامچال', + 'نساجي خوي', + 'شيميايي فرآورد قشم', + 'نساجي غرب', + 'شیمیایی بهداد', + 'نساجي قائم شهر', + 'شیمیایی بهداش', + 'نساجي مازندران', + 'شیمیایی و تولیدی رزپلیمر', + 'وطن اصفهان', + 'صنايع شيميايي رنگين', + 'يزد باف', + 'صنايع شيميايي سينا', + 'صنايع نساجي ايران', + 'صنايع شيميايي فارس', + 'گروه بانك ها، موسسات اعتباري و ساير نهادهاي مالي', + 'صنایع بهداشتی ساینا', + 'بانك اقتصاد نوين', + 'صنایع رنگ و رزین طیف سایپا', + 'بانك پارسيان', + 'صنایع شیمی ساختمان آباد گران', + 'بانك سامان', + 'فراپاکس شیراز', + 'بانك كارآفرين', + 'كربن ايران', + 'بانک انصار', + 'كف', + 'بانک ایران زمین', + 'کلر پارس', + 'بانک پاسارگاد', + 'گلتاش', + 'بانک تجارت ایران', + 'لابراتوارهای داروهای گیاهی طبیعت زنده', + 'بانک حکمت ایرانیان', + 'لعاب مشهد', + 'بانک دی', + 'لعابيران', + 'بانک سرمایه', + 'مجتمع صنایع شیمیایی پلیمر ایران', + 'بانک سینا', + 'مديريت صنعت شوينده توسعه صنايع بهشهر', + 'بانک شهر', + 'مروارید هامون', + 'بانک صادرات ایران', + 'معدني املاح ايران', + 'بانک گردشگری', + 'ملي شيمي كشاورز', + 'بانک ملت', + 'من', + 'پست بانک', + 'نيرو كلر', + 'بانک تات', + 'الياف', + 'بانک کشاورزی', + 'پارسيلون', + 'گروه واسطه گري هاي مالي', + 'توليدي  الياف پلي  پروپيلين  بنياد', + 'رايان سايپا', + 'صنايع تبديلي گلستان', + 'سپرده گذاری مرکزی اوراق بهادار و تسویه وجوه', + 'كارخانجات توليدي سوپر رنگ', + 'ليزينگ آريادانا', + 'صنايع رنگ پارس الوان', + 'ليزينگ ايران', + 'گروه مواد و محصولات دارويي', + 'ليزينگ خودرو غدير', + 'آفا شیمی', + 'ليزينگ صنعت و معدن', + 'البرز دارو', + 'ليزينگ ماشين الات سنگين ايرانيان', + 'ايران دارو', + 'لیزینگ اقتصاد نوین', + 'پارس دارو', + 'لیزینگ رازی', + 'تحقیقاتی و تولیدی سیناژن', + 'لیزینگ ماشین آلات و تجهیزات پاسارگاد', + 'تهران دارو', + 'لیزینگ ایرانیان', + 'تهران شيمي', + 'لیزینگ شهر – لیزینگ سامان آریا', + 'توليد ژلاتين کپسول ايران', + 'گروه توزیع برق', + 'توليد مواد اوليه دارو پخش', + 'توزیع برق بوشهر', + 'تولید مواد دارویی درسا دارو', + 'توسعه برق شمال افشان گستر', + 'داروسازي اسوه', + 'صنايع برق زنگان پارس', + 'داروسازي اكسير', + 'گهر انرژي سيرجان', + 'داروسازي امين', + 'برق و انرژی صبا', + 'داروسازي جابرابن حيان', + 'گروه شرکتهای بازرگانی', + 'داروسازي حكيم', + 'اتصال استیل هما', + 'داروسازي دكتر عبيدي', + 'اسپرلوس اهورا', + 'داروسازي روزدارو', + 'افزار پرداز رمیس', + 'داروسازي زهراوي', + 'الهام بیسان', + 'داروسازي فارابي', + 'ایمان تجارت روشن', + 'داروسازي كوثر', + 'بازرگاني پتروشيمي', + 'داروسازی بهوزان', + 'بازرگانی ارمغان مهر سیرت', + 'داروسازی تولید دارو – سهامی خاص', + 'بازرگانی ایران ترانسفو', + 'داروسازی دانا', + 'بازرگانی بین المللی استوان سپند', + 'داروسازی شهید قاضی تبریز', + 'بازرگانی پارس ماهان آسیا', + 'داروسازی گیلارانکو', + 'بازرگانی پتروشیمی زنجان', + 'داروئي و بهداشتي لقمان', + 'بازرگانی تبادل و تدارک کالا', + 'داملران', + 'بازرگانی صبا بیمه ایرانیان', + 'سينا دارو', + 'بازرگانی مبین تجارت غرب', + 'شيمي دارويي داروپخش', + 'بازرگانی نفت یاب', + 'صنعتي كيميدارو', + 'بازرگانی،صنعتی بهشت پارس', + 'فارما شیمی', + 'بهترین های پزشکی پارس', + 'فراورده هاي تزريقي ايران', + 'پارس بازرگان', + 'كارخانجات دارو پخش', + 'پارس گستر مینو', + 'لابراتورهای دارویی رازک', + 'پديده گستران غرب', + 'مواد اولیه دارویی تهران شیمی', + 'تجارت گستران خوارزمي', + 'داروسازی سبحان انکولوژی', + 'تجاری و بازرگانی مواد معدنی میناب', + 'سرمايه گذاري البرز', + 'تجهیز یاران', + 'شيرين دارو', + 'تهیه و تولید خاک نسوز استقلال آباده', + 'گروه دارویی سبحان', + 'توسعه صنايع غذايي بم', + 'گروه خودروسازی', + 'توسعه و تجارت بین المللی صبا', + 'ايران خودرو', + 'توسعه و تجارت ماتریس', + 'ايران خودروديزل', + 'جهان فعالیت', + 'ایران خودرو تبریز', + 'خشکبار دست چین', + 'ایران خودرو خراسان', + 'داده های رسا', + 'ایران خودرو مازندران', + 'دانیال کار', + 'بهمن دیزل', + 'درمان یار آنی', + 'پارس خودرو', + 'راسن درمان', + 'تولیدی و صنعتی عقاب افشان', + 'رویال پیشگام شرق', + 'زامياد', + 'سامان بارز', + 'سايپا', + 'سیاحان سپهر آسیا', + 'سايپاديزل', + 'صخره سنگی فرزین', + 'سایپا کاشان', + 'صنایع نئون پرس', + 'گروه بهمن', + 'فانوس دشت تجارت', + 'بنيان ديزل', + 'کیا مهستان', + 'توليدي مرتب', + 'کیمیا آرا هرم', + 'گروه محصولات لبني', + 'گسترش تجارت کالای ایرانیان', + 'پاک پی', + 'مديريت و ساخت طرحهاي نفت گستر', + 'تولید فرآورده های لبنی کاله', + 'مهر اسپند پویا', + 'شير پاستوريزه پگاه اصفهان', + 'مهندسی بازرگانی درداران سریر', + 'شير پاستوريزه پگاه خراسان', + 'نویان بسپار', + 'شير پگاه آذربايجان غربي', + 'نیکان شهد بارز', + 'صنايع شير ايلام زاگرس', + 'گروه هولدینگ', + 'فراورده هاي لبني پاکسار ساري', + 'توسعه صنايع بهشهر – هلدينگ', + 'لبنيات پاستوريزه پاك', + 'داروپخش – هلدينگ', + 'لبنيات كالبر', + 'راه آهن جمهوری اسلامی ایران', + 'لبنیات پاستوریزه پاک آرا سنندج', + 'سرمايه گذاري توسعه معادن و فلزات', + 'گروه منسوجات و فرش بافی', + 'سرمايه گذاري توكا فولاد – هلدينگ', + 'ابهر ریس', + 'سرمايه گذاري صنعت نفت – هلدينگ', + 'ايران پوپلين', + 'سرمایه گذاری گروه صنعتی ملی', + 'ايران مرينوس', + 'گروه صنعتي سديد – هلدينگ', + 'بافتینه', + 'گروه صنعتي قطعات اتومبيل ايران', + 'پشمبافي توس', + 'گروه صنعتي ناب', + 'پلي اكريل ايران', + 'گسترش نفت و گاز پارسیان', + 'تمدن فرش کاشان', + 'مدیریت پروژه های نیروگاهی ایران – مپنا', + 'تولیدی پارس دکور', + 'هلدینگ توسعه معادن و صنایع معدنی خاورمیانه', + 'تولیدی پارس نخ', + 'هلدینگ دامپروری شیروگوشت پارس', + 'تولیدی پینک', + 'سرمايه گذاري بانك ملي ايران – هلدينگ', + 'تولیدی و صنعتی پارس تکمیل', + 'صنعتي بهشهر', + 'تولیدی و صنعتی رسول اصفهان', + 'گروه بنادر ودریانوردی', + 'شبنم باف', + 'پایانه ها و مخازن پتروشیمی', + 'صنایع موکت همدان', + 'خدمات دریایی و بندری کاوه', + 'صنایع نخ خمین', + 'گروه گاز', + 'صنایع نساجی همدانیان', + 'گاز اصفهان', + 'ظریف مصور', + 'ملی گاز', + 'فرش مشهد', + 'گاز خراسان جنوبی', + 'فرش نگین مشهد', + 'گروه آشامیدنی ها', + 'کارخانجات ریسندگی نطنز', + 'آب معدنی دماوند', + 'مخمل و ابريشم كاشان', + 'آذر شهد ارومیه', + 'موکت نگین مشهد', + 'بهنوش ايران', + 'نساجي بروجرد', + 'پیمان فردان', + 'نساجی کویر سمنان', + 'تولیدی نوشابه ارم نوش', + 'صنايع نساجي ايران', + 'زمزم آذربایجان', + 'گروه حمل و نقل دریایی و حمل و نقل آب های ساحلی', + 'زمزم اصفهان', + 'حمل و نقل ترکیبی کشتیرانی جمهوری اسلامی', + 'زمزم تهران', + 'حمل و نقل خدمات دریایی آبادان', + 'زمزم رشت', + 'خدمات دریایی و کشتیرانی خط دریا بندر', + 'زمزم گرگان', + 'دريابان جنوب ايران', + 'شهداب', + 'کشتیرانی آریا', + 'فرآورده های نوشیدنی تسنیم نوش', + 'کشتیرانی جمهوری اسلامی ایران', + 'نوش مازندران', + 'کشتیرانی والفجر', + 'ساسان', + 'گروه خدمات فنی-مهندسی خودرو', + 'گروه تایر سازی', + 'امداد خودرو ایران', + 'ایران یاسا', + 'امداد خودرو سایپا', + 'بید وایر ایران', + 'بازرسی فنی و کنترل خوردگی تکین کو', + 'توليدي ايران تاير', + 'گواه', + 'توليدي لاستيکهاي صنعتي مبارکه', + 'مزدا یدک', + 'کویر تایر', + 'مهندسی و مشاور سازه گستر سایپا', + 'لاستيك دنا', + 'خدمات کمات ماشین شرق', + 'لاستیک بارز', + 'گروه فرهنگی و گردشگری', + '8', + 'لاستیک پارس', + 'تجارت توسعه گردشگري آتيه انديشان', + 'مجتمع صنايع لاستيك يزد', + 'توسعه گردشگري کاروانسراي پارس', + 'مجتمع صنعتي آرتاويل تاير', + 'گروه سرمايه گذاري ميراث فرهنگي و گردشگري ايران', + 'توليدي لاستيك البرز – كيان تاير', + 'مجتمع توريستي، رفاهي آبادگران ايران', + 'گروه شرکتهای مشاوره', + 'گروه كاني های غير فلزي', + 'irpmc', + 'آجر نسوز امين آباد', + 'بودجه irpmc', + 'آذريت', + 'همکاران سیستم اردبیل', + 'ايتالران', + 'همکاران سیستم البرز', + 'ايرانيت', + 'همکاران سیستم پناه شرق', + 'پرمیت', + 'همکاران سیستم خراسان جنوبی', + 'پشم شیشه ایران', + '7', + 'همکاران سیستم خراسان رضوی', + 'تولیدی و صنعتی آبگینه', + 'همکاران سیستم خوزستان', + 'خاك چيني ايران', + 'همکاران سیستم زنجان', + 'زرین شیشه مرکزی', + 'همکاران سیستم فارس', + 'سایپا شیشه', + 'همکاران سیستم قزوین', + 'سراميك هاي صنعتي اردكان', + 'همکاران سیستم گیلان', + 'شيشه قزوين', + 'همکاران سیستم مازندران', + 'شيشه همدان', + 'گروه ماشين آلات و دستگاههاي برقي', + 'شيشه و گاز', + 'ايران ترانسفو', + 'شیشه داروئی رازی تاکستان', + 'ایران ترانسفوی ری', + 'فارسيت اهواز', + 'پارس سوئيچ', + 'فرآورده هاي نسوز پارس', + 'تال ایران', + 'فرآورده هاي نسوزآذر', + 'تامین تابلو', + 'فراورده های نسوز ایران', + 'تجهیزات انتقال برق پارس', + 'كارخانجات توليدي شيشه دارويي رازي', + 'ترانسفور ماتور توزیع زنگان', + 'كارخانه فارسيت درود', + 'تهران پادنا', + 'ورزيران', + 'توربوژنراتور شاهرود', + 'مقره سازی ایران', + 'توس فیوز', + 'چینی سازی البرز', + 'جابون', + 'گروه ارتباطات', + 'خیام الکتریک', + 'ارتباطات فن آوا', + 'صنايع جوشكاب يزد', + 'ارتباطات کوه نور', + 'صنایع کابل سازی افق البرز', + 'ارتباطات سیار ایران – همراه اول', + 'صنعتی مهندسی پالایش نیرو', + 'مخابرات ایران', + 'فاراتل', + 'گروه شرکت های پخش', + 'كابل البرز', + 'پخش سراسری کالای کالبر', + 'كابل باختر', + 'پخش هجرت', + 'كابلهاي مخابراتي شهيد قندي', + 'توزيع داروهاي دامي داروپخش', + 'كارخانجات كابلسازي ايران', + 'مهندسي و پشتيباني پخش فرآورده هاي نفتي امين', + 'کابل تک', + 'گروه بیمه', + 'لامپ پارس شهاب', + 'بيمه پاسارگاد', + 'مازی نور', + 'بیمه آسیا', + 'مهندسی مپنا مکو', + 'بیمه البرز', + 'مهندسی و ساخت توربین مپنا توکا', + 'بیمه پارسیان', + 'مهندسی و ساخت ژنراتور مپنا – پارس', + 'بیمه دانا', + 'موتوژن', + 'بیمه دی', + 'نيرو ترانس', + 'بیمه نوین', + 'پارس نور الکتریک', + 'صندوق بیمه سرمایه گذاری فعالیت های معدنی', + 'توليدي قوه پارس', + 'گروه سرمايه گذاري ها', + 'مهندسی و ساخت پره توربين مپنا – پرتو', + 'حفیظ سامانه', + 'تامین قطعات و تجهیزات سرو نیرو شیراز', + 'تکادو', + 'صنایع مهتاب خراسان', + 'سرمايه گذاري آتيه دماوند', + 'صنعتي مهر آباد', + 'سرمايه گذاري انديشه محوران', + 'گروه كشاورزي ، دامپروري و خدمات وابسته به آن', + 'سرمايه گذاري بهمن', + 'تلیسه نمونه', + 'سرمايه گذاري پارس توشه', + 'دانه چین', + 'سرمايه گذاري توسعه آذربايجان', + 'دامپروری و مرغداری دشت خرمدره', + 'سرمايه گذاري توسعه صنعتي ايران', + 'دامداری شیر و دام بنیاد', + 'سرمايه گذاري توسعه ملي', + 'شیر و گوشت زاگرس', + 'سرمايه گذاري چشم انداز توسعه شمال', + 'کشاورزی ودامپروری بینالود', + 'سرمايه گذاري ساختمان ايران – هلدينگ', + 'کشاورزی ودامپروری دشت نوین ملایرا', + 'سرمايه گذاري سايپا', + 'کشاورزی ودامپروری یاسوج', + 'سرمايه گذاري سپه', + 'کشت و دام قیام اصفهان', + 'سرمايه گذاري صندوق بازنشستگي كشوري', + 'کشت وصنعت سبز پاسارگاد', + 'سرمايه گذاري صنعت بيمه', + 'گسترش صنايع و خدمات کشاورزي', + 'سرمايه گذاري صنعت ومعدن', + 'مجتمع دامداری بیجین', + 'سرمايه گذاري گروه صنايع بهشهر ايران', + 'مجتمع شیر و گوشت مهدشت', + 'سرمايه گذاري گروه صنعتي رنا', + 'مگسال', + 'سرمايه گذاري معيار صنعت پارس', + 'کشت وصنعت پیوند هراز', + 'سرمايه گذاري ملت', + 'گروه محصولات فلزي', + 'سرمايه گذاري ملي ايران', + 'صنعتی گام اراک', + 'سرمايه گذاري نيرو', + 'آریا بارون توس', + 'سرمايه گذاري هامون کيش', + 'پودر جوش ایران', + 'سرمایه گذاری اعتماد جم', + 'تولیدی و صنعتی الکترود یزد', + 'سرمایه گذاری اقتصاد نوین', + 'جوش و اکسیژن ایران', + 'سرمایه گذاری ایساتیس پویا', + 'دژپاد', + 'سرمایه گذاری پارس آریان', + 'سولیران', + 'سرمایه گذاری توسعه و عمران استان اردبیل-سبلان سبز', + 'صنايع مفتولي زنجان', + 'سرمایه گذاری دارویی تامین', + 'صنایع آذرآب', + 'سرمایه گذاری دانایان پارس', + 'صنایع استیل البرز', + 'سرمایه گذاری سروش یاران', + 'صنایع بسته بندی ایران', + 'سرمایه گذاری صندوق بازنشستگی کارکنان بانک ها', + 'صنایع بسته بندی مشهد', + 'گسترش سرمايه گذاري ايران خودرو', + 'صنایع فلزی کوشا', + 'گسترش سرمایه گذاری ایرانیان', + 'صنعتی آما', + 'مديريت سرمايه گذاري اميد', + 'صنعتی جام دارو', + 'نیرو سرمایه', + 'لامیران – تیغ ایران', + 'هلدینگ توسعه معادن و صنایع معدنی خاور میانه -میدکو', + 'آونگان', + 'ملی نفت ایران', + 'پارس متال', + 'مديريت سرمايه برنا', + 'پایساز', + 'سرمايه گذاري بوعلي', + 'توسعه و گسترش صنایع بسته بندی فلزی', + 'سرمايه گذاري سمند', + 'تولیدی ابزار مهدی', + 'سرمايه گذاري صنايع پتروشيمي', + 'گسترش صنایع انرژی آذرآب', + 'سرمايه گذاري كار آفرين', + 'صنایع فلزی ایران', + 'سرمايه گذاري نفت قشم', + 'صنعتی کاوه', + 'سرمایه گذاری پویا همگام', + 'صنعتی ملایر', + 'سرمایه گذاری توسعه  الوند غدیر', + 'بسته بندي البرز', + 'گروه فعاليتهاي پشتيباني و حمل و نقل', + 'گروه حمل و نقل، انبارداری و ارتباطات', + 'خدمات دريايي تايدواترخاورميانه', + 'بنیادبارانداز', + 'گروه توليدات پتروشيمي', + 'توکا ریل', + 'پترو شیمی لاله', + 'حمل و نقل آشنا راه سماء', + 'پتروشيمي آبادان', + 'حمل و نقل بین المللی خلیج فارس', + 'پتروشيمي اراك-پتروشیمی شازند', + 'حمل و نقل پتروشیمی', + 'پتروشيمي اصفهان', + 'حمل و نقل توکا', + 'پتروشيمي شيراز', + 'گروه فرآورده هاي نفتي كك و سوخت هسته اي', + 'پتروشیمی  پردیس', + 'پالايشگاه نفت تبريز', + 'پتروشیمی  زاگرس', + 'پالایش نفت آبادان', + 'پتروشیمی امیرکبیر', + 'پالایش نفت بندر عباس', + 'پتروشیمی بندر امام', + 'پالایش نفت تهران', + 'پتروشیمی بیستون', + 'پالایش نفت لاوان', + 'پتروشیمی تند گویان', + 'پالایشگاه نفت شیراز', + 'پتروشیمی جم', + 'تجهيز نيروي زنگان', + 'پتروشیمی جهرم', + 'خدمات حفاری صنایع نفت', + 'پتروشیمی خارک', + 'نفت ایرانول', + 'پتروشیمی خراسان', + 'نفت بهران', + 'پتروشیمی رجال', + 'نفت پارس', + 'پتروشیمی فن آوران', + 'نگین فخر آذربایجان', + 'پتروشیمی مارون', + 'توسعه نفت وگاز مپنا', + 'پتروشیمی مبین', + 'تولیدی مخازن گاز طبیعی آسیا ناما', + 'صنایع پتروشیمی کرمانشاه', + 'گروه كاشي و سراميك', + 'پتروشيمي اروند', + 'پارس سرام', + 'پتروشيمي برزويه', + 'تولید سرام دیر گداز', + 'پتروشيمي فجر', + 'تولیدی توس چینی', + 'مديريت توسعه صنايع پتروشيمي', + 'تولیدی گرانیت بهسرام', + 'پتروشيمي بوعلي سينا', + 'سرامیک طوس', + 'پتروشيمي بين الملل', + 'صنایع چینی زرین ایران', + 'پتروشيمي خوزستان', + 'صنایع کاشی اصفهان', + 'پتروشيمي پارس', + 'صنایع کاشی تیما', + 'اوره و ؛آمونیک پتروشیمی زنجان', + 'صنایع کاشی نائین', + 'پتروشيمي فسا', + 'صنایع کاشی و سرامیک الوند', + 'پتروشیمی داراب', + 'کارخانجات کاشی و سرامیک حافظ', + 'پتروشیمی سرمایه گذاری ایرانیان', + 'کارخانه چینی ایران', + 'پتروشیمی لردگان', + 'کاشی بیستون', + 'پتروشیمی ممسنی', + 'کاشی پارس', + 'خاک طلایی توس', + 'کاشی تکسرام', + 'شهرک صنعتی پتروشیمی زنجان', + 'کاشی فیروزه مشهد', + 'صنايع پتروشيمي دهدشت', + 'کاشی کرد', + 'صنایع پتروشیمی تخت جمشید', + 'کاشی نیلو', + 'صنایع پتروشیمی زنجان', + 'کاشی و سرامیک سعدی', + 'گروه انبوه سازي، املاك و مستغلات', + 'کاشی و سرامیک سینا', + 'آ س پ', + 'گلسار فارس', + 'آذر توسعه مسکن', + 'گروه شركتهاي چند رشته اي صنعتي', + 'بين المللي توسعه ساختمان', + 'سرمايه گذاري غدير', + 'پارس مسکن خزر', + 'سرمایه گذاری گروه توسعه ملی(سرمایه گذاری بانک ملی ایران', + 'توسعه ساختمان خوارزمي', + 'گروه ساير وسايل حمل و نقل', + 'توسعه صنعت ساختمان غدیرخوزستان', + 'سرمايه گذاري اعتباري ايران', + 'زرین بنا پارسیان', + 'گروه ساخت راديو، تلويزيون و دستگاهها و وسايل ارتباطي', + 'ساختمان اصفهان', + 'آريا الكترونيك ايران', + 'ساختماني برج ناهيد', + 'پارس الكتريك', + 'سامان گستر اصفهان', + 'شهاب', + 'سرمايه گذاري توسعه شهري توس گستر', + 'صنايع مخابراتي راه دور ايران', + 'سرمايه گذاري توسعه وساختماني برج آوران', + 'فن آوران انیاک', + 'سرمايه گذاري ساختمان نوین', + 'كارخانجات صنعتي پيام', + 'سرمايه گذاري شاهد', + 'كارخانجات مخابراتي ايران', + 'سرمايه گذاري و توسعه خوزستان', + 'مرکز ماشینهای اداری ایران', + 'سرمایه گذاری مسکن تهران', + 'گروه محصولات چوبي', + 'سرمایه گذاری مسکن شمال شرق', + 'ایزوفام', + 'شهرسازی و خانه سازی باغ میشه', + 'توليد فيبر ايران', + 'صبا آرمه', + 'صنايع چوب خزر کاسپين', + 'طرح ساختمان پارسا', + 'نئوپان 22 بهمن', + 'عمران و توسعه شاهد', + 'سخت آژند', + 'گروه شرکت های مشاوره تبلیغاتی', + 'موسسه پویندگان توسعه پارس', + # Source: https://en.wikipedia.org/wiki/List_of_companies_of_Iran + 'شرکت ملی نفت ایران', + 'معادن ایران', + 'سازمان نوسازی', + 'ایران خودرو', + 'امیدان تجارت کیش ', + 'سایپا', + 'مجتمع فولاد مبارکه', + 'بانک پارسیان', + 'بانک سامان', + 'بانک سپه', + 'صنایع پتروشیمی ایران', + 'بانک مسکن', + 'لایف برد پارسه', + 'صنایع پترو شیمی بو علی سینا', + 'فولاد خورستان', + 'ابر موتور', + 'سرمایه‌گذاری بانک ملی', + 'ایران خودرو دیزل', + 'توسعه صنعتی بوشهر', + 'بانک اقتصاد نوین', + 'شرکت زامیاد', + 'صنایع شیر ایران (پگاه)', + 'سرمایه‌گذاری غدیر', + 'ایمیدرو', + 'کارخانجات داروپخش', + 'سایپا دیزل', + 'بانک کارآفرین', + 'معدنی و صنعتی چادرملو', + 'ساخت تأسیسات دریایی ایران', + 'اتکا', + 'گسترش و نوسازی صنایع ایران', + 'تولی‌پرس', + 'هواپیمایی آسمان', + 'سازمان صنایع هوایی ایران', + 'مادیران', + 'پارس آنلاین', + 'شاتل', + 'شرکت مخابرات ایران', + 'ایرانسل', + 'راه‌آهن ایران', + 'هواپیمایی پیام', + 'متروی تهران', + 'شرکت ملی نفت‌کش ایران', + 'پالایش و پخش فراورده‌های نفتی ایران', + 'سازمان انرژی اتمی ایران', + 'صدا و سیما', + 'رجحان', + 'شرکت داده‌پردازی ایران', + 'گروه هتل‌های هما', + 'کیش اورینتال', + 'الک تیک', + ] + + def company(self): + return self.random_element(self.company_names) diff --git a/testbed/joke2k__faker/faker/providers/company/fi_FI/__init__.py b/testbed/joke2k__faker/faker/providers/company/fi_FI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8718a43e753a3adb9608cbe6cf691995612bbd53 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/fi_FI/__init__.py @@ -0,0 +1,52 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + ) + + company_suffixes = ( + 'As Oy', 'Tmi', 'Oy', 'Oyj', 'Ky', 'Osk', 'ry', + ) + + def company_business_id(self): + """ + Returns Finnish company Business Identity Code (y-tunnus). + Format is 8 digits - e.g. FI99999999,[8] last digit is a check + digit utilizing MOD 11-2. The first digit is zero for some old + organizations. This function provides current codes starting with + non-zero. + """ + def calculate_checksum(number): + """Calculate the checksum using mod 11,2 method""" + factors = [7, 9, 10, 5, 8, 4, 2] + sum_ = 0 + for x, y in zip(number, factors): + sum_ = sum_ + int(x) * y + if sum_ % 11 == 0: + return '0' + else: + return str(11 - sum_ % 11) + + first_digit = str(self.random_digit_not_null()) + body = first_digit + self.bothify('######') + cs = calculate_checksum(body) + return body + '-' + str(cs) + + def company_vat(self): + """ + Returns Finnish VAT identification number (Arvonlisaveronumero). + This can be calculated from company business identity code by + adding prefix "FI" and removing dash before checksum. + """ + def convert_to_vat(business_id): + """ + Convert business id to VATIN + """ + return 'FI' + business_id.replace('-', '') + + return convert_to_vat(self.company_business_id()) diff --git a/testbed/joke2k__faker/faker/providers/company/fil_PH/__init__.py b/testbed/joke2k__faker/faker/providers/company/fil_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a09f07115b78dba2dd9e2c1026f519ebc3a648b --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/fil_PH/__init__.py @@ -0,0 +1,85 @@ +from collections import OrderedDict + +from ..en_PH import Provider as EnPhProvider + + +class Provider(EnPhProvider): + """ + Provider for company names for fil_PH locale + + Companies in the Philippines rarely have Filipino names, and when they do, the English name is usually used way more + frequently by the locals. In some cases, the Filipino names are more like in Taglish, so for the purposes of this + provider, only English company names will be generated for this locale. + + Company and brand taglines in pure Filipino, however, are much more common, so this provider will generate catch + phrases in pure Filipino randomly alongside the English ones. + """ + + catch_phrase_formats = OrderedDict([ + ('{{english_catch_phrase}}', 0.64), + ('Ang {{random_noun_ish_good_trait}} ng {{random_object_of_concern}}!', 0.12), + ('Serbisyong {{random_good_service_adjective}} para sa {{random_object_of_concern}}!', 0.12), + ('Kahit kailan, {{random_good_service_adjective_chain}}!', 0.12), + ]) + noun_ish_good_traits = ( + 'bida', + 'ginhawa', + 'haligi', + 'karangalan', + 'lingkod', + 'liwanag', + 'numero uno', + 'pag-asa', + 'tulay', + ) + good_service_adjectives = ( + 'bida', + 'dekalidad', + 'hindi umaatras', + 'kakaiba', + 'maasahan', + 'magaling', + 'mapatitiwalaan', + 'numero uno', + 'panalo', + 'tagumpay', + 'tama', + 'tapat', + 'totoo', + 'tunay', + 'walang kapantay', + 'walang katulad', + 'walang tatalo', + ) + objects_of_concern = [ + 'Filipino', + 'Pilipinas', + 'Pilipino', + 'Pinoy', + 'bahay', + 'bansa', + 'bayan', + 'buhay', + 'mamamayan', + 'mundo', + 'tahanan', + ] + + def random_noun_ish_good_trait(self): + return self.random_element(self.noun_ish_good_traits) + + def random_good_service_adjective(self): + return self.random_element(self.good_service_adjectives) + + def random_good_service_adjective_chain(self): + adjectives = self.random_elements(self.good_service_adjectives, length=2, unique=True) + return ' at '.join(adjectives) + + def random_object_of_concern(self): + return self.random_element(self.objects_of_concern) + + def english_catch_phrase(self): + return super().catch_phrase() + + def catch_phrase(self): + return self.random_element(self.catch_phrase_formats) diff --git a/testbed/joke2k__faker/faker/providers/company/fr_CH/__init__.py b/testbed/joke2k__faker/faker/providers/company/fr_CH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..224ec8730271a2f018d825defac1089ab5fb1da2 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/fr_CH/__init__.py @@ -0,0 +1,38 @@ +from ..fr_FR import Provider as CompanyProvider + + +class Provider(CompanyProvider): + company_suffixes = ('SA', 'Sàrl.') + + def ide(self): + """ + Generates a IDE number (9 digits). + http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html + """ + def _checksum(digits): + factors = (5, 4, 3, 2, 7, 6, 5, 4) + sum_ = 0 + for i in range(len(digits)): + sum_ += digits[i] * factors[i] + return sum_ % 11 + + while True: + # create an array of first 8 elements initialized randomly + digits = self.generator.random.sample(range(10), 8) + # sum those 8 digits according to (part of) the "modulo 11" + sum_ = _checksum(digits) + # determine the last digit to make it qualify the test + control_number = 11 - sum_ + if control_number != 10: + digits.append(control_number) + break + + digits = ''.join([str(digit) for digit in digits]) + # finally return our random but valid BSN + return 'CHE-' + digits[0:3] + '.'\ + + digits[3:6] + '.'\ + + digits[6:9] + uid = ide + # uid: german name for ide + idi = ide + # idi: italian name for ide diff --git a/testbed/joke2k__faker/faker/providers/company/fr_FR/__init__.py b/testbed/joke2k__faker/faker/providers/company/fr_FR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..448f3c7a4729b7d9c9e58763e10f196129d8ee26 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/fr_FR/__init__.py @@ -0,0 +1,130 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + '{{last_name}}', + ) + + catch_phrase_formats = ( + '{{catch_phrase_noun}} {{catch_phrase_verb}} {{catch_phrase_attribute}}', ) + + nouns = ( + 'la sécurité', + 'le plaisir', + 'le confort', + 'la simplicité', + "l'assurance", + "l'art", + 'le pouvoir', + 'le droit', + 'la possibilité', + "l'avantage", + 'la liberté') + + verbs = ( + 'de rouler', + "d'avancer", + "d'évoluer", + 'de changer', + "d'innover", + 'de louer', + "d'atteindre vos buts", + 'de concrétiser vos projets') + + attributes = ( + 'de manière efficace', + 'plus rapidement', + 'plus facilement', + 'plus simplement', + 'en toute tranquilité', + 'avant-tout', + 'autrement', + 'naturellement', + 'à la pointe', + 'sans soucis', + "à l'état pur", + 'à sa source', + 'de manière sûre', + 'en toute sécurité') + + company_suffixes = ('SA', 'S.A.', 'SARL', 'S.A.R.L.', 'S.A.S.', 'et Fils') + + siren_format = "### ### ###" + + def catch_phrase_noun(self): + """ + Returns a random catch phrase noun. + """ + return self.random_element(self.nouns) + + def catch_phrase_attribute(self): + """ + Returns a random catch phrase attribute. + """ + return self.random_element(self.attributes) + + def catch_phrase_verb(self): + """ + Returns a random catch phrase verb. + """ + return self.random_element(self.verbs) + + def catch_phrase(self): + """ + :example 'integrate extensible convergence' + """ + catch_phrase = "" + while True: + + pattern = self.random_element(self.catch_phrase_formats) + catch_phrase = self.generator.parse(pattern) + catch_phrase = catch_phrase[0].upper() + catch_phrase[1:] + + if self._is_catch_phrase_valid(catch_phrase): + break + + return catch_phrase + + # An array containing string which should not appear twice in a catch phrase + words_which_should_not_appear_twice = ('sécurité', 'simpl') + + def _is_catch_phrase_valid(self, catch_phrase): + """ + Validates a french catch phrase. + + :param catch_phrase: The catch phrase to validate. + """ + for word in self.words_which_should_not_appear_twice: + # Fastest way to check if a piece of word does not appear twice. + begin_pos = catch_phrase.find(word) + end_pos = catch_phrase.find(word, begin_pos + 1) + + if begin_pos != -1 and begin_pos != end_pos: + return False + + return True + + def siren(self): + """ + Generates a siren number (9 digits). + """ + return self.numerify(self.siren_format) + + def siret(self, max_sequential_digits=2): + """ + Generates a siret number (14 digits). + It is in fact the result of the concatenation of a siren number (9 digits), + a sequential number (4 digits) and a control number (1 digit) concatenation. + If $max_sequential_digits is invalid, it is set to 2. + :param max_sequential_digits The maximum number of digits for the sequential number (> 0 && <= 4). + """ + if max_sequential_digits > 4 or max_sequential_digits <= 0: + max_sequential_digits = 2 + + sequential_number = str(self.random_number( + max_sequential_digits)).zfill(4) + return self.numerify(self.siren() + ' ' + sequential_number + '#') diff --git a/testbed/joke2k__faker/faker/providers/company/hr_HR/__init__.py b/testbed/joke2k__faker/faker/providers/company/hr_HR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15e63daa25ab30ccc545de348a34dac4dfcaa47c --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/hr_HR/__init__.py @@ -0,0 +1,13 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + ) + + company_suffixes = ( + 'd.o.o.', 'd.d.', 'j.d.o.o.', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/hu_HU/__init__.py b/testbed/joke2k__faker/faker/providers/company/hu_HU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6649e17f338bc4fcd0c54cafe9b4e7f3cee4bb --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/hu_HU/__init__.py @@ -0,0 +1,15 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}} és {{last_name}} {{company_suffix}}', + '{{last_name}} és társa {{company_suffix}}', + ) + + company_suffixes = ('Kft.', 'Kht.', 'Zrt.', 'Bt.', 'Nyrt.', 'Kkt.') + + def company_suffix(self): + return self.random_element(self.company_suffixes) diff --git a/testbed/joke2k__faker/faker/providers/company/hy_AM/__init__.py b/testbed/joke2k__faker/faker/providers/company/hy_AM/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fcdb10521606dfb4cb0472d5862dcf62094fbdbc --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/hy_AM/__init__.py @@ -0,0 +1,270 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + + formats = ( + '{{first_name}} և {{first_name}} {{company_suffix}}', + '{{last_name} {{company_suffix}}', + '{{last_name}} և {{last_name}} {{company_suffix}}' + '{{last_name}}, {{last_name}} և {{last_name}} {{company_suffix}}', + ) + + company_suffixes = ('ՍՊԸ', 'ՀՁ', 'ՓԲԸ', 'ԲԲԸ', 'Գրուպ', 'Հոլդինգ') + + catch_phrase_words = ( + ('առաջավոր', + 'բարելավված', + 'ավտոմատացված', + 'հավասարակշռված', + 'կենտրոնացված', + 'համատեղելի', + 'կարգավորելի', + 'անհատականացված', + 'ապակենտրոնացված', + 'թվայնացված', + 'տարածված', + 'փոքրացված', + 'ընդլայնված', + 'էրգոնիկ', + 'բացառիկ', + 'երկարացված', + 'լիովին կոնֆիգուրացվող', + 'ֆունկցիոնալ հիմունքներով', + 'հիմնական', + 'հորիզոնական', + 'իրականացված', + 'նորարական', + 'ինտեգրված', + 'ինտուիտիվ', + 'պարտադիր', + 'բազմուղի', + 'բազմաշերտ', + 'ցանցային', + 'բաց կոդով', + 'օպերատիվ', + 'օպտիմալացված', + 'օրգանական', + 'կազմակերպված', + 'կայուն', + 'կենսունակ', + 'ավարտված', + 'բևեռացված', + 'կանխարգելող', + 'ակտիվ', + 'ծրագրավորելի', + 'առաջադիմական', + 'որակով', + 'ռեակտիվ', + 'իրականացված', + 'նվազեցված', + 'դիմացկուն', + 'անխափան', + 'ապահով', + 'համատեղելի', + 'հեշտացված', + 'փոխարկելի', + 'սինխրոնիզացված', + 'ունիվերսալ', + 'ճկուն', + 'վիրտուալ'), + ('3-րդ սերնդի', + '4-րդ սերնդի', + '5-րդ սերնդի', + '6-րդ սերնդի', + 'ասիմետրիկ', + 'ասինխրոն', + 'թողունակությունը վերահսկվող', + 'երկկողմանի', + 'հստակ մտածող', + 'համաձայնեցված', + 'բաղադրյալ', + 'դիդակտիկ', + 'ուղղորդիչ', + 'դիսկրետ', + 'բացահայտ', + 'գլոբալ', + 'բարձր մակարդակի', + 'ամբողջական', + 'միատարր', + 'հիբրիդ', + 'ազդեցիկ', + 'ինտերակտիվ', + 'միջանկյալ', + 'առաջատար', + 'տեղային', + 'լոգիստիկ', + 'սիստեմատիկ', + 'մոդուլային', + 'չեզոք', + 'հաջորդ սերնդի', + 'օբյեկտի վրա հիմնված', + 'օպտիմալ', + 'արմատական', + 'փոխադարձ', + 'ռեգիոնալ', + 'երկրորդական', + 'կայուն', + 'ստատիկ', + 'համակարգված', + 'համակարգային', + 'շոշափելի', + 'երրորդական', + 'անցումային', + 'միատեսակ', + 'լավ մոդուլացված', + 'առանց թերությունների'), + ('կարողություն', + 'մուտք', + 'ադապտեր', + 'ալգորիթմ', + 'միություն', + 'վերլուծիչ', + 'ծրագրային ապահովում', + 'մոտեցում', + 'արխիվ', + 'արհեստական բանականություն', + 'վերաբերմունք', + 'ընդունակություն', + 'կարողություն', + 'մարտահրավեր', + 'գործակցություն', + 'բարդություն', + 'գաղափար', + 'համախմբվածություն', + 'տվյալների բազա', + 'տվյալների պահեստ', + 'սահմանում', + 'իմացություն', + 'կոդավորում', + 'գաղտնագրում', + 'կանխատեսում', + 'հենքային ծրագիր', + 'ֆունկցիա', + 'գործառույթ', + 'գրաֆիկական ինտերֆեյս', + 'սարքային ապահովում', + 'հիերարխիա', + 'հանգույց', + 'ենթակառուցվածք', + 'նախաձեռնություն', + 'ծրագրի ներդրում', + 'հրահանգների հավաքածու', + 'ինտերֆեյս', + 'ինտրանետ', + 'գիտելիքների բազա', + 'տեղական ցանց', + 'մատրիցա', + 'մեթոդաբանություն', + 'միջանկյալ շերտ', + 'միգրացիա', + 'մոդել', + 'կարգավորիչ', + 'մոնիտորինգ', + 'բաց համակարգ', + 'պարադիգմ', + 'պորտալ', + 'գնային կառուցվածք', + 'արդյունավետություն', + 'նախագիծ', + 'ապահովված գիծ', + 'ծրագրային ապահովում', + 'լուծում', + 'ստանդարտացում', + 'ստրատեգիա', + 'կառուցվածք', + 'օպերատիվ խումբ', + 'արտադրողականություն', + 'ժամանակացույց', + 'գործիք', + 'օգտագործում', + 'կայք', + 'աշխատուժ')) + + bsWords = ( + ('իրականացնել', + 'օգտագործել', + 'ինտեգրել', + 'ռացիոնալացնել', + 'օպտիմալացնել', + 'փոխակերպել', + 'ընդգրկել', + 'ակտիվացնել', + 'կազմակերպել', + 'նախագծել', + 'խթանել', + 'ձևափոխել', + 'արտոնել', + 'դրամայնացնել', + 'հեշտացնել', + 'վերցնել', + 'աճեցնել', + 'սինթեզել', + 'առաքել', + 'զբաղվել', + 'առավելագույնի հասցնել', + 'արագացնել', + 'միջնորդել', + 'պատկերացնել', + 'վերափոխել', + 'ընդլայնել', + 'նախաձեռնել', + 'հեղափոխականացնել', + 'առաջացնել', + 'օգտագործել', + 'զարգացնել', + 'արտադրանքի վերածել'), + ('ուղղահայաց', + 'ակտիվ', + 'դիմացկուն', + 'հեղափոխական', + 'առաջատար', + 'նորարարական', + 'ինտուիտիվ', + 'ռազմավարական', + 'էլեկտրոնային', + 'գլոբալ', + 'վիրտուալ', + 'դինամիկ', + 'գրավիչ', + 'ինտերակտիվ', + 'արդյունավետ', + 'ընդարձակելի', + 'պատրաստի', + 'ինտեգրված', + 'ազդեցիկ', + 'անլար', + 'թափանցիկ', + 'հաջորդ սերնդի', + 'ժամանակակից', + 'հարմարեցված', + 'համատարած', + 'ազդեցիկ', + 'ամբողջական', + 'հարուստ', + 'անվճար'), + ('պարադիգմներ', + 'շուկաներ', + 'ենթակառուցվածքներ', + 'պլատֆորմներ', + 'նախաձեռնություններ', + 'ուղիներ', + 'համայնքներ', + 'լուծումներ', + 'պորտալներ', + 'տեխնոլոգիաներ', + 'հարաբերություններ', + 'կառուցվածքներ', + 'ինտերֆեյսներ', + 'շուկաներ', + 'համակարգեր', + 'մոդելներ', + 'օգտագործողներ', + 'սխեմաներ', + 'ցանցեր', + 'ծրագրեր', + 'չափանիշներ', + 'բիզնես', + 'գործառույթներ', + 'փորձառություններ', + 'մեթոդաբանություններ')) diff --git a/testbed/joke2k__faker/faker/providers/company/id_ID/__init__.py b/testbed/joke2k__faker/faker/providers/company/id_ID/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec5d3702356c4576ab3d2289769e75ca551c1ba --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/id_ID/__init__.py @@ -0,0 +1,27 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{company_prefix}} {{last_name}}', + '{{company_prefix}} {{last_name}} {{last_name}}', + '{{company_prefix}} {{last_name}} {{company_suffix}}', + '{{company_prefix}} {{last_name}} {{last_name}} {{company_suffix}}', + ) + + # From http://id.wikipedia.org/wiki/Jenis_badan_usaha + # via + # https://github.com/fzaninotto/faker/blob/master/src/Faker/Provider/id_ID/Company.php + company_prefixes = ( + 'PT', 'CV', 'UD', 'PD', 'Perum', + ) + + # From http://id.wikipedia.org/wiki/Jenis_badan_usaha + # via + # https://github.com/fzaninotto/faker/blob/master/src/Faker/Provider/id_ID/Company.php + company_suffixes = ( + '(Persero) Tbk', 'Tbk', + ) + + def company_prefix(self): + return self.random_element(self.company_prefixes) diff --git a/testbed/joke2k__faker/faker/providers/company/it_IT/__init__.py b/testbed/joke2k__faker/faker/providers/company/it_IT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76150ad9d776bffbb62614811a6a2c14d533d4a5 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/it_IT/__init__.py @@ -0,0 +1,351 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}}-{{last_name}} {{company_suffix}}', + '{{last_name}}, {{last_name}} e {{last_name}} {{company_suffix}}', + ) + + catch_phrase_words = ( + ('Abilità', + 'Access', + 'Adattatore', + 'Algoritmo', + 'Alleanza', + 'Analizzatore', + 'Applicazione', + 'Approccio', + 'Architettura', + 'Archivio', + 'Intelligenza artificiale', + 'Array', + 'Attitudine', + 'Benchmark', + 'Capacità', + 'Sfida', + 'Circuito', + 'Collaborazione', + 'Complessità', + 'Concetto', + 'Conglomerato', + 'Contingenza', + 'Core', + 'Database', + 'Data-warehouse', + 'Definizione', + 'Emulazione', + 'Codifica', + 'Criptazione', + 'Firmware', + 'Flessibilità', + 'Previsione', + 'Frame', + 'framework', + 'Funzione', + 'Funzionalità', + 'Interfaccia grafica', + 'Hardware', + 'Help-desk', + 'Gerarchia', + 'Hub', + 'Implementazione', + 'Infrastruttura', + 'Iniziativa', + 'Installazione', + 'Set di istruzioni', + 'Interfaccia', + 'Soluzione internet', + 'Intranet', + 'Conoscenza base', + 'Matrici', + 'Matrice', + 'Metodologia', + 'Middleware', + 'Migrazione', + 'Modello', + 'Moderazione', + 'Monitoraggio', + 'Moratoria', + 'Rete', + 'Architettura aperta', + 'Sistema aperto', + 'Orchestrazione', + 'Paradigma', + 'Parallelismo', + 'Policy', + 'Portale', + 'Struttura di prezzo', + 'Prodotto', + 'Produttività', + 'Progetto', + 'Proiezione', + 'Protocollo', + 'Servizio clienti', + 'Software', + 'Soluzione', + 'Standardizzazione', + 'Strategia', + 'Struttura', + 'Successo', + 'Sovrastruttura', + 'Supporto', + 'Sinergia', + 'Task-force', + 'Finestra temporale', + 'Strumenti', + 'Utilizzazione', + 'Sito web', + 'Forza lavoro'), + ('adattiva', + 'avanzata', + 'migliorata', + 'assimilata', + 'automatizzata', + 'bilanciata', + 'centralizzata', + 'compatibile', + 'configurabile', + 'cross-platform', + 'decentralizzata', + 'digitalizzata', + 'distribuita', + 'piccola', + 'ergonomica', + 'esclusiva', + 'espansa', + 'estesa', + 'configurabile', + 'fondamentale', + 'orizzontale', + 'implementata', + 'innovativa', + 'integrata', + 'intuitiva', + 'inversa', + 'gestita', + 'obbligatoria', + 'monitorata', + 'multi-canale', + 'multi-laterale', + 'open-source', + 'operativa', + 'ottimizzata', + 'organica', + 'persistente', + 'polarizzata', + 'proattiva', + 'programmabile', + 'progressiva', + 'reattiva', + 'riallineata', + 'ricontestualizzata', + 'ridotta', + 'robusta', + 'sicura', + 'condivisibile', + 'stand-alone', + 'switchabile', + 'sincronizzata', + 'sinergica', + 'totale', + 'universale', + 'user-friendly', + 'versatile', + 'virtuale', + 'visionaria'), + ('24 ore', + '24/7', + 'terza generazione', + 'quarta generazione', + 'quinta generazione', + 'sesta generazione', + 'asimmetrica', + 'asincrona', + 'background', + 'bi-direzionale', + 'biforcata', + 'bottom-line', + 'coerente', + 'coesiva', + 'composita', + 'sensibile al contesto', + 'basta sul contesto', + 'basata sul contenuto', + 'dedicata', + 'didattica', + 'direzionale', + 'discreta', + 'dinamica', + 'eco-centrica', + 'esecutiva', + 'esplicita', + 'full-range', + 'globale', + 'euristica', + 'alto livello', + 'olistica', + 'omogenea', + 'ibrida', + 'impattante', + 'incrementale', + 'intangibile', + 'interattiva', + 'intermediaria', + 'locale', + 'logistica', + 'massimizzata', + 'metodica', + 'mission-critical', + 'mobile', + 'modulare', + 'motivazionale', + 'multimedia', + 'multi-tasking', + 'nazionale', + 'neutrale', + 'nextgeneration', + 'non-volatile', + 'object-oriented', + 'ottima', + 'ottimizzante', + 'radicale', + 'real-time', + 'reciproca', + 'regionale', + 'responsiva', + 'scalabile', + 'secondaria', + 'stabile', + 'statica', + 'sistematica', + 'sistemica', + 'tangibile', + 'terziaria', + 'uniforme', + 'valore aggiunto')) + + bsWords = ( + ('partnerships', + 'comunità', + 'ROI', + 'soluzioni', + 'e-services', + 'nicchie', + 'tecnologie', + 'contenuti', + 'supply-chains', + 'convergenze', + 'relazioni', + 'architetture', + 'interfacce', + 'mercati', + 'e-commerce', + 'sistemi', + 'modelli', + 'schemi', + 'reti', + 'applicazioni', + 'metriche', + 'e-business', + 'funzionalità', + 'esperienze', + 'webservices', + 'metodologie'), + ('implementate', + 'utilizzo', + 'integrate', + 'ottimali', + 'evolutive', + 'abilitate', + 'reinventate', + 'aggregate', + 'migliorate', + 'incentivate', + 'monetizzate', + 'sinergizzate', + 'strategiche', + 'deploy', + 'marchi', + 'accrescitive', + 'target', + 'sintetizzate', + 'spedizioni', + 'massimizzate', + 'innovazione', + 'guida', + 'estensioni', + 'generate', + 'exploit', + 'transizionali', + 'matrici', + 'ricontestualizzate'), + ('valore aggiunto', + 'verticalizzate', + 'proattive', + 'forti', + 'rivoluzionari', + 'scalabili', + 'innovativi', + 'intuitivi', + 'strategici', + 'e-business', + 'mission-critical', + '24/7', + 'globali', + 'B2B', + 'B2C', + 'granulari', + 'virtuali', + 'virali', + 'dinamiche', + 'magnetiche', + 'web', + 'interattive', + 'sexy', + 'back-end', + 'real-time', + 'efficienti', + 'front-end', + 'distributivi', + 'estensibili', + 'mondiali', + 'open-source', + 'cross-platform', + 'sinergiche', + 'out-of-the-box', + 'enterprise', + 'integrate', + 'di impatto', + 'wireless', + 'trasparenti', + 'next-generation', + 'cutting-edge', + 'visionari', + 'plug-and-play', + 'collaborative', + 'olistiche', + 'ricche')) + + company_suffixes = ('SPA', 'e figli', 'Group', 's.r.l.') + + def catch_phrase(self): + """ + :example 'Robust full-range hub' + """ + result = [] + for word_list in self.catch_phrase_words: + result.append(self.random_element(word_list)) + + return " ".join(result) + + def bs(self): + """ + :example 'integrate extensible convergence' + """ + result = [] + for word_list in self.bsWords: + result.append(self.random_element(word_list)) + + return " ".join(result) diff --git a/testbed/joke2k__faker/faker/providers/company/ja_JP/__init__.py b/testbed/joke2k__faker/faker/providers/company/ja_JP/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3968950e50cb5011825bffd61b8540f921f8e84e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/ja_JP/__init__.py @@ -0,0 +1,17 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{company_prefix}}{{last_name}}{{company_category}}', + '{{last_name}}{{company_category}}{{company_prefix}}', + ) + + company_prefixes = ('株式会社', '有限会社', '合同会社') + company_categories = ('水産', '農林', '鉱業', '建設', '食品', '印刷', '電気', 'ガス', '情報', '通信', '運輸', '銀行', '保険') + + def company_prefix(self): + return self.random_element(self.company_prefixes) + + def company_category(self): + return self.random_element(self.company_categories) diff --git a/testbed/joke2k__faker/faker/providers/company/ko_KR/__init__.py b/testbed/joke2k__faker/faker/providers/company/ko_KR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38229ffaa5e6b2db4a497b6e78d99ccc0f4cfa32 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/ko_KR/__init__.py @@ -0,0 +1,378 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{company_suffix}} {{last_name}}{{last_name}}{{last_name}}', + '{{company_suffix}} {{last_name}}', + '{{last_name}}{{last_name}}', + '{{last_name}}{{last_name}}{{last_name}}', + ) + + catch_phrase_words = ( + ('적응된', + '숙련된', + '자동화된', + '안정적인', + '비즈니스 중점적', + '중심이', + '복제된', + '효율적인', + '설정 가능한', + '크로스 그룹', + '크로스 플랫폼', + '사용자 중심의', + '조절 가능한', + '디지털화된', + '출판된', + '다양한', + '낮은', + '강화된', + '인체 공학적인', + '특별한', + '확장된', + '확대된', + '1:1', + '최전방', + '완벽히 설정된', + '함수 기반의', + '미래가 보장된', + '관리된', + '모니터링되는', + '멀티 채널', + '다중 주파수', + '멀티 레이어', + '조직화된', + '객체 기반의', + '공개 아키텍쳐', + '오픈소스', + '최적화된', + '선택적', + '유기농', + '수익에 중점을 둔', + '프로그래밍 가능한', + '진보적인', + '공개 키', + '품질 중심의', + '반동적인', + '재정렬', + '줄어든', + '리버스 엔지니어링된', + '올바른 사이즈의', + '강력한', + '원활한', + '안전한', + '자가 이용 가능한', + '공유 가능한', + '독보적인', + '무결점의', + '변경 가능한', + '동기화', + '융합력있는', + '융합된', + '단체 기반의', + '총', + '트리플 버퍼', + '다용도', + '더 커진', + '업그레이드 가능한', + '더 작아진', + '유저 친화적', + '가상', + '비전 있는'), + ('24시간', + '24/7', + '3세대', + '4세대', + '5세대', + '6세대', + '작동', + '분석중인', + '비대칭', + '비동기', + '고도 기반', + '백그라운드', + '주파수 탐지 가능', + '요약', + '클라이언트 단', + '클라이언트-서버', + '밀착', + '결합된', + '합성물', + '상황에 맞는', + '문맥 기반', + '컨텐츠 기반', + '헌신적', + '교훈적', + '방향', + '분리된', + '다이나믹', + '환경 친화적', + '실행', + '취약점', + '스며든', + '수요 중심', + '장거리', + '글로벌', + '그리드 가능', + '휴리스틱', + '고단계', + '분리형', + '인간자원', + '하이브리드', + '선구적', + '로컬', + '물류', + '최대화', + '결정', + '휴대형', + '모듈형', + '멀티미디어', + '다중 상태', + '멀티 태스킹', + '국가적', + '범국가적', + '중립형', + '다음 세대', + '객체 지향적', + '필수', + '최적화된', + '근본적', + '실시간', + '역수', + '지역적', + '확장', + '보조', + '해답 기반', + '안정적', + '정적', + '가치추가', + '웹 사용 가능', + '잘 모듈화된', + '무관리', + '무해한', + '무관용'), + ('능력', + '접근', + '어댑터', + '알고리즘', + '연합', + '분석', + '어플리케이션', + '접근', + '아키텍쳐', + '아카이브', + '인공지능', + '배열', + '태도', + '벤치마크', + '예산 관리', + '환경', + '생산 능력', + '도전', + '회로', + '융합', + '컨셉', + '축적', + '우연성', + '코어', + '고객 만족', + '데이터베이스', + '정의', + '에뮬레이션', + '인코딩', + '암호화', + '엑스트라넷', + '펌웨어', + '유연성', + '예보', + '프레임', + '프레임워크', + '함수', + '그래픽 인터페이스', + '그룹웨어', + 'GUI', + '하드웨어', + '안내 창구', + '계층', + '허브', + '미디어 정보', + '환경', + '설치과정', + '인터페이스', + '인트라넷', + '지식 기반', + 'LAN', + '미들웨어', + '마이그레이션', + '모델', + '관리자', + '모니터링', + '공개 시스템', + '패러다임', + '정책', + '포탈', + '제품', + '프로젝트', + '프로토콜', + '서비스 창구', + '소프트웨어', + '솔루션', + '보안구역', + '전략', + '구조체', + '성공', + '지원', + '시너지', + '엔진', + '표준', + '시간화', + '공구', + '웹 사이트')) + + bsWords = ( + ('다용도의', + '통합된', + '간소화된', + '최적화된', + '진화된', + '변화된', + '포용적인', + '사용 가능한', + '웅장한', + '재평가된', + '재발명된', + '구조적인', + '강화된', + '장려하는', + '변화무쌍한', + '자율적인', + '선구적인', + '화폐화된', + '전략적인', + '발전하는', + '합성', + '배송', + '혼합된', + '최대화된', + '벤치마킹된', + '신속한', + '깨끗한', + '시각적인', + '창의적인', + '큰', + '폭발하는', + '확장된', + '엔지니어', + '혁명적인', + '제작된', + '취약점의', + '배열적인', + '문화적인'), + ('온라인 쇼핑', + '가치 상승', + '선구적', + '철벽', + '혁명적', + '가변', + '창조적', + '직감', + '전략적', + '전자 비즈니스', + '끈끈한', + '1:1', + '24/7', + '글로벌', + 'B2B', + 'B2C', + '고운', + '가상', + '바이러스성', + '다이나믹', + '24/365', + '고사양', + '킬러', + '자기장', + '최첨단', + '닷컴', + '섹시', + '백 엔드', + '실시간', + '효율적', + '프론트 엔드', + '무결점', + '확장', + '턴키', + '세계급', + '오픈 소스', + '크로스 플랫폼', + '크로스 미디어', + '엔터프라이즈', + '통합', + '강렬한', + '무선', + '투명', + '다음 세대', + '날카로운', + '창의적', + '반투명', + '유비쿼터스', + '플러그 앤 플레이', + '융합', + '강력한', + '강렬한', + '부자'), + ('시너지', + '패러다임', + '마케팅', + '파트너쉽', + '인프라', + '플랫폼', + '채널', + '커뮤니티', + '솔루션', + '전자 서비스', + '포탈', + '기술', + '컨텐츠', + '생산라인', + '관계', + '아키텍쳐', + '인터페이스', + '전자시장', + '전자화폐', + '시스템', + '주파수', + '모델', + '어플리케이션', + '사용자들', + '스키마', + '네트웍스', + '앱', + '매트릭스', + '전자 비즈니스', + '경험', + '웹서비스', + '방법론')) + + company_suffixes = ('(주)', '주식회사', '(유)', '유한회사') + + def catch_phrase(self): + """ + :example 'Robust full-range hub' + """ + result = [] + for word_list in self.catch_phrase_words: + result.append(self.random_element(word_list)) + + return " ".join(result) + + def bs(self): + """ + :example 'integrate extensible convergence' + """ + result = [] + for word_list in self.bsWords: + result.append(self.random_element(word_list)) + + return " ".join(result) diff --git a/testbed/joke2k__faker/faker/providers/company/nl_NL/__init__.py b/testbed/joke2k__faker/faker/providers/company/nl_NL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b70b274f3e6e55f148dc9d7aa26a1fcfef2565b --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/nl_NL/__init__.py @@ -0,0 +1,106 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} & {{last_name}}', + '{{company_prefix}} {{last_name}}', + '{{large_company}}', + ) + + company_prefixes = ( + 'Stichting', 'Koninklijke', 'Royal', + ) + + company_suffixes = ( + 'BV', 'NV', 'Groep', + ) + + # Source: https://www.mt.nl/management/reputatie/mt-500-2018-de-lijst/559930 + large_companies = ( + 'Shell', 'Coolblue', 'ASML', 'Ahold', 'Tata Steel', 'KLM', 'Bol.com', 'BP Nederland', 'De Efteling', 'Eneco', + 'De Persgroep', 'ING', 'Royal HaskoningDHV', 'Randstad', 'Google', 'Ikea', 'Rockwool', 'BAM', 'Achmea', + 'Damen Shipyard', 'ABN Amro', 'Remeha Group', 'TenneT', 'Coca-Cola', 'Van Leeuwen Buizen', 'Wavin', 'Rabobank', + 'AkzoNobel', 'Arcadis', 'AFAS', 'Cisco', 'DAF Trucks', 'DHL', 'Hanos', 'Boon Edam', 'BMW Nederland', + 'The Greenery', 'Dutch Flower Group', 'Koninklijke Mosa', 'Yacht', 'Rituals', 'Microsoft', 'Esso', + '3W Vastgoed', 'Deloitte', 'Corio', 'Voortman Steel Group', 'Agrifirm', 'Makro Nederland', + 'Nederlandse Publieke Omroep', 'De Alliantie', 'Heijmans', 'McDonalds', 'ANWB', 'Mediamarkt', 'Kruidvat' + 'Van Merksteijn Steel', 'Dura Vermeer', 'Alliander', 'Unilever', 'Enexis', 'Berenschot', 'Jumbo', + 'Technische Unie', 'Havenbedrijf Rotterdam', 'Ballast Nedam', 'RTL Nederland', 'Talpa Media', + 'Blauwhoed Vastgoed', 'DSM', 'Ymere', 'Witteveen+Bos', 'NS', 'Action', 'FloraHolland', 'Heineken', 'Nuon', 'EY', + 'Dow Benelux', 'Bavaria', 'Schiphol', 'Holland Casino', 'Binck bank', 'BDO', 'HEMA', 'Alphabet Nederland', + 'Croon Elektrotechniek', 'ASR Vastgoed ontwikkeling', 'PwC', 'Mammoet', 'KEMA', 'IBM', 'A.S. Watson', + 'KPMG', 'VodafoneZiggo', 'YoungCapital', 'Triodos Bank', 'Aviko', 'AgruniekRijnvallei', 'Heerema', 'Accenture', + 'Aegon', 'NXP', 'Breman Installatiegroep', 'Movares Groep', 'Q-Park', 'FleuraMetz', 'Sanoma', + 'Bakker Logistiek', 'VDL Group', 'Bayer', 'Boskalis', 'Nutreco', 'Dell', 'Brunel', 'Exact', 'Manpower', + 'Essent', 'Canon', 'ONVZ Zorgverzekeraar', 'Telegraaf Media Group', 'Nationale Nederlanden', 'Andus Group', + 'Den Braven Group', 'ADP', 'ASR', 'ArboNed', 'Plieger', 'De Heus Diervoeders', 'USG People', 'Bidvest Deli XL', + 'Apollo Vredestein', 'Tempo-Team', 'Trespa', 'Janssen Biologics', 'Starbucks', 'PostNL', 'Vanderlande', + 'FrieslandCampina', 'Constellium', 'Huisman', 'Abbott', 'Koninklijke Boom Uitgevers', 'Bosch Rexroth', 'BASF', + 'Audax', 'VolkerWessels', 'Hunkemöller', 'Athlon Car Lease', 'DSW Zorgverzekeraar', 'Mars', + 'De Brauw Blackstone Westbroek', 'NDC Mediagroep', 'Bluewater', 'Stedin', 'Feenstra', + 'Wuppermann Staal Nederland', 'Kramp', 'SABIC', 'Iv-Groep', 'Bejo Zaden', 'Wolters Kluwer', 'Nyrstar holding', + 'Adecco', 'Tauw', 'Robeco', 'Eriks', 'Allianz Nederland Groep', 'Driessen', 'Burger King', 'Lekkerland', + 'Van Lanschot', 'Brocacef', 'Bureau Veritas', 'Relx', 'Pathé Bioscopen', 'Bosal', + 'Ardagh Group', 'Maandag', 'Inalfa', 'Atradius', 'Capgemini', 'Greenchoice', 'Q8 (Kuwait Petroleum Europe)', + 'ASM International', 'Van der Valk', 'Delta Lloyd', 'GlaxoSmithKline', 'ABB', + 'Fabory, a Grainger company', 'Veen Bosch & Keuning Uitgeversgroep', 'CZ', 'Plus', 'RET Rotterdam', + 'Loyens & Loeff', 'Holland Trading', 'Archer Daniels Midland Nederland', 'Ten Brinke', 'NAM', 'DAS', + 'Samsung Electronics Benelux', 'Koopman International', 'TUI', 'Lannoo Meulenhoff', 'AC Restaurants', + 'Stage Entertainment', 'Acer', 'HDI Global SE', 'Detailresult', 'Nestle', 'GVB Amsterdam', 'Dekamarkt', 'Dirk', + 'MSD', 'Arriva', 'Baker Tilly Berk', 'SBM Offshore', 'TomTom', 'Fujifilm', 'B&S', 'BCC', 'Gasunie', + 'Oracle Nederland', 'Astellas Pharma', 'SKF', 'Woningstichting Eigen Haard', 'Rijk Zwaan', 'Chubb', 'Fugro', + 'Total', 'Rochdale', 'ASVB', 'Atos', 'Acomo', 'KPN', 'Van Drie Group', 'Olympia uitzendbureau', + 'Bacardi Nederland', 'JMW Horeca Uitzendbureau', 'Warner Bros/Eyeworks', 'Aalberts Industries', 'SNS Bank', + 'Amtrada Holding', 'VGZ', 'Grolsch', 'Office Depot', 'De Rijke Group', 'Bovemij Verzekeringsgroep', + 'Coop Nederland', 'Eaton Industries', 'ASN', 'Yara Sluiskil', 'HSF Logistics', 'Fokker', 'Deutsche Bank', + 'Sweco', 'Univé Groep', 'Koninklijke Wagenborg', 'Strukton', 'Conclusion', 'Philips', 'In Person', + 'Fluor', 'Vroegop-Windig', 'ArboUnie', 'Centraal Boekhuis', 'Siemens', 'Connexxion', 'Fujitsu', 'Consolid', + 'AVR Afvalverwerking', 'Brabant Alucast', 'Centric', 'Havensteder', 'Novartis', 'Booking.com', 'Menzis', + 'Frankort & Koning Groep', 'Jan de Rijk', 'Brand Loyalty Group', 'Ohra Verzekeringen', 'Terberg Group', + 'Cloetta', 'Holland & Barrett', 'Enza Zaden', 'VION', 'Woonzorg Nederland', + 'T-Mobile', 'Crucell', 'NautaDutilh', 'BNP Paribas', 'NIBC Bank', 'VastNed', 'CCV Holland', + 'IHC Merwede', 'Neways', 'NSI N.V.', 'Deen', 'Accor', 'HTM', 'ITM Group', 'Ordina', 'Dümmen Orange', 'Optiver', + 'Zara', 'L\'Oreal Nederland B.V.', 'Vinci Energies', 'Suit Supply Topco', 'Sita', 'Vos Logistics', + 'Altran', 'St. Clair', 'BESI', 'Fiat Chrysler Automobiles', 'UPS', 'Jacobs', 'Emté', 'TBI', 'De Bijenkorf', + 'Aldi Nederland', 'Van Wijnen', 'Vitens', 'De Goudse Verzekeringen', 'SBS Broadcasting', + 'Sandd', 'Omron', 'Sogeti', 'Alfa Accountants & Adviseurs', 'Harvey Nash', 'Stork', 'Glencore Grain', + 'Meijburg & Co', 'Honeywell', 'Meyn', 'Ericsson Telecommunicatie', 'Hurks', 'Mitsubishi', 'GGN', + 'CGI Nederland', 'Staples Nederland', 'Denkavit International', 'Ecorys', 'Rexel Nederland', + 'A. Hakpark', 'DuPont Nederland', 'CBRE Group', 'Bolsius', 'Marel', 'Metro', + 'Flynth Adviseurs en Accountants', 'Kropman Installatietechniek', 'Kuijpers', 'Medtronic', 'Cefetra', + 'Simon Loos', 'Citadel Enterprises', 'Intergamma', 'Ceva Logistics', 'Beter Bed', 'Subway', 'Gamma', 'Karwei' + 'Varo Energy', 'APM Terminals', 'Center Parcs', 'Brenntag Nederland', 'NFI', 'Hoogvliet', + 'Van Gansewinkel', 'Nedap', 'Blokker', 'Perfetti Van Melle', 'Vestia', 'Kuehne + Nagel Logistics', + 'Rensa Group', 'NTS Group', 'Joh. Mourik & Co. Holding', 'Mercedes-Benz', 'DIT Personeel', 'Verkade', + 'Hametha', 'Vopak', 'IFF', 'Pearle', 'Mainfreight', 'De Jong & Laan', 'DSV', 'P4People', 'Mazars', 'Cargill', + 'Ten Brinke Groep', 'Alewijnse', 'Agio Cigars', 'Peter Appel Transport', 'Syngenta', 'Avery Dennison', + 'Accon AVM', 'Vitol', 'Vermaat Groep', 'BMC', 'Alcatel-Lucent', 'Maxeda DIY', 'Equens', + 'Van Gelder Groep', 'Emerson Electric Nederland', 'Bakkersland', 'Specsavers', 'E.On', 'Landal Greenparks', + 'IMC Trading', 'Barentz Group', 'Epson', 'Raet', 'Van Oord', 'Thomas Cook Nederland', 'SDU uitgevers', + 'Nedschroef', 'Linde Gas', 'Ewals Cargo Care', 'Theodoor Gilissen', 'TMF Group', 'Cornelis Vrolijk', + 'Jan Linders Supermarkten', 'SIF group', 'BT Nederland', 'Kinepolis', 'Pink Elephant', + 'General Motors Nederland', 'Carlson Wagonlit', 'Bruna', 'Docdata', 'Schenk Tanktransport', 'WPG', 'Peak-IT', + 'Martinair', 'Reesink', 'Elopak Nederland', 'Fagron N.V.', 'OVG Groep', 'Ford Nederland', 'Multi Corporation', + 'Simac', 'Primark', 'Tech Data Nederland', 'Vleesgroothandel Zandbergen', 'Raben Group', 'Farm Frites', + 'Libéma', 'Caldic', 'Portaal', 'Syntus', 'Jacobs DE', 'Stena Line', 'The Phone House', 'Interfood Group', + 'Thales', 'Teva Pharmaceuticals', 'RFS Holland', 'Aebi Schmidt Nederland', + 'Rockwell Automation Nederland', 'Engie Services', 'Hendrix Genetics', 'Qbuzz', 'Unica', + '2SistersFoodGroup', 'Ziut', 'Munckhof Groep', 'Spar Holding', 'Samskip', 'Continental Bakeries', 'Sligro', + 'Merck', 'Foot Locker Europe', 'Unit4', 'PepsiCo', 'Sulzer', 'Tebodin', 'Value8', 'Boels', + 'DKG Groep', 'Bruynzeel Keukens', 'Janssen de Jong Groep', 'ProRail', 'Solid Professionals', 'Hermes Partners', + ) + + def large_company(self): + """ + :example: 'Bol.com' + """ + return self.random_element(self.large_companies) + + def company_prefix(self): + """ + :example 'Stichting' + """ + return self.random_element(self.company_prefixes) diff --git a/testbed/joke2k__faker/faker/providers/company/no_NO/__init__.py b/testbed/joke2k__faker/faker/providers/company/no_NO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c86b9bf805df73e323a8680ce3fa6f9af72fa510 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/no_NO/__init__.py @@ -0,0 +1,16 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = [ + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{company_suffix}}', + '{{last_name}}-{{last_name}} {{company_suffix}}', + '{{last_name}}, {{last_name}} og {{last_name}}', + '{{last_name}}-{{last_name}}', + ] + + company_suffixes = [ + 'Gruppen', 'AS', 'ASA', 'BA', 'RFH', 'og Sønner', '& co.', + ] diff --git a/testbed/joke2k__faker/faker/providers/company/pl_PL/__init__.py b/testbed/joke2k__faker/faker/providers/company/pl_PL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..23e222357d1830e68183b882faa0c69195f5f025 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/pl_PL/__init__.py @@ -0,0 +1,132 @@ +from .. import Provider as CompanyProvider + + +def regon_checksum(digits): + """ + Calculates and returns a control digit for given list of digits basing on REGON standard. + """ + weights_for_check_digit = [8, 9, 2, 3, 4, 5, 6, 7] + check_digit = 0 + + for i in range(0, 8): + check_digit += weights_for_check_digit[i] * digits[i] + + check_digit %= 11 + + if check_digit == 10: + check_digit = 0 + + return check_digit + + +def local_regon_checksum(digits): + """ + Calculates and returns a control digit for given list of digits basing on local REGON standard. + """ + weights_for_check_digit = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8] + check_digit = 0 + + for i in range(0, 13): + check_digit += weights_for_check_digit[i] * digits[i] + + check_digit %= 11 + + if check_digit == 10: + check_digit = 0 + + return check_digit + + +def company_vat_checksum(digits): + """ + Calculates and returns a control digit for given list of digits basing on NIP standard. + """ + weights_for_check_digit = [6, 5, 7, 2, 3, 4, 5, 6, 7] + check_digit = 0 + + for i in range(0, 9): + check_digit += weights_for_check_digit[i] * digits[i] + + check_digit %= 11 + + return check_digit + + +class Provider(CompanyProvider): + + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}}-{{last_name}} {{company_suffix}}', + '{{company_prefix}} {{last_name}}', + '{{company_prefix}} {{last_name}} {{company_suffix}}', + '{{company_prefix}} {{last_name}}-{{last_name}} {{company_suffix}}', + ) + + company_prefixes = ('Grupa', 'Spółdzielnia', 'Stowarzyszenie', 'Fundacja', 'PPUH', 'FPUH', 'Gabinety') + + company_suffixes = ('Sp. z o.o.', 'S.A.', 'Sp. z o.o. Sp.k.', 'Sp.j.', 's.c.', 'Sp.k.', 'i syn s.c.') + + def company_prefix(self): + """ + :example 'Grupa' + """ + return self.random_element(self.company_prefixes) + + def regon(self): + """ + Returns 9 character Polish National Business Registry Number, + Polish: Rejestr Gospodarki Narodowej - REGON. + + https://pl.wikipedia.org/wiki/REGON + """ + voivodeship_number = self.random_int(0, 49) * 2 + 1 + regon_digits = [int(voivodeship_number / 10), voivodeship_number % 10] + + for _ in range(6): + regon_digits.append(self.random_digit()) + + regon_digits.append(regon_checksum(regon_digits)) + + return ''.join(str(digit) for digit in regon_digits) + + def local_regon(self): + """ + Returns 14 character Polish National Business Registry Number, + local entity number. + + https://pl.wikipedia.org/wiki/REGON + """ + regon_digits = [int(digit) for digit in list(self.regon())] + + for _ in range(4): + regon_digits.append(self.random_digit()) + + regon_digits.append(local_regon_checksum(regon_digits)) + + return ''.join(str(digit) for digit in regon_digits) + + def company_vat(self): + """ + Returns 10 character tax identification number, + Polish: Numer identyfikacji podatkowej. + + https://pl.wikipedia.org/wiki/NIP + """ + vat_digits = [] + + for _ in range(3): + vat_digits.append(self.random_digit_not_null()) + + for _ in range(6): + vat_digits.append(self.random_digit()) + + check_digit = company_vat_checksum(vat_digits) + + # in this case we must generate a tax number again, because check_digit + # cannot be 10 + if check_digit == 10: + return self.company_vat() + + vat_digits.append(check_digit) + + return ''.join(str(digit) for digit in vat_digits) diff --git a/testbed/joke2k__faker/faker/providers/company/pt_BR/__init__.py b/testbed/joke2k__faker/faker/providers/company/pt_BR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42d7fad4a59c814ca123a0adfe0eab69d8afcf23 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/pt_BR/__init__.py @@ -0,0 +1,107 @@ +from .. import Provider as CompanyProvider + + +def company_id_checksum(digits): + digits = list(digits) + weights = 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 + + dv = sum(w * d for w, d in zip(weights[1:], digits)) + dv = (11 - dv) % 11 + dv = 0 if dv >= 10 else dv + digits.append(dv) + + dv2 = sum(w * d for w, d in zip(weights, digits)) + dv2 = (11 - dv2) % 11 + dv2 = 0 if dv2 >= 10 else dv2 + digits.append(dv2) + + return digits[-2:] + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + '{{last_name}}', + ) + + catch_phrase_formats = ( + '{{catch_phrase_noun}} {{catch_phrase_verb}} {{catch_phrase_attribute}}', ) + + nouns = ( + 'a segurança', + 'o prazer', + 'o conforto', + 'a simplicidade', + 'a certeza', + 'a arte', + 'o poder', + 'o direito', + 'a possibilidade', + 'a vantagem', + 'a liberdade') + + verbs = ( + 'de conseguir', + 'de avançar', + 'de evoluir', + 'de mudar', + 'de inovar', + 'de ganhar', + 'de atingir seus objetivos', + 'de concretizar seus projetos', + 'de realizar seus sonhos') + + attributes = ( + 'de maneira eficaz', + 'mais rapidamente', + 'mais facilmente', + 'simplesmente', + 'com toda a tranquilidade', + 'antes de tudo', + 'naturalmente', + 'sem preocupação', + 'em estado puro', + 'com força total', + 'direto da fonte', + 'com confiança') + + company_suffixes = ('S/A', 'S.A.', 'Ltda.', '- ME', '- EI', 'e Filhos') + + def catch_phrase_noun(self): + """ + Returns a random catch phrase noun. + """ + return self.random_element(self.nouns) + + def catch_phrase_attribute(self): + """ + Returns a random catch phrase attribute. + """ + return self.random_element(self.attributes) + + def catch_phrase_verb(self): + """ + Returns a random catch phrase verb. + """ + return self.random_element(self.verbs) + + def catch_phrase(self): + """ + :example 'a segurança de evoluir sem preocupação' + """ + pattern = self.random_element(self.catch_phrase_formats) + catch_phrase = self.generator.parse(pattern) + catch_phrase = catch_phrase[0].upper() + catch_phrase[1:] + return catch_phrase + + def company_id(self): + digits = self.random_sample(range(10), 8) + [0, 0, 0, 1] + digits += company_id_checksum(digits) + return ''.join(str(d) for d in digits) + + def cnpj(self): + digits = self.company_id() + return '{}.{}.{}/{}-{}'.format(digits[:2], digits[2:5], digits[5:8], + digits[8:12], digits[12:]) diff --git a/testbed/joke2k__faker/faker/providers/company/pt_PT/__init__.py b/testbed/joke2k__faker/faker/providers/company/pt_PT/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93ab7959daf90293aedc6e7079fbf6fccba49294 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/pt_PT/__init__.py @@ -0,0 +1,34 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + '{{last_name}}', + ) + + catch_phrase_formats = ( + '{{catch_phrase_noun}} {{catch_phrase_verb}} {{catch_phrase_attribute}}', ) + + nouns = ( + 'a segurança', 'o prazer', 'o conforto', 'a simplicidade', 'a certeza', + 'a arte', 'o poder', 'o direito', 'a possibilidade', 'a vantagem', + 'a liberdade', + ) + + verbs = ( + 'de conseguir', 'de avançar', 'de evoluir', 'de mudar', 'de inovar', + 'de ganhar', 'de atingir os seus objetivos', + 'de concretizar seus projetos', 'de realizar seus sonhos', + ) + + attributes = ( + 'de maneira eficaz', 'mais rapidamente', 'mais facilmente', + 'simplesmente', 'com toda a tranquilidade', 'antes de tudo', + 'naturalmente', 'sem preocupação', 'em estado puro', 'com força total', + 'direto da fonte', 'com confiança', + ) + + company_suffixes = ('S/A', 'S.A.', 'Lda.', 'e Filhos') diff --git a/testbed/joke2k__faker/faker/providers/company/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/company/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91bcbb0fdc8f804b34a4ee815ea710a89668b4f8 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/ru_RU/__init__.py @@ -0,0 +1,323 @@ +from faker.utils.datetime_safe import datetime + +from .. import Provider as CompanyProvider + + +def calculate_checksum(value): + factors = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8][-len(value):] + check_sum = 0 + for number, factor in zip(value, factors): + check_sum += int(number) * factor + + return str((check_sum % 11) % 10) + + +class Provider(CompanyProvider): + formats = ( + '{{company_prefix}} «{{last_name}}»', + '{{company_prefix}} «{{last_name}} {{last_name}}»', + '{{company_prefix}} «{{last_name}}-{{last_name}}»', + '{{company_prefix}} «{{last_name}}, {{last_name}} и {{last_name}}»', + '{{last_name}} {{company_suffix}}', + '{{large_company}}', + ) + + company_prefixes = ( + 'РАО', 'АО', 'ИП', 'НПО', 'ЗАО', 'ООО', 'ОАО', + ) + + company_suffixes = ( + 'Инк', 'Инкорпорэйтед', 'и партнеры', 'Групп', 'Лтд', 'Лимитед', + ) + + # Source: https://www.rbc.ru/rbc500/ + large_companies = ( + 'Газпром', 'ЛУКОЙЛ', 'Роснефть', 'Сбербанк России', 'Российские железные дороги', 'Ростех', 'Сургутнефтегаз', + 'X5 Retail Group', 'ВТБ', 'Магнит', 'САФМАР', 'Росатом', 'Российские сети', 'Интер РАО', 'Транснефть', + 'Татнефть', 'НОВАТЭК', 'Евраз', 'АФК Система', 'En +', 'НЛМК', 'Норникель', 'ГК Мегаполис', 'Газпромбанк', + 'Русал', 'Аэрофлот — Российские авиалинии', 'Сибур Холдинг', 'Северсталь', 'СУЭК', 'ММК', 'Группа УГМК', + 'Мобильные телесистемы', 'Металлоинвест', 'Лента', 'Объединенная авиастроительная корпорация', 'РусГидро', + 'Сахалин Энерджи', 'Т Плюс', 'Группа М.Видео-Эльдорадо', 'Еврохим', 'ВымпелКом', + 'Банковский холдинг Альфа-банка', 'Объединенная судостроительная корпорация', 'МегаФон', 'Ростелеком', 'ТМК', + 'Славнефть', 'Тойота Мотор (Toyota)', 'Мечел', 'Автотор холдинг', 'Стройгазмонтаж', 'Дж.Т.И. Россия (JTI)', + 'Торговая сеть Красное и Белое', 'АК Алроса', 'Дикси Групп', 'ВЭБ.РФ', 'ФМСМ (PMI)', 'Фольксваген Груп Рус', + 'АвтоВАЗ', 'Леруа Мерлен Восток (Leroi Merlin)', 'Ашан (Auchan)', 'Россельхозбанк', 'ДНС Групп', + 'ГК ТНС энерго', 'Протек', 'Группа компаний ПИК', 'Объединенная двигателестроительная корпорация', + 'Независимая нефтегазовая компания', 'Merlion', 'ФосАгро', 'КМР и СНГ (KIA)', 'Катрен', 'Банк ФК Открытие', + 'Корпорация Тактическое ракетное вооружение', 'Группа Рольф', 'ТАИФ-НК', 'Трансмашхолдинг', + 'Метро Кэш энд Керри (Metro Cash & Carry)', 'Мостотрест', 'СОГАЗ', 'Эппл Рус (Apple)', 'Арктикгаз', + 'Нижнекамскнефтехим', '«Томскнефть» ВНК', 'Зарубежнефть', 'ЕвроСибЭнерго', 'Вертолеты России', 'Группа ГАЗ', + 'Почта России', 'МУМТ (BAT)', 'Стройтранснефтегаз', 'КамАЗ', 'ФК Пульс', 'Полюс', 'Хендэ Мотор СНГ (Hyundai)', + 'S7 Group', 'Ямал СПГ', 'Группа Содружество', 'ЧТПЗ', 'Иркутская нефтяная компания', 'Русснефть', + 'Национальная компьютерная корпорация', 'Мерседес-Бенц Рус (Mercedes-Benz)', 'Русэнергосбыт', 'ОМК', + 'Уралкалий', 'ГК Ташир', 'Компания Газ-Альянс', 'ФортеИнвест', 'Группа Мэйджор', 'Российская электроника', + 'ГК СНС', 'Сибирский антрацит', "Группа О'кей", 'Мосинжпроект', 'UCL Holding', 'Группа Илим', + 'Московский кредитный банк', 'Группа Синара', 'Нефтиса', 'Объединенная компания Связной — Евросеть', + 'Группа ЛСР', 'Т2 РТК Холдинг', 'НЗНП', 'АльфаСтрахование', 'Ланит', 'НПК Уралвагонзавод', + 'Рено Россия (Renault)', 'Удмуртнефть', 'Нестле Россия (Nestle)', 'Райффайзенбанк (Raiffeisen)', + 'Техкомпания Хуавэй (Huawei)', 'КДВ Групп', 'Яндекс', 'Мессояханефтегаз', 'БМВ Русланд Трейдинг (BMW)', + 'Салым Петролеум', 'Данон (Danone)', 'ЮниКредит Банк (UniCredit)', 'ТД Риф', 'Мираторг', 'Группа Волга-Днепр', + 'Вайлдберриз', 'Московский метрополитен', 'Полиметалл', 'Группа РЕСО', 'Пепсико холдингс', 'ГК Эфко', + 'СДС-Уголь', 'ЛокоТех', 'ГК Автомир', 'Совкомбанк', 'ФСК Лидер', 'Марс (Mars)', 'Детский мир', + 'Группа НПФ Благосостояние', 'Госкорпорация по ОрВД', 'Трансойл', 'ОХК Уралхим', + 'Каспийский трубопроводный консорциум-Р', 'Тинькофф Банк', 'Fix Price', 'Промсвязьбанк', 'Акрон', + 'Спортмастер', 'Проктер Энд Гэмбл. Дистрибьюторская компания (Procter & Gamble)', + 'Eurasia Drilling Company', 'Группа Черкизово', 'ИКЕА Дом (INGKA)', 'Славянск Эко', 'Корпорация ВСМПО-АВИСМА', + 'Росбанк (Societe General)', 'Монетка', 'Стройсервис', 'ГК Транстехсервис', 'Совкомфлот', 'ВСК', + 'СБСВ-Ключавто', 'Ингосстрах', 'Сэтл групп', 'Гиперглобус (Bruch-Beteiligungs)', 'Технониколь', + 'Металлсервис', 'Нефтехимсервис', 'Промышленно-металлургический холдинг', + 'Урало-Сибирская металлургическая компания', 'Мария-Ра', 'Globaltrans', 'Кубанская нефтегазовая компания', + 'Авиакомпания ЮТэйр', 'НПФ Газфонд пенсионные накопления', 'Русагро', "Л'Этуаль", 'ЛГ Электроникс Рус (LG)', + 'Каргилл (Cargill)', 'ВАД', 'Астон', 'Уральские авиалинии', 'Сталепромышленная компания', 'НИПИ НГ Петон', + 'Бристоль', 'Уралвтормет', 'Нефтетранссервис', 'Казаньоргсинтез', 'Газпром бурение', 'ГК Агро-Белогорье', + 'Фортум (Fortum)', 'ПК Балтика (Carlsbergfondet)', 'Авилон АГ', 'Шелл Нефть (Shell)', 'Юнипро (Uniper)', + 'Технологии машиностроения (Техмаш)', 'НПК Объединенная вагонная компания', 'Велесстрой', 'ТД Интерторг', + 'Юнилевер Русь (Unilever)', 'Солид-товарные рынки', 'Вольво Восток (AB Volvo)', 'Энел Россия', 'Марвел КТ', + 'ГК Эталон', 'Металлокомплект-М', 'Группа Ренессанс Страхование', 'Военторг', 'Nordgold', 'Сибуглемет', + 'Акционерный банк Россия', 'ДОМ.РФ', 'Форд Соллерс Холдинг', 'ИКЕА Торг (INGKA)', 'Макдоналдc (McDonald`s)', + 'Кузбасская топливная компания', 'Хенкель Рус (Henkel)', 'Дон-Строй Инвест', + 'Главное управление обустройства войск (ГУОВ)', 'СК Росгосстрах', 'Кока-Кола Эйчбиси Евразия (Coca-Cola)', + 'Хоум Кредит энд Финанс Банк (PPF)', 'Гленкор Агро Мзк (Firada)', 'Mail.Ru Group', 'Монди СЛПК (Mondi)', + 'НПО Алмаз', 'ММС Рус (Mitsubishi Motors)', 'Объединенные кондитеры', 'Комацу СНГ (Komatsu)', + 'Национальная медиа группа', 'Агентство по страхованию вкладов (АСВ)', 'Татэнергосбыт', 'Куйбышевазот', + 'Азбука вкуса', 'Трансбункер', 'Башкирская содовая компания', 'Инвестнефтетрейд', 'Inventive Retail Group', + 'Самсунг Электроникс Рус Калуга (Samsung)', 'Крокус', 'Гугл (Google)', 'АСЦ-Холдинг', + 'Новороссийский морской торговый порт', 'Швабе', 'Русская медная компания', 'Евроцемент груп', 'Мосводоканал', + 'Международный аэропорт Шереметьево', 'Сегежа', 'Р-Фарм', 'Фармстандарт', 'Ростсельмаш', + 'Транспортная группа FESCO', 'Компания Адамас', 'Метафракс', 'Джонсон & Джонсон (Johnson & Johnson)', + 'Softline', 'Ягуар ленд ровер', 'Байер', 'Эркафарм', 'Фармперспектива', 'Банк Уралсиб', 'ВО Машиноимпорт', + 'Кордиант', 'Новосталь', 'ВкусВилл', "Л'Ореаль (L'Oreal)", 'DDS', 'ТОАЗ', 'Банк Санкт-Петербург', + 'Группа агропредприятий Ресурс', 'Ярче!', 'Ренейссанс Констракшн (Ronesans Holding Anonim Sirketi)', + 'Санофи Россия (Sanofi)', 'Группа ГМС', 'Северный ветер', 'БСС', 'Скания-Русь (Scania)', 'ГК Фаворит Моторс', + 'Группа РТК', 'Фармкомплект', 'Нокиан Шина (Nokian)', 'ДСК Автобан', 'Омега Групп', 'Квадра', 'Roust', + 'ГК Невада (Самбери)', 'Восточный экспресс банк', 'Верисел-трейдинг', 'Гознак', + 'Фирма Агрокомплекс им. Ткачева', 'Банк Русский стандарт', 'Мазда Мотор Рус (Mazda)', 'Группа Газфонд', + 'СТД Петрович', 'Беркс', 'Кари', 'Арконик СМЗ', 'Мон Дэлис (Mondelez)', 'Комус', 'Группа Агат', + 'Великолукский мясокомбинат', 'Верный', 'СДС Азот', 'М Фэшн', 'Белгранкорм-холдинг', 'Группа Нэфис', + 'ФГ Будущее', 'Глория Джинс', 'Билла (Rewe)', 'Государственная транспортная лизинговая компания', + 'ФК Гранд Капитал', 'ЭС', 'Компания Металл Профиль', 'ГК Орими Трэйд', 'ГСЛ', + 'Интернешнл Пейпер (International Paper)', 'Лаборатория Касперского', 'ПСМА Рус', 'Аптечная сеть 36,6', + 'Тетра Пак (Tetra Pak)', 'Центральная пригородная пассажирская компания', 'Самараэнерго', 'Азур Эйр', + 'Командор-Холдинг', 'Белуга Групп', 'ТД БелАЗ', 'Мосгортранс', 'Спар Миддл Волга', + 'Холдинг Транспортные компоненты', 'Московский аэропорт Домодедово', 'Рулог (Havi)', 'Эйч Энд Эм (H&M)', + 'Концерн Автоматика', 'Татэнерго', 'Трубная грузовая компания', 'Комос Групп', 'Первая тяжеловесная компания', + 'ОМПК', 'НК Дулисьма', 'Ачимгаз', 'Новосибирскэнергосбыт', 'Компания СИМ-Авто', 'Ситибанк', 'Остин', + 'Адидас (Adidas)', 'Ферреро Руссия (Ferrero)', 'Пермэнергосбыт', 'РКК Энергия', 'Свеза', 'Росжелдорпроект', + 'Мазда Соллерс Мануфэкчуринг Рус', 'БСХ Бытовые приборы (BSH Hausgerate)', 'Московская биржа ММВБ-РТС', + 'Русэнергоресурс', 'Компания Луис Дрейфус Восток (Louis Dreyfus)', 'ЭР-Телеком Холдинг', 'Соллерс', + 'Объединенная энергетическая компания', 'Уральские локомотивы', 'ТМК Чермет', 'Загорский трубный завод', + 'Элко Рус (Elko)', 'Архангельский ЦБК', 'Мособлгаз', 'ДК Рус', 'Энергосбытовая компания Восток', + 'ГКНПЦ им. М.В.Хруничева', 'Металлоторг', 'Агросила Групп', 'Ман Трак Энд Бас Рус (Volkswagen)', + 'Петербургский метрополитен', 'ТГК-2', 'Концерн Титан-2', 'Ренейссанс Хэви Индастрис Ronesans Endustri', + 'Бургер Рус (Burger King)', 'Ozon', 'Сони Электроникс (Sony)', 'Продо', 'Продимекс-Холдинг', 'АвтоГермес', + 'Railgo', 'Новотранс', 'Новикомбанк', 'Рив Гош', 'Сибирская горно-металлургическая компания', + 'Сименс (Siemens)', 'Лига ставок', 'Банк Ак Барс', 'Группа Полипластик', 'Водоканал Санкт-Петербурга', + 'РэйлАльянс', 'Российская телевизионная и радиовещательная сеть', 'Зерно-трейд', 'Ренессанс Кредит', + 'Роберт Бош (Robert Bosch)', 'ВО Промсырьеимпорт', 'САП СНГ (SAP)', 'А Групп', 'Приосколье', 'Зара СНГ (Zara)', + 'Модум-транс', 'Эбботт лэбораториз (Abbott Laboratories)', 'Группа Магнезит', 'Газпром автоматизация', + 'Газэнергосервис', 'Независимая энергосбытовая компания Краснодарского края', 'Группа ЭПМ', 'Минудобрения', + 'Либхерр-Русланд (Liebherr)', 'Восточная техника (Vost-Tech)', 'Первый канал', 'ГМК Сплав', 'ГК Автодилерство', + 'НМЖК', 'ВГТРК', 'Неофарм', 'Роскосмос', 'Вита Лайн', 'Краснодарзернопродукт-Экспо', 'Алкоторг', 'Красцветмет', + 'Касторама Рус (Castorama)', 'Деловые линии', 'ГВСУ по специальным объектам', 'ПКФ ДиПОС', 'Восток-Запад', + 'Амурская нефтебаза', 'Юг Руси', 'Шнейдер Электрик (Schneider Electric)', 'Сингента (Chemchina)', 'Титан', + 'Петропавловск', 'Фармимэкс', 'АБ Инбев Эфес (Anheuser-Busch Inbev)', 'ABI Product', 'Профитмед', + 'ТД Агроторг', 'ТЭК СПБ', 'ТД Ункомтех', 'ОПХ (Heineken)', 'ТГК-16', 'Уральский банк реконструкции и развития', + 'QIWI', 'СК Согласие', 'Группа Эссен', 'Втормет', 'Эссити (Essity)', 'Hoff (Домашний интерьер)', + 'Сиско Солюшенз (Cisco)', 'ВО ЖДТ России', 'Купишуз (Lamoda)', 'Делл (Dell)', 'ПСК', + 'Каменск-Уральский металлургический завод', 'Аргос', 'А.П.Р.', 'ГК 1520', 'Артис-Агро Экспорт', 'Луидор', + 'Порше Руссланд (Porsche)', 'Денцу Эйджис Си Эс (Dentsu)', 'Эйвон Бьюти Продактс Компани (Avon)', + 'РКЦ Прогресс', 'Силовые машины', 'АНГК', 'Корпорация Гринн', 'Фаберлик', 'Сибирская сервисная компания', + 'Банк Возрождение', 'Отисифарм', 'Боэс Констракшн (Boes Construction)', 'Саткинский чугуноплавильный завод', + 'Алтайвагон', 'ПТК', 'Щекиноазот', 'Волгоградэнергосбыт', 'Русский уголь', 'Трест КХМ', 'РМ Рейл', + 'Восточная горнорудная компания', 'Группа Стройтрансгаз', 'БАСФ (BASF)', 'Мерида', 'Брок-Инвест-Сервис и К', + 'Вирлпул Рус (Whirlpool)', 'Карелия Палп', 'Тева (Teva)', 'Media Direction Group', + 'Якобс Дау Эгбертс Рус (Jacobs Douwe Egberts)', 'ГК Великан', 'Август', 'Транслом', 'ОТП Банк', 'РусВинил', + 'Системный оператор Единой энергетической системы', 'АСР-Углесбыт', 'ЦЭНКИ', 'Транстрейдойл', 'Росморпорт', + 'Газнефтетрэйдинг', 'Сладковско-Заречное', 'Кроношпан (Kronoplus)', 'ТЦ Кунцево Лимитед', 'СНПХ', + 'Кимберли-Кларк (Kimberly-Clark)', 'Катерпиллар Евразия (Caterpillar)', 'Крок инкорпорейтед', + 'Ашинский металлургический завод', 'Автодом', 'Международный центр', 'Мишлен (Michelin)', 'Картли', 'БелАЗ-24', + 'Первый завод', 'ГК ЕКС', 'Петролеум Трейдинг', 'Нижфарм (Nidda Midco)', 'Импэкснефтехим', + 'Вольво Карс (Zhejiang Geely)', 'Мосметрострой', 'ТЭК Мосэнерго', 'Борисхоф 1 (Inchcape)', 'ГК Титан', + 'ПТК Уголь', 'Авторусь', 'Юг-Авто', 'Нова', 'Метрострой', 'Ресурс', 'Сетевая компания', 'РЕ Трэйдинг (LPP)', + 'Углетранс', 'ЭйчПи Инк (HP Inc.)', 'ТК Шлюмберже (Schlumberger)', 'ГК Мега-Авто', + 'Корпорация Электросевкавмонтаж', 'ГК Российские коммунальные системы', 'Запсибгазпром', 'Нефтепродукттрейд', + 'Сатурн-Р', 'Завод имени Дегтярева', 'Такеда Фармасьютикалс (Takeda Pharmaceutical)', 'Слата супермаркет', + 'Emex', 'САМ-МБ', '171 Меридиан', 'Армтек', 'Центр финансовых технологий', 'Группа компаний Пионер', + 'АХ Степь', 'Таграс (ТНГ-Групп)', 'Fonbet', 'Сандоз (Sandoz)', 'Берлин-Хеми А. Менарини (Berlin Chemie)', + 'ГК Агропромкомплектация', 'МАКС', 'Компания Трасса', 'Башкирэнерго', 'Охрана Росгвардии', 'Гала-Форм', + 'КРКА Фарма (KRKA)', 'Максидом', 'Нефтехимремстрой', 'Нефтьмагистраль', 'Авеста Фармацевтика (Baby Dream)', + 'Старттех', 'Конар', 'Нортгаз', 'УГС', 'АББ (ABB)', 'Металлстандарт', 'Балтийская топливная компания', + 'Мострансавто', 'Аксель-Моторс', 'Группа компаний МИЦ', 'ПК Борец', 'Европа', 'Сибирская аграрная группа', + 'РТИ', 'Ферронордик машины (Ferronordic)', 'Южуралзолото ГК', 'Прогресс', 'Юг-Нефтепродукт', 'Камский кабель', + 'Familia', 'Транскапиталбанк', 'А-Ойл', 'Сибтрейд', 'МТС-банк', 'Московская инженерно-строительная компания', + 'Курганмашзавод', 'Вектрум-К', 'Морской терминал Тамань', 'Таркетт Рус (Tarkett)', + 'Несте Санкт-Петербург (Neste)', 'Ново-Уренгойская газовая компания', 'Национальная нерудная компания', + 'Октоблу (Decathlon)', 'Снежная Королева', 'Новартис Фарма (Novartis)', 'Магнолия', 'Техинком', + 'Дочки-Сыночки', 'Астеллас Фарма', 'General Fueller', 'Автозаправочные комплексы Atan', 'Псковвтормет', + 'Авиакомпания Икар', + ) + + catch_phrase_adj = ( + ('Автоматизированный', 'Автономный', 'Адаптивный', 'Амортизированный', 'Ассимилированный', 'Безопасный', + 'Бизнес-ориентированный', 'Взаимовыгодный', 'Виртуальный', 'Глубокий', 'Горизонтальный', 'Делегируемый', + 'Децентрализованный', 'Дублируемый', 'Инверсный', 'Инновационный', 'Интегрированный', 'Интуитивный', + 'Качественный', 'Клиент-ориентированный', 'Контролируемый', 'Концептуальный', 'Корпоративный', + 'Кросс-платформенный', 'Межгрупповой', 'Многогранный', 'Многоканальный', 'Многослойный', 'Многоуровневый', + 'Модернизируемый', 'Настраиваемый', 'Новый', 'Общедоступный', 'Объектный', 'Обязательный', 'Оперативный', + 'Оптимизированный', 'Опциональный', 'Организованный', 'Органичный', 'Ориентированный', 'Открытый', + 'Оцифрованный', 'Переключаемый', 'Переосмысленный', 'Переработанный', 'Перспективный', 'Полный', 'Поэтапный', + 'Превентивный', 'Программируемый', 'Прогрессивный', 'Продвинутый', 'Прочный', 'Разнообразный', + 'Распределённый', 'Расширенный', 'Реализованный', 'Реконструируемый', 'Самодостаточный', 'Сбалансированный', + 'Сетевой', 'Синхронизированный', 'Совместимый', 'Сокращенный', 'Сосредоточенный', 'Стабильный', + 'Стратегический', 'Увеличенный', 'Удобный', 'Улучшенный', 'Улучшенный', 'Уменьшенный', 'Универсальный', + 'Управляемый', 'Устойчивый', 'Фундаментальный', 'Функциональный', 'Цельный', 'Централизованный', + 'Эксклюзивный', 'Элегантный', 'Эргономичный'), + ('аналитический', 'асимметричный', 'асинхронный', 'бездефектный', 'бескомпромиссный', 'веб-ориентированный', + 'встречный', 'вторичный', 'высокоуровневый', 'гибкий', 'гибридный', 'глобальный', 'двунаправленный', + 'действенный', 'динамичный', 'единообразный', 'заметный', 'инструктивный', 'интерактивный', 'исполнительный', + 'итернациональный', 'клиент-серверный', 'контекстуальный', 'круглосуточный', 'логистический', 'локальный', + 'максимальный', 'масштабируемый', 'методичный', 'многозадачный', 'мобильный', 'модульный', 'мультимедийный', + 'наглядный', 'направленный', 'национальный', 'нейтральный', 'нестандартный', 'объектно-ориентированный', + 'однородный', 'оптимальный', 'основной', 'отказостойкий', 'переходный', 'последовательный', 'потенциальный', + 'пошаговый', 'прибыльный', 'приоритетный', 'промежуточный', 'радикальный', 'раздвоенный', 'региональный', + 'связный', 'систематический', 'системный', 'составной', 'социальный', 'специализированный', 'статический', + 'третичный', 'ультрасовременный', 'целостный', 'широкий', 'широкопрофильный', 'эвристический', + 'экоцентричный', 'энергонезависимый', 'яркий'), + ) + + catch_phrase_nouns_masc = ( + 'адаптер', 'алгоритм', 'альянс', 'анализатор', 'архив', 'веб-сайт', 'вызов', 'графический интерфейс', + 'графический интерфейс пользователя', 'доступ', 'инструментарий', 'интерфейс', 'инфопосредник', + 'искусственный интеллект', 'массив', 'модератор', 'мониторинг', 'набор инструкций', 'параллелизм', 'подход', + 'портал', 'прогноз', 'продукт', 'проект', 'протокол', 'ресурс', 'системный движок', 'успех', 'фреймворк', 'хаб', + 'эталон', + ) + + catch_phrase_nouns_fem = ( + 'архитектура', 'база данных', 'база знаний', 'вероятность', 'возможность', 'гибкость', 'защищенная линия', + 'иерархия', 'инициатива', 'инфраструктура', 'кодировка', 'конгломерация', 'концепция', 'координация', + 'локальная сеть', 'матрица', 'методология', 'миграция', 'модель', 'нейронная сеть', 'парадигма', 'поддержка', + 'политика', 'проекция', 'производительность', 'прошивка', 'рабочая группа', 'реализация', 'сеть Интранет', + 'сеть Экстранет', 'служба поддержки', 'служба техподдержки', 'способность', 'стандартизация', 'стратегия', + 'структура', 'суперструктура', 'установка', 'фокус-группа', 'функциональность', 'функция', 'ценовая структура', + 'эмуляция', + ) + + catch_phrase_nouns_neu = ( + 'взаимодействие', 'групповое программное обеспечение', 'интернет-решение', 'использование', + 'межплатформенное программное обеспечение', 'оборудование', 'определение', 'отношение', 'приложение', + 'программное обеспечение', 'решение', 'совершенствование процесса', 'сотрудничество', 'управление бюджетом', + 'хранилище данных', 'шифрование', 'ядро', + ) + + bsWords = ( + ('Адаптация', 'Визуализация', 'Включение', 'Внедрение', 'Генерация', 'Инновация', 'Интеграция', 'Использование', + 'Итерация', 'Конструирование', 'Координация', 'Культивация', 'Максимизация', 'Модернизация', 'Монетизация', + 'Мотивация', 'Обеспечение', 'Объединение', 'Оптимизация', 'Освоение', 'Охват', 'Оцифровка', 'Перезагрузка', + 'Переопределение', 'Переосмысление', 'Перепрофилирование', 'Переход', 'Преображение', 'Приспособление', + 'Продление', 'Производство', 'Развитие', 'Разворачивание', 'Разработка', 'Распределение', 'Реализация', + 'Революция', 'Синтез', 'Синхронизация', 'Сравнение', 'Трансформация', 'Увеличение', 'Управление', 'Ускорение', + 'Формирование', 'Шкалирование', 'Эксплуатация'), + ('B2B', 'B2C', 'активных', 'безотказных', 'беспроводных', 'богатых', 'веб-ориентированных', 'вертикальных', + 'виртуальных', 'глобальных', 'действенных', 'динамичных', 'заказных', 'индивидуальных', 'инновационных', + 'интегрированных', 'интерактивных', 'интуитивных', 'концептуальных', 'корпоративных', 'критически важных', + 'кроссплатформенных', 'круглогодичных', 'круглосуточных', 'лучших в своём роде', 'масштабируемых', + 'мультимедийных', 'наглядных', 'надежных', 'онлайн и офлайн', 'ориентированных на пользователя', 'открытых', + 'передовых', 'подробных', 'популярных', 'престижных', 'прибыльных', 'притягательных', 'прозрачных', + 'распределённых', 'распространенных', 'расширяемых', 'революционных', 'сенсационных', 'серверных', 'сетевых', + 'соблазнительных', 'совместных', 'современных', 'стандартных', 'стратегических', 'ультрасовременных', + 'фронт-энд', 'целостных', 'цельных', 'эффективных'), + ('архитектур', 'аудиторий', 'веб-сервисов', 'взаимодействий', 'действий', 'диапазонов', 'знаний', 'инициатив', + 'интернет-компаний', 'интернет-магазинов', 'интернет-продавцоы', 'интернет-услуг', 'интерфейсов', + 'инфопосредников', 'инфраструктур', 'каналов', 'методик', 'метрик', 'моделей', 'ниш', 'областей интереса', + 'отношений', 'парадигм', 'партнерств', 'платформ', 'пользователей', 'порталов', 'приложений', 'результатов', + 'решений', 'рынков', 'сетей', 'систем', 'систем снабжения', 'сообществ', 'схем', 'технологий', 'функций')) + + def catch_phrase(self): + """ + :example: 'Адаптивный и масштабируемый графический интерфейс' + """ + noun = self.random_element(self.catch_phrase_nouns_masc + self.catch_phrase_nouns_fem + + self.catch_phrase_nouns_neu) + adj_first = self.random_element(self.catch_phrase_adj[0]) + adj_second = self.random_element(self.catch_phrase_adj[1]) + if noun in self.catch_phrase_nouns_fem: + adj_first = adj_first[:-2] + 'ая' + adj_second = adj_second[:-2] + 'ая' + elif noun in self.catch_phrase_nouns_neu: + adj_first = adj_first[:-2] + 'ое' + adj_second = adj_second[:-2] + 'ое' + return adj_first + ' и ' + adj_second + ' ' + noun + + def large_company(self): + """ + :example: 'АвтоВАЗ' + """ + return self.random_element(self.large_companies) + + def company_prefix(self): + """ + :example: 'ООО' + """ + return self.random_element(self.company_prefixes) + + def businesses_inn(self): + """ + Returns tax identification number for businesses (ru. идентификационный номер налогоплательщика, ИНН). + """ + region = '%02d' % self.random_int(min=1, max=92) + inspection = '%02d' % self.random_int(min=1, max=99) + tail = '%05d' % self.random_int(min=1, max=99999) + result = region + inspection + tail + + return result + calculate_checksum(result) + + def individuals_inn(self): + """ + Returns tax identification number for individuals (ru. идентификационный номер налогоплательщика, ИНН). + """ + region = '%02d' % self.random_int(min=1, max=92) + inspection = '%02d' % self.random_int(min=1, max=99) + tail = '%06d' % self.random_int(min=1, max=999999) + result = region + inspection + tail + result += calculate_checksum(result) + + return result + calculate_checksum(result) + + def businesses_ogrn(self): + """ + Returns primary state registration number for businesses + (ru. основной государственный регистрационный номер, ОГРН). + """ + sign = self.random_element(('1', '5')) + year = '%02d' % self.random_int(min=1, max=datetime.now().year - 2000) + region = '%02d' % self.random_int(min=1, max=92) + tail = '%07d' % self.random_int(min=1, max=9999999) + + result = sign + year + region + tail + + return result + str((int(result) % 11) % 10) + + def individuals_ogrn(self): + """ + Returns primary state registration number for individuals + (ru. основной государственный регистрационный номер, ОГРН). + """ + year = '%02d' % self.random_int(min=1, max=datetime.now().year - 2000) + region = '%02d' % self.random_int(min=1, max=92) + tail = '%09d' % self.random_int(min=1, max=999999999) + + result = '3' + year + region + tail + + return result + str((int(result) % 13) % 10) + + def kpp(self): + """ + Returns tax registration reason code (ru. код причины постановки на учет, КПП). + """ + region = '%02d' % self.random_int(min=1, max=92) + inspection = '%02d' % self.random_int(min=1, max=99) + reason = self.random_element(('01', '43', '44', '45')) + tail = '%03d' % self.random_int(min=1, max=999) + + return region + inspection + reason + tail diff --git a/testbed/joke2k__faker/faker/providers/company/sk_SK/__init__.py b/testbed/joke2k__faker/faker/providers/company/sk_SK/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e8e2f3b6e1a7dbef281662bcf8f8b3b6974dd8 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/sk_SK/__init__.py @@ -0,0 +1,13 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}}', + ) + + company_suffixes = ( + 's.r.o.', 'v.o.s.', 'a.s.', 'k.s.', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/sl_SI/__init__.py b/testbed/joke2k__faker/faker/providers/company/sl_SI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf9202be77e4017e8c775012ac06c78cbfd5fb6 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/sl_SI/__init__.py @@ -0,0 +1,12 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{first_name}} {{last_name}} s.p.', + ) + + company_suffixes = ( + 'd.o.o.', 'd.d.', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/sv_SE/__init__.py b/testbed/joke2k__faker/faker/providers/company/sv_SE/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da008726339e58625590dbc826676c07a9e1239b --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/sv_SE/__init__.py @@ -0,0 +1,13 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} {{last_name}} {{company_suffix}}', + '{{last_name}} & {{last_name}} {{company_suffix}}', + ) + + company_suffixes = ( + 'AB', 'HB', + ) diff --git a/testbed/joke2k__faker/faker/providers/company/tl_PH/__init__.py b/testbed/joke2k__faker/faker/providers/company/tl_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05bb9c090df9b888d22ba0b4bc9728a32826a195 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/tl_PH/__init__.py @@ -0,0 +1,6 @@ +from ..fil_PH import Provider as FilPhProvider + + +class Provider(FilPhProvider): + """No difference from Company Provider for fil_PH locale""" + pass diff --git a/testbed/joke2k__faker/faker/providers/company/zh_CN/__init__.py b/testbed/joke2k__faker/faker/providers/company/zh_CN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb404765edbe76c73ce80aa9d5505498a8fa6f5 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/zh_CN/__init__.py @@ -0,0 +1,24 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ["{{company_prefix}}{{company_suffix}}"] + + company_prefixes = ["超艺", "和泰", "九方", "鑫博腾飞", "戴硕电子", "济南亿次元", + "海创", "创联世纪", "凌云", "泰麒麟", "彩虹", "兰金电子", + "晖来计算机", "天益", "恒聪百汇", "菊风公司", "惠派国际公司", + "创汇", "思优", "时空盒数字", "易动力", "飞海科技", "华泰通安", + "盟新", "商软冠联", "图龙信息", "易动力", "华远软件", "创亿", + "时刻", "开发区世创", "明腾", "良诺", "天开", "毕博诚", "快讯", + "凌颖信息", "黄石金承", "恩悌", "雨林木风计算机", "双敏电子", + "维旺明", "网新恒天", "数字100", "飞利信", "立信电子", "联通时科", + "中建创业", "新格林耐特", "新宇龙信息", "浙大万朋", "MBP软件", + "昂歌信息", "万迅电脑", "方正科技", "联软", "七喜", "南康", "银嘉", + "巨奥", "佳禾", "国讯", "信诚致远", "浦华众城", "迪摩", "太极", + "群英", "合联电子", "同兴万点", "襄樊地球村", "精芯", "艾提科信", + "昊嘉", "鸿睿思博", "四通", "富罳", "商软冠联", "诺依曼软件", + "东方峻景", "华成育卓", "趋势", "维涛", "通际名联"] + company_suffixes = [n + "有限公司" for n in ["科技", "网络", "信息", "传媒"]] + + def company_prefix(self): + return self.random_element(self.company_prefixes) diff --git a/testbed/joke2k__faker/faker/providers/company/zh_TW/__init__.py b/testbed/joke2k__faker/faker/providers/company/zh_TW/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15a09ff5d231482006996e4e926d20ee1e8d5349 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/company/zh_TW/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + formats = ("{{company_prefix}}{{company_suffix}}", ) + + company_prefixes = ( + "品王餐飲", "一統企業", "品誠", "台灣電信", + "Goagle", "一統星巴克", "台日積體電路", "榮長航空", + "台灣印無品良", "華中航空", "台灣人銀行", "國中鋼鐵", + "海鴻精密", "台灣鐵高", "家宜家居(KIEA)", "天上雜誌", + "台灣力電", "碩華電腦", "雄豹旅遊", "光新三越百貨", + "台灣軟微", "鐵台", "一統超商", "碁宏", + "創群光電(奇原美電子)", "台灣酒菸", "美奧廣告", "AYHOO!摩奇", + "台灣台油", "達宏國際電子", "華晶國際酒店", "秀威影城", + "王鼎餐飲集團", "台灣五星電子", "遊戲葡萄數位科技", "橋子王生技", + "大八電視", "台灣業糖", "都亞緻麗", "台灣來自水", + "麥當當", "風微廣場", "見遠雜誌", "石金堂", + "邦城文化事業", "華中郵政", "達友光電", "中台信託商業銀行", + "台北登來喜大飯店", "全味食品工業", "遠西百貨", "旗花(台灣銀)行", + "冠智科技", "丹味企業", "發聯科技", "台灣雅萊(Y'ORÉAL)", + "古太可口可樂", "榮長海運", "達廣電腦", "華福大飯店", + "立三電視", "星燦國際旅行社", "衣優庫(Nuiqlo)", "德汎", + "台北眾大捷運", "共公電視", "明陽海運", "雄遠建設事業", + "台灣迪奧汽車", "台灣地土銀行", "天中電視", "月日光半導體", + "塑台石化", "樂可旅遊集團", "信永藥品", "輝燁企業", + "興復航空運輸", "豐兆國際商業銀行", "平太洋崇光百貨", "神漢名店百貨", + "台灣士賓", "賓國大飯店", "業商週刊", "台灣BIM", + "湖劍山世界", "合作庫金商業銀行", "台北邦富商業銀行", "愛味之", + "邦富人壽保險", "律理法律", "心安食品服務(斯摩漢堡)", "松黑", + "台灣生資堂", "鮮爭", "達台電子", "聯燁鋼鐵", "華聯電子", + "瑞輝大藥廠", "隆豐大飯店(北台君悅)", "資華粧業(生資堂)") + + company_suffixes = ("", "有限公司", "股份有限公司", "資訊有限公司") + + def company_prefix(self): + return self.random_element(self.company_prefixes) diff --git a/testbed/joke2k__faker/faker/providers/credit_card/__init__.py b/testbed/joke2k__faker/faker/providers/credit_card/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf433a2b00c93b8404e14185af45bf5c574802c8 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/credit_card/__init__.py @@ -0,0 +1,132 @@ +from collections import OrderedDict + +from .. import BaseProvider + +localized = True + + +class CreditCard: + + def __init__( + self, + name, + prefixes, + length=16, + security_code='CVC', + security_code_length=3): + self.name = name + self.prefixes = prefixes + self.length = length + self.security_code = security_code + self.security_code_length = security_code_length + + +class Provider(BaseProvider): + + # Prefixes from: + # * https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_.28IIN.29 + # * https://www.regular-expressions.info/creditcard.html + # * https://creditcardjs.com/credit-card-type-detection + prefix_maestro = ['5018', '5020', '5038', '56##', '57##', '58##', + '6304', '6759', '6761', '6762', '6763', '0604', '6390'] + prefix_mastercard = ['51', '52', '53', '54', '55', '222%', '223', '224', + '225', '226', '227', '228', '229', '23', '24', '25', + '26', '270', '271', '2720'] + prefix_visa = ['4'] + prefix_amex = ['34', '37'] + prefix_discover = ['6011', '65'] + prefix_diners = ['300', '301', '302', '303', '304', '305', '36', '38'] + prefix_jcb16 = ['35'] + prefix_jcb15 = ['2131', '1800'] + + credit_card_types = OrderedDict(( + ('maestro', CreditCard('Maestro', + prefix_maestro, 12, security_code='CVV')), + ('mastercard', CreditCard('Mastercard', + prefix_mastercard, 16, security_code='CVV')), + ('visa16', CreditCard('VISA 16 digit', prefix_visa)), + ('visa13', CreditCard('VISA 13 digit', prefix_visa, 13)), + ('visa19', CreditCard('VISA 19 digit', prefix_visa, 19)), + ('amex', CreditCard('American Express', prefix_amex, + 15, security_code='CID', security_code_length=4)), + ('discover', CreditCard('Discover', prefix_discover)), + ('diners', CreditCard('Diners Club / Carte Blanche', prefix_diners, 14)), + ('jcb15', CreditCard('JCB 15 digit', prefix_jcb15, 15)), + ('jcb16', CreditCard('JCB 16 digit', prefix_jcb16)), + )) + credit_card_types['visa'] = credit_card_types['visa16'] + credit_card_types['jcb'] = credit_card_types['jcb16'] + + luhn_lookup = {'0': 0, '1': 2, '2': 4, '3': 6, '4': 8, + '5': 1, '6': 3, '7': 5, '8': 7, '9': 9} + + def credit_card_provider(self, card_type=None): + """ Returns the provider's name of the credit card. """ + if card_type is None: + card_type = self.random_element(self.credit_card_types.keys()) + return self._credit_card_type(card_type).name + + def credit_card_number(self, card_type=None): + """ Returns a valid credit card number. """ + card = self._credit_card_type(card_type) + prefix = self.random_element(card.prefixes) + number = self._generate_number(self.numerify(prefix), card.length) + return number + + def credit_card_expire(self, start='now', end='+10y', date_format='%m/%y'): + expire_date = self.generator.date_time_between(start, end) + return expire_date.strftime(date_format) + + def credit_card_full(self, card_type=None): + card = self._credit_card_type(card_type) + + tpl = ('{provider}\n' + '{owner}\n' + '{number} {expire_date}\n' + '{security}: {security_nb}\n') + + tpl = tpl.format(provider=card.name, + owner=self.generator.parse( + "{{first_name}} {{last_name}}"), + number=self.credit_card_number(card), + expire_date=self.credit_card_expire(), + security=card.security_code, + security_nb=self.credit_card_security_code(card)) + + return self.generator.parse(tpl) + + def credit_card_security_code(self, card_type=None): + """ Returns a security code string. """ + sec_len = self._credit_card_type(card_type).security_code_length + return self.numerify('#' * sec_len) + + def _credit_card_type(self, card_type=None): + """ Returns a random credit card type instance. """ + if card_type is None: + card_type = self.random_element(self.credit_card_types.keys()) + elif isinstance(card_type, CreditCard): + return card_type + return self.credit_card_types[card_type] + + def _generate_number(self, prefix, length): + """ + 'prefix' is the start of the CC number as a string, any number of digits. + 'length' is the length of the CC number to generate. Typically 13 or 16 + """ + number = prefix + # Generate random char digits + number += '#' * (length - len(prefix) - 1) + number = self.numerify(number) + reverse = number[::-1] + # Calculate sum + tot = 0 + pos = 0 + while pos < length - 1: + tot += Provider.luhn_lookup[reverse[pos]] + if pos != (length - 2): + tot += int(reverse[pos + 1]) + pos += 2 + # Calculate check digit + check_digit = (10 - (tot % 10)) % 10 + number += str(check_digit) + return number diff --git a/testbed/joke2k__faker/faker/providers/credit_card/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/credit_card/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3467a2c82e9dbba9684d6c2d3e33349e295bbfcc --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/credit_card/en_US/__init__.py @@ -0,0 +1,5 @@ +from .. import Provider as CreditCardProvider + + +class Provider(CreditCardProvider): + pass diff --git a/testbed/joke2k__faker/faker/providers/credit_card/fa_IR/__init__.py b/testbed/joke2k__faker/faker/providers/credit_card/fa_IR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2761374e2a44e62b6a0fc8baca0bcc32cfe7a3ed --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/credit_card/fa_IR/__init__.py @@ -0,0 +1,74 @@ +from collections import OrderedDict + +from .. import CreditCard +from .. import Provider as CreditCardProvider + + +class Provider(CreditCardProvider): + + # https://way2pay.ir/21653 + prefix_ansar = ["627381"] + prefix_iran_zamin = ["505785"] + prefix_hekmat = ["636949"] + prefix_keshavarzi = ["603770"] + prefix_shahr = ["502806"] + prefix_mehr_eghtesad = ["606373"] + prefix_sarmayeh = ["639607"] + prefix_post_bank = ["627760"] + prefix_tose = ["628157"] + prefix_eghtesad_novin = ["627412"] + prefix_meli = ["603799"] + prefix_pasargad = ["502229"] + prefix_tourism_bank = ["505416"] + prefix_ghavamin = ["639599"] + prefix_day = ["502938"] + prefix_mellat = ["610433"] + prefix_tejarat = ["585983"] + prefix_moasse_mellal = ["606256"] + prefix_saman_bank = ["621986"] + prefix_kosar = ["505801"] + prefix_refah = ["589463"] + prefix_saderat = ["603761"] + prefix_tat = ["621986"] + prefix_sina = ["639346"] + prefix_kar_afarin = ["627488"] + prefix_sepah = ["589210"] + prefix_maskan = ["628023"] + prefix_parsian = ["622106"] + prefix_bim = ["627961"] + + credit_card_types = OrderedDict(( + ('ansar', CreditCard('انصار', prefix_ansar, 16, security_code='CVV2')), + ('iran_zamin', CreditCard('ایران زمین', prefix_iran_zamin, 16, security_code='CVV2')), + ('hekmat', CreditCard('حکمت', prefix_hekmat, 16, security_code='CVV2')), + ('keshavarzi', CreditCard('کشاورزی', prefix_keshavarzi, 16, security_code='CVV2')), + ('shahr', CreditCard('شهر', prefix_shahr, 16, security_code='CVV2')), + ('mehre_ghtesad', CreditCard('مهراقتصاد', prefix_mehr_eghtesad, 16, security_code='CVV2')), + ('sarmayeh', CreditCard('سرمایه', prefix_sarmayeh, 16, security_code='CVV2')), + ('post_bank', CreditCard('پست بانک', prefix_post_bank, 16, security_code='CVV2')), + ('tose', CreditCard('توسعه', prefix_tose, 16, security_code='CVV2')), + ('eghtesad_novin', CreditCard('اقتصاد نوین', prefix_eghtesad_novin, 16, security_code='CVV2')), + ('meli', CreditCard('ملی', prefix_meli, 16, security_code='CVV2')), + ('pasargad', CreditCard('پاسارگاد', prefix_pasargad, 16, security_code='CVV2')), + ('tourism_bank', CreditCard('گردشگری', prefix_tourism_bank, 16, security_code='CVV2')), + ('ghavamin', CreditCard('قوامین', prefix_ghavamin, 16, security_code='CVV2')), + ('day', CreditCard('دی', prefix_day, 16, security_code='CVV2')), + ('mellat', CreditCard('ملت', prefix_mellat, 16, security_code='CVV2')), + ('tejarat', CreditCard('تجارت', prefix_tejarat, 16, security_code='CVV2')), + ('mellal', CreditCard('ملل', prefix_moasse_mellal, 16, security_code='CVV2')), + ('saman', CreditCard('سامان', prefix_saman_bank, 16, security_code='CVV2')), + ('kosar', CreditCard('کوثر', prefix_kosar, 16, security_code='CVV2')), + ('refah', CreditCard('رفاه', prefix_refah, 16, security_code='CVV2')), + ('saderat', CreditCard('صادرات', prefix_saderat, 16, security_code='CVV2')), + ('tat', CreditCard('تات', prefix_tat, 16, security_code='CVV2')), + ('sina', CreditCard('سینا', prefix_sina, 16, security_code='CVV2')), + ('kar_afarin', CreditCard('کار آفرین', prefix_kar_afarin, 16, security_code='CVV2')), + ('sepah', CreditCard('سپه', prefix_sepah, 16, security_code='CVV2')), + ('maskan', CreditCard('مسکن', prefix_maskan, 16, security_code='CVV2')), + ('parsian', CreditCard('پارسیان', prefix_parsian, 16, security_code='CVV2')), + ('bim', CreditCard('صنعت و معدن', prefix_bim, 16, security_code='CVV2')), + )) + + def credit_card_expire(self, start='now', end='+3y', date_format='%y/%m'): + expire_date = self.generator.date_time_between(start, end) + return expire_date.strftime(date_format) diff --git a/testbed/joke2k__faker/faker/providers/credit_card/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/credit_card/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65c968827cf25b4a9d18fbd5f9f80ce1b523fe58 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/credit_card/ru_RU/__init__.py @@ -0,0 +1,51 @@ +from collections import OrderedDict + +from faker.providers.person.ru_RU import translit + +from .. import CreditCard +from .. import Provider as CreditCardProvider + + +class Provider(CreditCardProvider): + # Prefixes from: https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) + prefix_visa = ['4'] + prefix_mastercard = ['51', '52', '53', '54', '55', '222%', '223', '224', '225', '226', + '227', '228', '229', '23', '24', '25', '26', '270', '271', '2720'] + prefix_mir = ['2200', '2201', '2202', '2203', '2204'] + prefix_maestro = ['50', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69'] + prefix_amex = ['34', '37'] + prefix_unionpay = ['62', '81'] + + credit_card_types = OrderedDict(( + ('visa', CreditCard('Visa', prefix_visa, security_code='CVV2')), + ('mastercard', CreditCard('Mastercard', prefix_mastercard, security_code='CVC2')), + ('mir', CreditCard('МИР', prefix_mir)), + ('maestro', CreditCard('Maestro', prefix_maestro, security_code='CVV2')), + ('amex', CreditCard('American Express', prefix_amex, 15, security_code='CID', security_code_length=4)), + ('unionpay', CreditCard('Union Pay', prefix_unionpay)), + )) + + def credit_card_expire(self, start='now', end='+4y', date_format='%m/%y'): + expire_date = self.generator.date_time_between(start, end) + return expire_date.strftime(date_format) + + def credit_card_full(self, card_type=None): + card = self._credit_card_type(card_type) + + tpl = ('{provider}\n' + '{owner}\n' + '{number} {expire_date}\n' + '{security}: {security_nb}\n' + '{issuer}') + + tpl = tpl.format(provider=card.name, + owner=translit( + self.generator.parse(self.random_element(["{{first_name_male}} {{last_name_male}}", + "{{first_name_female}} {{last_name_female}}"]))), + number=self.credit_card_number(card), + expire_date=self.credit_card_expire(), + security=card.security_code, + security_nb=self.credit_card_security_code(card), + issuer=self.generator.parse("{{bank}}")) + + return self.generator.parse(tpl) diff --git a/testbed/joke2k__faker/faker/providers/currency/__init__.py b/testbed/joke2k__faker/faker/providers/currency/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6842e0e71c634e3896fedcc79eed95236d10f46 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/currency/__init__.py @@ -0,0 +1,264 @@ +from .. import BaseProvider + +localized = True + + +class Provider(BaseProvider): + # Format: (code, name) + currencies = ( + ("AED", "United Arab Emirates dirham"), + ("AFN", "Afghan afghani"), + ("ALL", "Albanian lek"), + ("AMD", "Armenian dram"), + ("ANG", "Netherlands Antillean guilder"), + ("AOA", "Angolan kwanza"), + ("ARS", "Argentine peso"), + ("AUD", "Australian dollar"), + ("AWG", "Aruban florin"), + ("AZN", "Azerbaijani manat"), + ("BAM", "Bosnia and Herzegovina convertible mark"), + ("BBD", "Barbadian dollar"), + ("BDT", "Bangladeshi taka"), + ("BGN", "Bulgarian lev"), + ("BHD", "Bahraini dinar"), + ("BIF", "Burundian franc"), + ("BMD", "Bermudian dollar"), + ("BND", "Brunei dollar"), + ("BOB", "Bolivian boliviano"), + ("BRL", "Brazilian real"), + ("BSD", "Bahamian dollar"), + ("BTN", "Bhutanese ngultrum"), + ("BWP", "Botswana pula"), + ("BYR", "Belarusian ruble"), + ("BZD", "Belize dollar"), + ("CAD", "Canadian dollar"), + ("CDF", "Congolese franc"), + ("CHF", "Swiss franc"), + ("CLP", "Chilean peso"), + ("CNY", "Renminbi"), + ("COP", "Colombian peso"), + ("CRC", "Costa Rican colón"), + ("CUC", "Cuban convertible peso"), + ("CUP", "Cuban peso"), + ("CVE", "Cape Verdean escudo"), + ("CZK", "Czech koruna"), + ("DJF", "Djiboutian franc"), + ("DKK", "Danish krone"), + ("DOP", "Dominican peso"), + ("DZD", "Algerian dinar"), + ("EGP", "Egyptian pound"), + ("ERN", "Eritrean nakfa"), + ("ETB", "Ethiopian birr"), + ("EUR", "Euro"), + ("FJD", "Fijian dollar"), + ("FKP", "Falkland Islands pound"), + ("GBP", "Pound sterling"), + ("GEL", "Georgian lari"), + ("GGP", "Guernsey pound"), + ("GHS", "Ghanaian cedi"), + ("GIP", "Gibraltar pound"), + ("GMD", "Gambian dalasi"), + ("GNF", "Guinean franc"), + ("GTQ", "Guatemalan quetzal"), + ("GYD", "Guyanese dollar"), + ("HKD", "Hong Kong dollar"), + ("HNL", "Honduran lempira"), + ("HRK", "Croatian kuna"), + ("HTG", "Haitian gourde"), + ("HUF", "Hungarian forint"), + ("IDR", "Indonesian rupiah"), + ("ILS", "Israeli new shekel"), + ("NIS", "Israeli new shekel"), + ("IMP", "Manx pound"), + ("INR", "Indian rupee"), + ("IQD", "Iraqi dinar"), + ("IRR", "Iranian rial"), + ("ISK", "Icelandic króna"), + ("JEP", "Jersey pound"), + ("JMD", "Jamaican dollar"), + ("JOD", "Jordanian dinar"), + ("JPY", "Japanese yen"), + ("KES", "Kenyan shilling"), + ("KGS", "Kyrgyzstani som"), + ("KHR", "Cambodian riel"), + ("KMF", "Comorian franc"), + ("KPW", "North Korean won"), + ("KRW", "Western Krahn language"), + ("KWD", "Kuwaiti dinar"), + ("KYD", "Cayman Islands dollar"), + ("KZT", "Kazakhstani tenge"), + ("LAK", "Lao kip"), + ("LBP", "Lebanese pound"), + ("LKR", "Sri Lankan rupee"), + ("LRD", "Liberian dollar"), + ("LSL", "Lesotho loti"), + ("LTL", "Lithuanian litas"), + ("LYD", "Libyan dinar"), + ("MAD", "Moroccan dirham"), + ("MDL", "Moldovan leu"), + ("MGA", "Malagasy ariar"), + ("MKD", "Macedonian denar"), + ("MMK", "Burmese kyat"), + ("MNT", "Mongolian tugrik"), + ("MOP", "Macanese pataca"), + ("MRO", "Mauritanian ouguiya"), + ("MUR", "Mauritian rupee"), + ("MVR", "Maldivian rufiyaa"), + ("MWK", "Malawian kwacha"), + ("MXN", "Mexican peso"), + ("MYR", "Malaysian ringgit"), + ("MZN", "Mozambican metical"), + ("NAD", "Namibian dollar"), + ("NGN", "Nigerian naira"), + ("NIO", "Nicaraguan córdoba"), + ("NOK", "Norwegian krone"), + ("NPR", "Nepalese rupee"), + ("NZD", "New Zealand dollar"), + ("OMR", "Omani rial"), + ("PAB", "Panamanian balboa"), + ("PEN", "Peruvian sol"), + ("PGK", "Papua New Guinean kina"), + ("PHP", "Philippine peso"), + ("PKR", "Pakistani rupee"), + ("PLN", "Polish zloty"), + ("PYG", "Paraguayan guarani"), + ("QAR", "Qatari riyal"), + ("RON", "Romanian leu"), + ("RSD", "Serbian dinar"), + ("RUB", "Russian ruble"), + ("RWF", "Rwandan franc"), + ("SAR", "Saudi riyal"), + ("SBD", "Solomon Islands dollar"), + ("SCR", "Seychellois rupee"), + ("SDG", "Sudanese pound"), + ("SEK", "Swedish krona"), + ("SGD", "Singapore dollar"), + ("SHP", "Saint Helena pound"), + ("SLL", "Sierra Leonean leone"), + ("SOS", "Somali shilling"), + ("SPL", "Seborga luigino"), + ("SRD", "Surinamese dollar"), + ("STD", "São Tomé and Príncipe dobra"), + ("SVC", "Salvadoran colón"), + ("SYP", "Syrian pound"), + ("SZL", "Swazi lilangeni"), + ("THB", "Thai baht"), + ("TJS", "Tajikistani somoni"), + ("TMT", "Turkmenistan manat"), + ("TND", "Tunisian dinar"), + ("TOP", "Tongan paʻanga"), + ("TRY", "Turkish lira"), + ("TTD", "Trinidad and Tobago dollar"), + ("TVD", "Tuvaluan dollar"), + ("TWD", "New Taiwan dollar"), + ("TZS", "Tanzanian shilling"), + ("UAH", "Ukrainian hryvnia"), + ("UGX", "Ugandan shilling"), + ("USD", "United States dollar"), + ("UYU", "Uruguayan peso"), + ("UZS", "Uzbekistani soʻm"), + ("VEF", "Venezuelan bolívar"), + ("VND", "Vietnamese đồng"), + ("VUV", "Vanuatu vatu"), + ("WST", "Samoan tālā"), + ("XAF", "Central African CFA franc"), + ("XCD", "Eastern Caribbean dollar"), + ("XDR", "Special drawing rights"), + ("XOF", "West African CFA franc"), + ("XPF", "CFP franc"), + ("YER", "Yemeni rial"), + ("ZAR", "South African rand"), + ("ZMW", "Zambian kwacha"), + ("ZWD", "Zimbabwean dollar"), + ) + + # Source: https://en.wikipedia.org/wiki/List_of_cryptocurrencies + cryptocurrencies = ( + ('AMP', "AMP"), + ('AUR', "Auroracoin"), + ('BC', "BlackCoin"), + ('BTC', "Bitcoin"), + ('BURST', "Burstcoin"), + ('DASH', "Dash"), + ('DOGE', "Dogecoin"), + ('EMC', "Emercoin"), + ('ETH', "Ethereum"), + ('ETC', "Ethereum Classic"), + ('GRC', "Gridcoin"), + ('KOI', "Coinye"), + ('LTC', "Litecoin"), + ('MSC', "Omni"), + ('MZC', "MazaCoin"), + ('NMC', "Namecoin"), + ('NXT', "Nxt"), + ('POT', "PotCoin"), + ('PPC', "Peercoin"), + ('TIT', "Titcoin"), + ('VTC', "Vertcoin"), + ('XDN', "DigitalNote"), + ('XMR', "Monero"), + ('XPM', "Primecoin"), + ('XRP', "Ripple"), + ('ZEC', "Zcash"), + ('STC', "SwiftCoin"), + ('BCN', "Bytecoin"), + ('FTH', "Feathercoin"), + ('NEO', "NEO"), + ('NEM', "XEM"), + ('USDT', "Tether"), + ('IOTA', "IOTA"), + ('DRC', "Decred"), + ('WAVES', "Waves Platform"), + ('LSK', "Lisk"), + ('ZCL', "Zclassic"), + ('BCH', "Bitcoin Cash"), + ('UBQ', "Ubiq"), + ('EOS', "EOS.IO"), + ('SRN', "Sirin Labs"), + ('TRX', "TRON"), + ('ADA', "Cardano"), + ) + + # List of currency symbols in Unicode, source: https://www.unicode.org/charts/beta/nameslist/n_20A0.html + currency_symbols = { + 'AFN': '\u060B', 'ANG': '\u0192', 'ARS': '\u0024', 'AUD': '\u0024', 'AWG': '\u0192', 'BBD': '\u0024', + 'BDT': '\u09F3', 'BMD': '\u0024', 'BND': '\u0024', 'BOB': '\u0024', 'BRL': '\u0024', 'BSD': '\u0024', + 'BZD': '\u0024', 'CAD': '\u0024', 'CLP': '\u0024', 'CNY': '\u00A5', 'COP': '\u0024', 'CRC': '\u20A1', + 'CUP': '\u0024', 'CVE': '\u0024', 'DOP': '\u0024', 'EGP': '\u00A3', 'EUR': '\u20AC', 'FJD': '\u0024', + 'FKP': '\u00A3', 'GBP': '\u00A3', 'GHS': '\u20B5', 'GIP': '\u00A3', 'GYD': '\u0024', 'HKD': '\u0024', + 'HUF': '\u0192', 'IDR': '\u20A8', 'ILS': '\u20AA', 'INR': '\u20B9', 'IRR': '\uFDFC', 'JMD': '\u0024', + 'JPY': '\u00A5', 'KHR': '\u17DB', 'KPW': '\u20A9', 'KRW': '\u20A9', 'KYD': '\u0024', 'KZT': '\u20B8', + 'LAK': '\u20AD', 'LBP': '\u00A3', 'LKR': '\u20A8', 'LRD': '\u0024', 'MNT': '\u20AE', 'MOP': '\u0024', + 'MUR': '\u20A8', 'MXN': '\u0024', 'NAD': '\u0024', 'NGN': '\u20A6', 'NIO': '\u0024', 'NPR': '\u20A8', + 'NZD': '\u0024', 'OMR': '\uFDFC', 'PHP': '\u20B1', 'PKR': '\u20A8', 'PYG': '\u20B2', 'QAR': '\uFDFC', + 'RUB': '\u20BD', 'SAR': '\uFDFC', 'SBD': '\u0024', 'SDG': '\u00A3', 'SGD': '\u0024', 'SHP': '\u00A3', + 'SRD': '\u0024', 'SYP': '\u00A3', 'THB': '\u0E3F', 'TOP': '\u0024', 'TRY': '\u20BA', 'TTD': '\u0024', + 'TWD': '\u0024', 'UAH': '\u20B4', 'USD': '\u0024', 'UY': '\u0024', 'VND': '\u20AB', 'WST': '\u0024', + 'XCD': '\u0024', 'YER': '\uFDFC', 'ZWD': '\u0024', + } + + def currency(self): + return self.random_element(self.currencies) + + def currency_code(self): + return self.currency()[0] + + def currency_name(self): + return self.currency()[1] + + def currency_symbol(self, code=None): + """ + :example: $ + """ + if code is None: + code = self.random_element(self.currency_symbols.keys()) + return self.currency_symbols[code] + + def cryptocurrency(self): + return self.random_element(self.cryptocurrencies) + + def cryptocurrency_code(self): + return self.cryptocurrency()[0] + + def cryptocurrency_name(self): + return self.cryptocurrency()[1] diff --git a/testbed/joke2k__faker/faker/providers/currency/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/currency/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..977d614cb61a19769b6a3a95d44a2506877236ee --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/currency/en_US/__init__.py @@ -0,0 +1,5 @@ +from .. import Provider as CurrencyProvider + + +class Provider(CurrencyProvider): + pass diff --git a/testbed/joke2k__faker/faker/providers/currency/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/currency/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72f3f778a6e1524f403228352affc69dd8c82e6b --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/currency/ru_RU/__init__.py @@ -0,0 +1,172 @@ +from .. import Provider as CurrencyProvider + + +class Provider(CurrencyProvider): + # Format: (code, name) + # See currency names in Russian: https://ru.wikipedia.org/wiki/Список_существующих_валют#Валюты + currencies = ( + ("AED", "Дирхам ОАЭ"), + ("AFN", "Афгани"), + ("ALL", "Лек"), + ("AMD", "Армянский драм"), + ("ANG", "Нидерландский антильский гульден"), + ("AOA", "Кванза"), + ("ARS", "Аргентинское песо"), + ("AUD", "Австралийский доллар"), + ("AWG", "Арубанский флорин"), + ("AZN", "Азербайджанский манат"), + ("BAM", "Конвертируемая марка Боснии и Герцеговины"), + ("BBD", "Барбадосский доллар"), + ("BDT", "Така"), + ("BGN", "Болгарский лев"), + ("BHD", "Бахрейнский динар"), + ("BIF", "Бурундийский франк"), + ("BMD", "Бермудский доллар"), + ("BND", "Брунейский доллар"), + ("BOB", "Боливиано"), + ("BRL", "Бразильский реал"), + ("BSD", "Багамский доллар"), + ("BTN", "Нгултрум"), + ("BWP", "Пула"), + ("BYR", "Белорусский рубль"), + ("BZD", "Белизский доллар"), + ("CAD", "Канадский доллар"), + ("CDF", "Конголезский франк"), + ("CHF", "Швейцарский франк"), + ("CLP", "Чилийское песо"), + ("CNY", "Юань"), + ("COP", "Колумбийское песо"), + ("CRC", "Коста-риканский колон"), + ("CUC", "Кубанское конвертируемое песо"), + ("CUP", "Кубанское песо"), + ("CVE", "Эскудо Кабо-Верде"), + ("CZK", "Чешская крона"), + ("DJF", "Франк Джибути"), + ("DKK", "Датская крона"), + ("DOP", "Доминиканское песо"), + ("DZD", "Алжирский динар"), + ("EGP", "Египетский фунт"), + ("ERN", "Накфа"), + ("ETB", "Эфиопский быр"), + ("EUR", "Евро"), + ("FJD", "Доллар Фиджи"), + ("FKP", "Фунт Фолклендских островов"), + ("GBP", "Фунт стерлингов"), + ("GEL", "Лари"), + ("GGP", "Гернсийский фунт"), + ("GHS", "Ганский седи"), + ("GIP", "Гибралтарский фунт"), + ("GMD", "Даласи"), + ("GNF", "Гвинейский франк"), + ("GTQ", "Кетсаль"), + ("GYD", "Гайанский доллар"), + ("HKD", "Гонконгский доллар"), + ("HNL", "Лемпира"), + ("HRK", "Хорватская куна"), + ("HTG", "Гурд"), + ("HUF", "Форинт"), + ("IDR", "Индонезийская рупия"), + ("ILS", "Новый израильский шекель"), + ("NIS", "Новый израильский шекель"), + ("IMP", "Фунт острова Мэн"), + ("INR", "Индийская рупия"), + ("IQD", "Иракский динар"), + ("IRR", "Иранский риал"), + ("ISK", "Исландская крона"), + ("JEP", "Джерсийский фунт"), + ("JMD", "Ямайский доллар"), + ("JOD", "Иорданский динар"), + ("JPY", "Иена"), + ("KES", "Кенийский шиллинг"), + ("KGS", "Сом"), + ("KHR", "Риель"), + ("KMF", "Франк Комор"), + ("KPW", "Северокорейская вона"), + ("KRW", "Южнокорейская вона"), + ("KWD", "Кувейтский динар"), + ("KYD", "Доллар Островов Кайман"), + ("KZT", "Тенге"), + ("LAK", "Кип"), + ("LBP", "Ливийский фунт"), + ("LKR", "Шри-ланкийская рупия"), + ("LRD", "Либерийский доллар"), + ("LSL", "Лоти"), + ("LTL", "Литовский лит"), + ("LYD", "Ливийский динар"), + ("MAD", "Марокканский дирхам"), + ("MDL", "Молдавский лей"), + ("MGA", "Малагасийский ариари"), + ("MKD", "Денар"), + ("MMK", "Кьят"), + ("MNT", "Тугрик"), + ("MOP", "Патака"), + ("MRO", "Угия"), + ("MUR", "Маврикийская рупия"), + ("MVR", "Рувия"), + ("MWK", "Квача"), + ("MXN", "Мексиканское песо"), + ("MYR", "Малайзийский ринггит"), + ("MZN", "Мозамбикский метикал"), + ("NAD", "Доллар Намибии"), + ("NGN", "Найра"), + ("NIO", "Кордоба"), + ("NOK", "Норвежская крона"), + ("NPR", "Непальская рупия"), + ("NZD", "Новозеландский доллар"), + ("OMR", "Оманский риал"), + ("PAB", "Бальбоа"), + ("PEN", "Соль"), + ("PGK", "Кина"), + ("PHP", "Филиппинское песо"), + ("PKR", "Пакистанская рупия"), + ("PLN", "Злотый"), + ("PYG", "Гуарани"), + ("QAR", "Катарский риал"), + ("RON", "Румынский лей"), + ("RSD", "Сербский динар"), + ("RUB", "Российский рубль"), + ("RWF", "Франк Руанды"), + ("SAR", "Саудовский риял"), + ("SBD", "Доллар Соломоновых Островов"), + ("SCR", "Сейшельская рупия"), + ("SDG", "Суданский фунт"), + ("SEK", "Шведская крона"), + ("SGD", "Сингапурский доллар"), + ("SHP", "Фунт Святой Елены"), + ("SLL", "Леоне"), + ("SOS", "Сомалийский шиллинг"), + ("SPL", "Луиджино"), + ("SRD", "Суринамский доллар"), + ("STD", "Добра"), + ("SVC", "Сальвадорский колон"), + ("SYP", "Сирийский фунт"), + ("SZL", "Лилангени"), + ("THB", "Бат"), + ("TJS", "Сомони"), + ("TMT", "Новый туркменский манат"), + ("TND", "Тунисский динар"), + ("TOP", "Паанга"), + ("TRY", "Турецкая лира"), + ("TTD", "Доллар Тринидада и Тобаго"), + ("TVD", "Доллар Тувалу"), + ("TWD", "Новый тайваньский доллар"), + ("TZS", "Танзанийский шиллинг"), + ("UAH", "Гривна"), + ("UGX", "Угандийский шиллинг"), + ("USD", "Доллар США"), + ("UYU", "Уругвайское песо"), + ("UZS", "Узбекский сум"), + ("VEF", "Суверенный боливар"), + ("VND", "Донг"), + ("VUV", "Вату"), + ("WST", "Тала"), + ("XAF", "Франк КФА ВЕАС"), + ("XCD", "Восточно-карибский доллар"), + ("XDR", "СДР"), + ("XOF", "Франк КФА ВСЕАО"), + ("XPF", "Франк КФП"), + ("YER", "Йеменский риал"), + ("ZAR", "Рэнд"), + ("ZMW", "Замбийская квача"), + ("ZWD", "Доллар Зимбабве"), + ) diff --git a/testbed/joke2k__faker/faker/providers/date_time/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39dab8380fe72420c35503b9e366bf646761b545 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/__init__.py @@ -0,0 +1,2004 @@ +import re + +from calendar import timegm +from datetime import MAXYEAR, timedelta + +from dateutil import relativedelta +from dateutil.tz import tzlocal, tzutc + +from faker.utils.datetime_safe import date, datetime, real_date, real_datetime + +from .. import BaseProvider + +localized = True + + +def datetime_to_timestamp(dt): + if getattr(dt, 'tzinfo', None) is not None: + dt = dt.astimezone(tzutc()) + return timegm(dt.timetuple()) + + +def timestamp_to_datetime(timestamp, tzinfo): + if tzinfo is None: + pick = datetime.fromtimestamp(timestamp, tzlocal()) + pick = pick.astimezone(tzutc()).replace(tzinfo=None) + else: + pick = datetime.fromtimestamp(timestamp, tzinfo) + + return pick + + +class ParseError(ValueError): + pass + + +timedelta_pattern = r'' +for name, sym in [('years', 'y'), ('months', 'M'), ('weeks', 'w'), ('days', 'd'), + ('hours', 'h'), ('minutes', 'm'), ('seconds', 's')]: + timedelta_pattern += r'((?P<{}>(?:\+|-)\d+?){})?'.format(name, sym) + + +class Provider(BaseProvider): + centuries = [ + 'I', + 'II', + 'III', + 'IV', + 'V', + 'VI', + 'VII', + 'VIII', + 'IX', + 'X', + 'XI', + 'XII', + 'XIII', + 'XIV', + 'XV', + 'XVI', + 'XVII', + 'XVIII', + 'XIX', + 'XX', + 'XXI'] + + countries = [{'timezones': ['Europe/Andorra'], + 'alpha-2-code': 'AD', + 'alpha-3-code': 'AND', + 'continent': 'Europe', + 'name': 'Andorra', + 'capital': 'Andorra la Vella'}, + {'timezones': ['Asia/Kabul'], + 'alpha-2-code': 'AF', + 'alpha-3-code': 'AFG', + 'continent': 'Asia', + 'name': 'Afghanistan', + 'capital': 'Kabul'}, + {'timezones': ['America/Antigua'], + 'alpha-2-code': 'AG', + 'alpha-3-code': 'ATG', + 'continent': 'North America', + 'name': 'Antigua and Barbuda', + 'capital': "St. John's"}, + {'timezones': ['Europe/Tirane'], + 'alpha-2-code': 'AL', + 'alpha-3-code': 'ALB', + 'continent': 'Europe', + 'name': 'Albania', + 'capital': 'Tirana'}, + {'timezones': ['Asia/Yerevan'], + 'alpha-2-code': 'AM', + 'alpha-3-code': 'ARM', + 'continent': 'Asia', + 'name': 'Armenia', + 'capital': 'Yerevan'}, + {'timezones': ['Africa/Luanda'], + 'alpha-2-code': 'AO', + 'alpha-3-code': 'AGO', + 'continent': 'Africa', + 'name': 'Angola', + 'capital': 'Luanda'}, + {'timezones': ['America/Argentina/Buenos_Aires', + 'America/Argentina/Cordoba', + 'America/Argentina/Jujuy', + 'America/Argentina/Tucuman', + 'America/Argentina/Catamarca', + 'America/Argentina/La_Rioja', + 'America/Argentina/San_Juan', + 'America/Argentina/Mendoza', + 'America/Argentina/Rio_Gallegos', + 'America/Argentina/Ushuaia'], + 'alpha-2-code': 'AR', + 'alpha-3-code': 'ARG', + 'continent': 'South America', + 'name': 'Argentina', + 'capital': 'Buenos Aires'}, + {'timezones': ['Europe/Vienna'], + 'alpha-2-code': 'AT', + 'alpha-3-code': 'AUT', + 'continent': 'Europe', + 'name': 'Austria', + 'capital': 'Vienna'}, + {'timezones': ['Australia/Lord_Howe', + 'Australia/Hobart', + 'Australia/Currie', + 'Australia/Melbourne', + 'Australia/Sydney', + 'Australia/Broken_Hill', + 'Australia/Brisbane', + 'Australia/Lindeman', + 'Australia/Adelaide', + 'Australia/Darwin', + 'Australia/Perth'], + 'alpha-2-code': 'AU', + 'alpha-3-code': 'AUS', + 'continent': 'Oceania', + 'name': 'Australia', + 'capital': 'Canberra'}, + {'timezones': ['Asia/Baku'], + 'alpha-2-code': 'AZ', + 'alpha-3-code': 'AZE', + 'continent': 'Asia', + 'name': 'Azerbaijan', + 'capital': 'Baku'}, + {'timezones': ['America/Barbados'], + 'alpha-2-code': 'BB', + 'alpha-3-code': 'BRB', + 'continent': 'North America', + 'name': 'Barbados', + 'capital': 'Bridgetown'}, + {'timezones': ['Asia/Dhaka'], + 'alpha-2-code': 'BD', + 'alpha-3-code': 'BGD', + 'continent': 'Asia', + 'name': 'Bangladesh', + 'capital': 'Dhaka'}, + {'timezones': ['Europe/Brussels'], + 'alpha-2-code': 'BE', + 'alpha-3-code': 'BEL', + 'continent': 'Europe', + 'name': 'Belgium', + 'capital': 'Brussels'}, + {'timezones': ['Africa/Ouagadougou'], + 'alpha-2-code': 'BF', + 'alpha-3-code': 'BFA', + 'continent': 'Africa', + 'name': 'Burkina Faso', + 'capital': 'Ouagadougou'}, + {'timezones': ['Europe/Sofia'], + 'alpha-2-code': 'BG', + 'alpha-3-code': 'BGR', + 'continent': 'Europe', + 'name': 'Bulgaria', + 'capital': 'Sofia'}, + {'timezones': ['Asia/Bahrain'], + 'alpha-2-code': 'BH', + 'alpha-3-code': 'BHR', + 'continent': 'Asia', + 'name': 'Bahrain', + 'capital': 'Manama'}, + {'timezones': ['Africa/Bujumbura'], + 'alpha-2-code': 'BI', + 'alpha-3-code': 'BDI', + 'continent': 'Africa', + 'name': 'Burundi', + 'capital': 'Bujumbura'}, + {'timezones': ['Africa/Porto-Novo'], + 'alpha-2-code': 'BJ', + 'alpha-3-code': 'BEN', + 'continent': 'Africa', + 'name': 'Benin', + 'capital': 'Porto-Novo'}, + {'timezones': ['Asia/Brunei'], + 'alpha-2-code': 'BN', + 'alpha-3-code': 'BRN', + 'continent': 'Asia', + 'name': 'Brunei Darussalam', + 'capital': 'Bandar Seri Begawan'}, + {'timezones': ['America/La_Paz'], + 'alpha-2-code': 'BO', + 'alpha-3-code': 'BOL', + 'continent': 'South America', + 'name': 'Bolivia', + 'capital': 'Sucre'}, + {'timezones': ['America/Noronha', + 'America/Belem', + 'America/Fortaleza', + 'America/Recife', + 'America/Araguaina', + 'America/Maceio', + 'America/Bahia', + 'America/Sao_Paulo', + 'America/Campo_Grande', + 'America/Cuiaba', + 'America/Porto_Velho', + 'America/Boa_Vista', + 'America/Manaus', + 'America/Eirunepe', + 'America/Rio_Branco'], + 'alpha-2-code': 'BR', + 'alpha-3-code': 'BRA', + 'continent': 'South America', + 'name': 'Brazil', + 'capital': 'Bras\xc3\xadlia'}, + {'timezones': ['America/Nassau'], + 'alpha-2-code': 'BS', + 'alpha-3-code': 'BHS', + 'continent': 'North America', + 'name': 'Bahamas', + 'capital': 'Nassau'}, + {'timezones': ['Asia/Thimphu'], + 'alpha-2-code': 'BT', + 'alpha-3-code': 'BTN', + 'continent': 'Asia', + 'name': 'Bhutan', + 'capital': 'Thimphu'}, + {'timezones': ['Africa/Gaborone'], + 'alpha-2-code': 'BW', + 'alpha-3-code': 'BWA', + 'continent': 'Africa', + 'name': 'Botswana', + 'capital': 'Gaborone'}, + {'timezones': ['Europe/Minsk'], + 'alpha-2-code': 'BY', + 'alpha-3-code': 'BLR', + 'continent': 'Europe', + 'name': 'Belarus', + 'capital': 'Minsk'}, + {'timezones': ['America/Belize'], + 'alpha-2-code': 'BZ', + 'alpha-3-code': 'BLZ', + 'continent': 'North America', + 'name': 'Belize', + 'capital': 'Belmopan'}, + {'timezones': ['America/St_Johns', + 'America/Halifax', + 'America/Glace_Bay', + 'America/Moncton', + 'America/Goose_Bay', + 'America/Blanc-Sablon', + 'America/Montreal', + 'America/Toronto', + 'America/Nipigon', + 'America/Thunder_Bay', + 'America/Pangnirtung', + 'America/Iqaluit', + 'America/Atikokan', + 'America/Rankin_Inlet', + 'America/Winnipeg', + 'America/Rainy_River', + 'America/Cambridge_Bay', + 'America/Regina', + 'America/Swift_Current', + 'America/Edmonton', + 'America/Yellowknife', + 'America/Inuvik', + 'America/Dawson_Creek', + 'America/Vancouver', + 'America/Whitehorse', + 'America/Dawson'], + 'alpha-2-code': 'CA', + 'alpha-3-code': 'CAN', + 'continent': 'North America', + 'name': 'Canada', + 'capital': 'Ottawa'}, + {'timezones': ['Africa/Kinshasa', + 'Africa/Lubumbashi'], + 'alpha-2-code': 'CD', + 'alpha-3-code': 'COD', + 'continent': 'Africa', + 'name': 'Democratic Republic of the Congo', + 'capital': 'Kinshasa'}, + {'timezones': ['Africa/Brazzaville'], + 'alpha-2-code': 'CG', + 'alpha-3-code': 'COG', + 'continent': 'Africa', + 'name': 'Republic of the Congo', + 'capital': 'Brazzaville'}, + {'timezones': ['Africa/Abidjan'], + 'alpha-2-code': 'CI', + 'alpha-3-code': 'CIV', + 'continent': 'Africa', + 'name': "C\xc3\xb4te d'Ivoire", + 'capital': 'Yamoussoukro'}, + {'timezones': ['America/Santiago', + 'Pacific/Easter'], + 'alpha-2-code': 'CL', + 'alpha-3-code': 'CHL', + 'continent': 'South America', + 'name': 'Chile', + 'capital': 'Santiago'}, + {'timezones': ['Africa/Douala'], + 'alpha-2-code': 'CM', + 'alpha-3-code': 'CMR', + 'continent': 'Africa', + 'name': 'Cameroon', + 'capital': 'Yaound\xc3\xa9'}, + {'timezones': ['Asia/Shanghai', + 'Asia/Harbin', + 'Asia/Chongqing', + 'Asia/Urumqi', + 'Asia/Kashgar'], + 'alpha-2-code': 'CN', + 'alpha-3-code': 'CHN', + 'continent': 'Asia', + 'name': "People's Republic of China", + 'capital': 'Beijing'}, + {'timezones': ['America/Bogota'], + 'alpha-2-code': 'CO', + 'alpha-3-code': 'COL', + 'continent': 'South America', + 'name': 'Colombia', + 'capital': 'Bogot\xc3\xa1'}, + {'timezones': ['America/Costa_Rica'], + 'alpha-2-code': 'CR', + 'alpha-3-code': 'CRI', + 'continent': 'North America', + 'name': 'Costa Rica', + 'capital': 'San Jos\xc3\xa9'}, + {'timezones': ['America/Havana'], + 'alpha-2-code': 'CU', + 'alpha-3-code': 'CUB', + 'continent': 'North America', + 'name': 'Cuba', + 'capital': 'Havana'}, + {'timezones': ['Atlantic/Cape_Verde'], + 'alpha-2-code': 'CV', + 'alpha-3-code': 'CPV', + 'continent': 'Africa', + 'name': 'Cape Verde', + 'capital': 'Praia'}, + {'timezones': ['Asia/Nicosia'], + 'alpha-2-code': 'CY', + 'alpha-3-code': 'CYP', + 'continent': 'Asia', + 'name': 'Cyprus', + 'capital': 'Nicosia'}, + {'timezones': ['Europe/Prague'], + 'alpha-2-code': 'CZ', + 'alpha-3-code': 'CZE', + 'continent': 'Europe', + 'name': 'Czech Republic', + 'capital': 'Prague'}, + {'timezones': ['Europe/Berlin'], + 'alpha-2-code': 'DE', + 'alpha-3-code': 'DEU', + 'continent': 'Europe', + 'name': 'Germany', + 'capital': 'Berlin'}, + {'timezones': ['Africa/Djibouti'], + 'alpha-2-code': 'DJ', + 'alpha-3-code': 'DJI', + 'continent': 'Africa', + 'name': 'Djibouti', + 'capital': 'Djibouti City'}, + {'timezones': ['Europe/Copenhagen'], + 'alpha-2-code': 'DK', + 'alpha-3-code': 'DNK', + 'continent': 'Europe', + 'name': 'Denmark', + 'capital': 'Copenhagen'}, + {'timezones': ['America/Dominica'], + 'alpha-2-code': 'DM', + 'alpha-3-code': 'DMA', + 'continent': 'North America', + 'name': 'Dominica', + 'capital': 'Roseau'}, + {'timezones': ['America/Santo_Domingo'], + 'alpha-2-code': 'DO', + 'alpha-3-code': 'DOM', + 'continent': 'North America', + 'name': 'Dominican Republic', + 'capital': 'Santo Domingo'}, + {'timezones': ['America/Guayaquil', + 'Pacific/Galapagos'], + 'alpha-2-code': 'EC', + 'alpha-3-code': 'ECU', + 'continent': 'South America', + 'name': 'Ecuador', + 'capital': 'Quito'}, + {'timezones': ['Europe/Tallinn'], + 'alpha-2-code': 'EE', + 'alpha-3-code': 'EST', + 'continent': 'Europe', + 'name': 'Estonia', + 'capital': 'Tallinn'}, + {'timezones': ['Africa/Cairo'], + 'alpha-2-code': 'EG', + 'alpha-3-code': 'EGY', + 'continent': 'Africa', + 'name': 'Egypt', + 'capital': 'Cairo'}, + {'timezones': ['Africa/Asmera'], + 'alpha-2-code': 'ER', + 'alpha-3-code': 'ERI', + 'continent': 'Africa', + 'name': 'Eritrea', + 'capital': 'Asmara'}, + {'timezones': ['Africa/Addis_Ababa'], + 'alpha-2-code': 'ET', + 'alpha-3-code': 'ETH', + 'continent': 'Africa', + 'name': 'Ethiopia', + 'capital': 'Addis Ababa'}, + {'timezones': ['Europe/Helsinki'], + 'alpha-2-code': 'FI', + 'alpha-3-code': 'FIN', + 'continent': 'Europe', + 'name': 'Finland', + 'capital': 'Helsinki'}, + {'timezones': ['Pacific/Fiji'], + 'alpha-2-code': 'FJ', + 'alpha-3-code': 'FJI', + 'continent': 'Oceania', + 'name': 'Fiji', + 'capital': 'Suva'}, + {'timezones': ['Europe/Paris'], + 'alpha-2-code': 'FR', + 'alpha-3-code': 'FRA', + 'continent': 'Europe', + 'name': 'France', + 'capital': 'Paris'}, + {'timezones': ['Africa/Libreville'], + 'alpha-2-code': 'GA', + 'alpha-3-code': 'GAB', + 'continent': 'Africa', + 'name': 'Gabon', + 'capital': 'Libreville'}, + {'timezones': ['Asia/Tbilisi'], + 'alpha-2-code': 'GE', + 'alpha-3-code': 'GEO', + 'continent': 'Asia', + 'name': 'Georgia', + 'capital': 'Tbilisi'}, + {'timezones': ['Africa/Accra'], + 'alpha-2-code': 'GH', + 'alpha-3-code': 'GHA', + 'continent': 'Africa', + 'name': 'Ghana', + 'capital': 'Accra'}, + {'timezones': ['Africa/Banjul'], + 'alpha-2-code': 'GM', + 'alpha-3-code': 'GMB', + 'continent': 'Africa', + 'name': 'The Gambia', + 'capital': 'Banjul'}, + {'timezones': ['Africa/Conakry'], + 'alpha-2-code': 'GN', + 'alpha-3-code': 'GIN', + 'continent': 'Africa', + 'name': 'Guinea', + 'capital': 'Conakry'}, + {'timezones': ['Europe/Athens'], + 'alpha-2-code': 'GR', + 'alpha-3-code': 'GRC', + 'continent': 'Europe', + 'name': 'Greece', + 'capital': 'Athens'}, + {'timezones': ['America/Guatemala'], + 'alpha-2-code': 'GT', + 'alpha-3-code': 'GTM', + 'continent': 'North America', + 'name': 'Guatemala', + 'capital': 'Guatemala City'}, + {'timezones': ['America/Guatemala'], + 'alpha-2-code': 'HT', + 'alpha-3-code': 'HTI', + 'continent': 'North America', + 'name': 'Haiti', + 'capital': 'Port-au-Prince'}, + {'timezones': ['Africa/Bissau'], + 'alpha-2-code': 'GW', + 'alpha-3-code': 'GNB', + 'continent': 'Africa', + 'name': 'Guinea-Bissau', + 'capital': 'Bissau'}, + {'timezones': ['America/Guyana'], + 'alpha-2-code': 'GY', + 'alpha-3-code': 'GUY', + 'continent': 'South America', + 'name': 'Guyana', + 'capital': 'Georgetown'}, + {'timezones': ['America/Tegucigalpa'], + 'alpha-2-code': 'HN', + 'alpha-3-code': 'HND', + 'continent': 'North America', + 'name': 'Honduras', + 'capital': 'Tegucigalpa'}, + {'timezones': ['Europe/Budapest'], + 'alpha-2-code': 'HU', + 'alpha-3-code': 'HUN', + 'continent': 'Europe', + 'name': 'Hungary', + 'capital': 'Budapest'}, + {'timezones': ['Asia/Jakarta', + 'Asia/Pontianak', + 'Asia/Makassar', + 'Asia/Jayapura'], + 'alpha-2-code': 'ID', + 'alpha-3-code': 'IDN', + 'continent': 'Asia', + 'name': 'Indonesia', + 'capital': 'Jakarta'}, + {'timezones': ['Europe/Dublin'], + 'alpha-2-code': 'IE', + 'alpha-3-code': 'IRL', + 'continent': 'Europe', + 'name': 'Republic of Ireland', + 'capital': 'Dublin'}, + {'timezones': ['Asia/Jerusalem'], + 'alpha-2-code': 'IL', + 'alpha-3-code': 'ISR', + 'continent': 'Asia', + 'name': 'Israel', + 'capital': 'Jerusalem'}, + {'timezones': ['Asia/Calcutta'], + 'alpha-2-code': 'IN', + 'alpha-3-code': 'IND', + 'continent': 'Asia', + 'name': 'India', + 'capital': 'New Delhi'}, + {'timezones': ['Asia/Baghdad'], + 'alpha-2-code': 'IQ', + 'alpha-3-code': 'IRQ', + 'continent': 'Asia', + 'name': 'Iraq', + 'capital': 'Baghdad'}, + {'timezones': ['Asia/Tehran'], + 'alpha-2-code': 'IR', + 'alpha-3-code': 'IRN', + 'continent': 'Asia', + 'name': 'Iran', + 'capital': 'Tehran'}, + {'timezones': ['Atlantic/Reykjavik'], + 'alpha-2-code': 'IS', + 'alpha-3-code': 'ISL', + 'continent': 'Europe', + 'name': 'Iceland', + 'capital': 'Reykjav\xc3\xadk'}, + {'timezones': ['Europe/Rome'], + 'alpha-2-code': 'IT', + 'alpha-3-code': 'ITA', + 'continent': 'Europe', + 'name': 'Italy', + 'capital': 'Rome'}, + {'timezones': ['America/Jamaica'], + 'alpha-2-code': 'JM', + 'alpha-3-code': 'JAM', + 'continent': 'North America', + 'name': 'Jamaica', + 'capital': 'Kingston'}, + {'timezones': ['Asia/Amman'], + 'alpha-2-code': 'JO', + 'alpha-3-code': 'JOR', + 'continent': 'Asia', + 'name': 'Jordan', + 'capital': 'Amman'}, + {'timezones': ['Asia/Tokyo'], + 'alpha-2-code': 'JP', + 'alpha-3-code': 'JPN', + 'continent': 'Asia', + 'name': 'Japan', + 'capital': 'Tokyo'}, + {'timezones': ['Africa/Nairobi'], + 'alpha-2-code': 'KE', + 'alpha-3-code': 'KEN', + 'continent': 'Africa', + 'name': 'Kenya', + 'capital': 'Nairobi'}, + {'timezones': ['Asia/Bishkek'], + 'alpha-2-code': 'KG', + 'alpha-3-code': 'KGZ', + 'continent': 'Asia', + 'name': 'Kyrgyzstan', + 'capital': 'Bishkek'}, + {'timezones': ['Pacific/Tarawa', + 'Pacific/Enderbury', + 'Pacific/Kiritimati'], + 'alpha-2-code': 'KI', + 'alpha-3-code': 'KIR', + 'continent': 'Oceania', + 'name': 'Kiribati', + 'capital': 'Tarawa'}, + {'timezones': ['Asia/Pyongyang'], + 'alpha-2-code': 'KP', + 'alpha-3-code': 'PRK', + 'continent': 'Asia', + 'name': 'North Korea', + 'capital': 'Pyongyang'}, + {'timezones': ['Asia/Seoul'], + 'alpha-2-code': 'KR', + 'alpha-3-code': 'KOR', + 'continent': 'Asia', + 'name': 'South Korea', + 'capital': 'Seoul'}, + {'timezones': ['Asia/Kuwait'], + 'alpha-2-code': 'KW', + 'alpha-3-code': 'KWT', + 'continent': 'Asia', + 'name': 'Kuwait', + 'capital': 'Kuwait City'}, + {'timezones': ['Asia/Beirut'], + 'alpha-2-code': 'LB', + 'alpha-3-code': 'LBN', + 'continent': 'Asia', + 'name': 'Lebanon', + 'capital': 'Beirut'}, + {'timezones': ['Europe/Vaduz'], + 'alpha-2-code': 'LI', + 'alpha-3-code': 'LIE', + 'continent': 'Europe', + 'name': 'Liechtenstein', + 'capital': 'Vaduz'}, + {'timezones': ['Africa/Monrovia'], + 'alpha-2-code': 'LR', + 'alpha-3-code': 'LBR', + 'continent': 'Africa', + 'name': 'Liberia', + 'capital': 'Monrovia'}, + {'timezones': ['Africa/Maseru'], + 'alpha-2-code': 'LS', + 'alpha-3-code': 'LSO', + 'continent': 'Africa', + 'name': 'Lesotho', + 'capital': 'Maseru'}, + {'timezones': ['Europe/Vilnius'], + 'alpha-2-code': 'LT', + 'alpha-3-code': 'LTU', + 'continent': 'Europe', + 'name': 'Lithuania', + 'capital': 'Vilnius'}, + {'timezones': ['Europe/Luxembourg'], + 'alpha-2-code': 'LU', + 'alpha-3-code': 'LUX', + 'continent': 'Europe', + 'name': 'Luxembourg', + 'capital': 'Luxembourg City'}, + {'timezones': ['Europe/Riga'], + 'alpha-2-code': 'LV', + 'alpha-3-code': 'LVA', + 'continent': 'Europe', + 'name': 'Latvia', + 'capital': 'Riga'}, + {'timezones': ['Africa/Tripoli'], + 'alpha-2-code': 'LY', + 'alpha-3-code': 'LBY', + 'continent': 'Africa', + 'name': 'Libya', + 'capital': 'Tripoli'}, + {'timezones': ['Indian/Antananarivo'], + 'alpha-2-code': 'MG', + 'alpha-3-code': 'MDG', + 'continent': 'Africa', + 'name': 'Madagascar', + 'capital': 'Antananarivo'}, + {'timezones': ['Pacific/Majuro', + 'Pacific/Kwajalein'], + 'alpha-2-code': 'MH', + 'alpha-3-code': 'MHL', + 'continent': 'Oceania', + 'name': 'Marshall Islands', + 'capital': 'Majuro'}, + {'timezones': ['Europe/Skopje'], + 'alpha-2-code': 'MK', + 'alpha-3-code': 'MKD', + 'continent': 'Europe', + 'name': 'Macedonia', + 'capital': 'Skopje'}, + {'timezones': ['Africa/Bamako'], + 'alpha-2-code': 'ML', + 'alpha-3-code': 'MLI', + 'continent': 'Africa', + 'name': 'Mali', + 'capital': 'Bamako'}, + {'timezones': ['Asia/Rangoon'], + 'alpha-2-code': 'MM', + 'alpha-3-code': 'MMR', + 'continent': 'Asia', + 'name': 'Myanmar', + 'capital': 'Naypyidaw'}, + {'timezones': ['Asia/Ulaanbaatar', + 'Asia/Hovd', + 'Asia/Choibalsan'], + 'alpha-2-code': 'MN', + 'alpha-3-code': 'MNG', + 'continent': 'Asia', + 'name': 'Mongolia', + 'capital': 'Ulaanbaatar'}, + {'timezones': ['Africa/Nouakchott'], + 'alpha-2-code': 'MR', + 'alpha-3-code': 'MRT', + 'continent': 'Africa', + 'name': 'Mauritania', + 'capital': 'Nouakchott'}, + {'timezones': ['Europe/Malta'], + 'alpha-2-code': 'MT', + 'alpha-3-code': 'MLT', + 'continent': 'Europe', + 'name': 'Malta', + 'capital': 'Valletta'}, + {'timezones': ['Indian/Mauritius'], + 'alpha-2-code': 'MU', + 'alpha-3-code': 'MUS', + 'continent': 'Africa', + 'name': 'Mauritius', + 'capital': 'Port Louis'}, + {'timezones': ['Indian/Maldives'], + 'alpha-2-code': 'MV', + 'alpha-3-code': 'MDV', + 'continent': 'Asia', + 'name': 'Maldives', + 'capital': 'Mal\xc3\xa9'}, + {'timezones': ['Africa/Blantyre'], + 'alpha-2-code': 'MW', + 'alpha-3-code': 'MWI', + 'continent': 'Africa', + 'name': 'Malawi', + 'capital': 'Lilongwe'}, + {'timezones': ['America/Mexico_City', + 'America/Cancun', + 'America/Merida', + 'America/Monterrey', + 'America/Mazatlan', + 'America/Chihuahua', + 'America/Hermosillo', + 'America/Tijuana'], + 'alpha-2-code': 'MX', + 'alpha-3-code': 'MEX', + 'continent': 'North America', + 'name': 'Mexico', + 'capital': 'Mexico City'}, + {'timezones': ['Asia/Kuala_Lumpur', + 'Asia/Kuching'], + 'alpha-2-code': 'MY', + 'alpha-3-code': 'MYS', + 'continent': 'Asia', + 'name': 'Malaysia', + 'capital': 'Kuala Lumpur'}, + {'timezones': ['Africa/Maputo'], + 'alpha-2-code': 'MZ', + 'alpha-3-code': 'MOZ', + 'continent': 'Africa', + 'name': 'Mozambique', + 'capital': 'Maputo'}, + {'timezones': ['Africa/Windhoek'], + 'alpha-2-code': 'NA', + 'alpha-3-code': 'NAM', + 'continent': 'Africa', + 'name': 'Namibia', + 'capital': 'Windhoek'}, + {'timezones': ['Africa/Niamey'], + 'alpha-2-code': 'NE', + 'alpha-3-code': 'NER', + 'continent': 'Africa', + 'name': 'Niger', + 'capital': 'Niamey'}, + {'timezones': ['Africa/Lagos'], + 'alpha-2-code': 'NG', + 'alpha-3-code': 'NGA', + 'continent': 'Africa', + 'name': 'Nigeria', + 'capital': 'Abuja'}, + {'timezones': ['America/Managua'], + 'alpha-2-code': 'NI', + 'alpha-3-code': 'NIC', + 'continent': 'North America', + 'name': 'Nicaragua', + 'capital': 'Managua'}, + {'timezones': ['Europe/Amsterdam'], + 'alpha-2-code': 'NL', + 'alpha-3-code': 'NLD', + 'continent': 'Europe', + 'name': 'Kingdom of the Netherlands', + 'capital': 'Amsterdam'}, + {'timezones': ['Europe/Oslo'], + 'alpha-2-code': 'NO', + 'alpha-3-code': 'NOR', + 'continent': 'Europe', + 'name': 'Norway', + 'capital': 'Oslo'}, + {'timezones': ['Asia/Katmandu'], + 'alpha-2-code': 'NP', + 'alpha-3-code': 'NPL', + 'continent': 'Asia', + 'name': 'Nepal', + 'capital': 'Kathmandu'}, + {'timezones': ['Pacific/Nauru'], + 'alpha-2-code': 'NR', + 'alpha-3-code': 'NRU', + 'continent': 'Oceania', + 'name': 'Nauru', + 'capital': 'Yaren'}, + {'timezones': ['Pacific/Auckland', + 'Pacific/Chatham'], + 'alpha-2-code': 'NZ', + 'alpha-3-code': 'NZL', + 'continent': 'Oceania', + 'name': 'New Zealand', + 'capital': 'Wellington'}, + {'timezones': ['Asia/Muscat'], + 'alpha-2-code': 'OM', + 'alpha-3-code': 'OMN', + 'continent': 'Asia', + 'name': 'Oman', + 'capital': 'Muscat'}, + {'timezones': ['America/Panama'], + 'alpha-2-code': 'PA', + 'alpha-3-code': 'PAN', + 'continent': 'North America', + 'name': 'Panama', + 'capital': 'Panama City'}, + {'timezones': ['America/Lima'], + 'alpha-2-code': 'PE', + 'alpha-3-code': 'PER', + 'continent': 'South America', + 'name': 'Peru', + 'capital': 'Lima'}, + {'timezones': ['Pacific/Port_Moresby'], + 'alpha-2-code': 'PG', + 'alpha-3-code': 'PNG', + 'continent': 'Oceania', + 'name': 'Papua New Guinea', + 'capital': 'Port Moresby'}, + {'timezones': ['Asia/Manila'], + 'alpha-2-code': 'PH', + 'alpha-3-code': 'PHL', + 'continent': 'Asia', + 'name': 'Philippines', + 'capital': 'Manila'}, + {'timezones': ['Asia/Karachi'], + 'alpha-2-code': 'PK', + 'alpha-3-code': 'PAK', + 'continent': 'Asia', + 'name': 'Pakistan', + 'capital': 'Islamabad'}, + {'timezones': ['Europe/Warsaw'], + 'alpha-2-code': 'PL', + 'alpha-3-code': 'POL', + 'continent': 'Europe', + 'name': 'Poland', + 'capital': 'Warsaw'}, + {'timezones': ['Europe/Lisbon', + 'Atlantic/Madeira', + 'Atlantic/Azores'], + 'alpha-2-code': 'PT', + 'alpha-3-code': 'PRT', + 'continent': 'Europe', + 'name': 'Portugal', + 'capital': 'Lisbon'}, + {'timezones': ['Pacific/Palau'], + 'alpha-2-code': 'PW', + 'alpha-3-code': 'PLW', + 'continent': 'Oceania', + 'name': 'Palau', + 'capital': 'Ngerulmud'}, + {'timezones': ['America/Asuncion'], + 'alpha-2-code': 'PY', + 'alpha-3-code': 'PRY', + 'continent': 'South America', + 'name': 'Paraguay', + 'capital': 'Asunci\xc3\xb3n'}, + {'timezones': ['Asia/Qatar'], + 'alpha-2-code': 'QA', + 'alpha-3-code': 'QAT', + 'continent': 'Asia', + 'name': 'Qatar', + 'capital': 'Doha'}, + {'timezones': ['Europe/Bucharest'], + 'alpha-2-code': 'RO', + 'alpha-3-code': 'ROU', + 'continent': 'Europe', + 'name': 'Romania', + 'capital': 'Bucharest'}, + {'timezones': ['Europe/Kaliningrad', + 'Europe/Moscow', + 'Europe/Volgograd', + 'Europe/Samara', + 'Asia/Yekaterinburg', + 'Asia/Omsk', + 'Asia/Novosibirsk', + 'Asia/Krasnoyarsk', + 'Asia/Irkutsk', + 'Asia/Yakutsk', + 'Asia/Vladivostok', + 'Asia/Sakhalin', + 'Asia/Magadan', + 'Asia/Kamchatka', + 'Asia/Anadyr'], + 'alpha-2-code': 'RU', + 'alpha-3-code': 'RUS', + 'continent': 'Europe', + 'name': 'Russia', + 'capital': 'Moscow'}, + {'timezones': ['Africa/Kigali'], + 'alpha-2-code': 'RW', + 'alpha-3-code': 'RWA', + 'continent': 'Africa', + 'name': 'Rwanda', + 'capital': 'Kigali'}, + {'timezones': ['Asia/Riyadh'], + 'alpha-2-code': 'SA', + 'alpha-3-code': 'SAU', + 'continent': 'Asia', + 'name': 'Saudi Arabia', + 'capital': 'Riyadh'}, + {'timezones': ['Pacific/Guadalcanal'], + 'alpha-2-code': 'SB', + 'alpha-3-code': 'SLB', + 'continent': 'Oceania', + 'name': 'Solomon Islands', + 'capital': 'Honiara'}, + {'timezones': ['Indian/Mahe'], + 'alpha-2-code': 'SC', + 'alpha-3-code': 'SYC', + 'continent': 'Africa', + 'name': 'Seychelles', + 'capital': 'Victoria'}, + {'timezones': ['Africa/Khartoum'], + 'alpha-2-code': 'SD', + 'alpha-3-code': 'SDN', + 'continent': 'Africa', + 'name': 'Sudan', + 'capital': 'Khartoum'}, + {'timezones': ['Europe/Stockholm'], + 'alpha-2-code': 'SE', + 'alpha-3-code': 'SWE', + 'continent': 'Europe', + 'name': 'Sweden', + 'capital': 'Stockholm'}, + {'timezones': ['Asia/Singapore'], + 'alpha-2-code': 'SG', + 'alpha-3-code': 'SGP', + 'continent': 'Asia', + 'name': 'Singapore', + 'capital': 'Singapore'}, + {'timezones': ['Europe/Ljubljana'], + 'alpha-2-code': 'SI', + 'alpha-3-code': 'SVN', + 'continent': 'Europe', + 'name': 'Slovenia', + 'capital': 'Ljubljana'}, + {'timezones': ['Europe/Bratislava'], + 'alpha-2-code': 'SK', + 'alpha-3-code': 'SVK', + 'continent': 'Europe', + 'name': 'Slovakia', + 'capital': 'Bratislava'}, + {'timezones': ['Africa/Freetown'], + 'alpha-2-code': 'SL', + 'alpha-3-code': 'SLE', + 'continent': 'Africa', + 'name': 'Sierra Leone', + 'capital': 'Freetown'}, + {'timezones': ['Europe/San_Marino'], + 'alpha-2-code': 'SM', + 'alpha-3-code': 'SMR', + 'continent': 'Europe', + 'name': 'San Marino', + 'capital': 'San Marino'}, + {'timezones': ['Africa/Dakar'], + 'alpha-2-code': 'SN', + 'alpha-3-code': 'SEN', + 'continent': 'Africa', + 'name': 'Senegal', + 'capital': 'Dakar'}, + {'timezones': ['Africa/Mogadishu'], + 'alpha-2-code': 'SO', + 'alpha-3-code': 'SOM', + 'continent': 'Africa', + 'name': 'Somalia', + 'capital': 'Mogadishu'}, + {'timezones': ['America/Paramaribo'], + 'alpha-2-code': 'SR', + 'alpha-3-code': 'SUR', + 'continent': 'South America', + 'name': 'Suriname', + 'capital': 'Paramaribo'}, + {'timezones': ['Africa/Sao_Tome'], + 'alpha-2-code': 'ST', + 'alpha-3-code': 'STP', + 'continent': 'Africa', + 'name': 'S\xc3\xa3o Tom\xc3\xa9 and Pr\xc3\xadncipe', + 'capital': 'S\xc3\xa3o Tom\xc3\xa9'}, + {'timezones': ['Asia/Damascus'], + 'alpha-2-code': 'SY', + 'alpha-3-code': 'SYR', + 'continent': 'Asia', + 'name': 'Syria', + 'capital': 'Damascus'}, + {'timezones': ['Africa/Lome'], + 'alpha-2-code': 'TG', + 'alpha-3-code': 'TGO', + 'continent': 'Africa', + 'name': 'Togo', + 'capital': 'Lom\xc3\xa9'}, + {'timezones': ['Asia/Bangkok'], + 'alpha-2-code': 'TH', + 'alpha-3-code': 'THA', + 'continent': 'Asia', + 'name': 'Thailand', + 'capital': 'Bangkok'}, + {'timezones': ['Asia/Dushanbe'], + 'alpha-2-code': 'TJ', + 'alpha-3-code': 'TJK', + 'continent': 'Asia', + 'name': 'Tajikistan', + 'capital': 'Dushanbe'}, + {'timezones': ['Asia/Ashgabat'], + 'alpha-2-code': 'TM', + 'alpha-3-code': 'TKM', + 'continent': 'Asia', + 'name': 'Turkmenistan', + 'capital': 'Ashgabat'}, + {'timezones': ['Africa/Tunis'], + 'alpha-2-code': 'TN', + 'alpha-3-code': 'TUN', + 'continent': 'Africa', + 'name': 'Tunisia', + 'capital': 'Tunis'}, + {'timezones': ['Pacific/Tongatapu'], + 'alpha-2-code': 'TO', + 'alpha-3-code': 'TON', + 'continent': 'Oceania', + 'name': 'Tonga', + 'capital': 'Nuku\xca\xbbalofa'}, + {'timezones': ['Europe/Istanbul'], + 'alpha-2-code': 'TR', + 'alpha-3-code': 'TUR', + 'continent': 'Asia', + 'name': 'Turkey', + 'capital': 'Ankara'}, + {'timezones': ['America/Port_of_Spain'], + 'alpha-2-code': 'TT', + 'alpha-3-code': 'TTO', + 'continent': 'North America', + 'name': 'Trinidad and Tobago', + 'capital': 'Port of Spain'}, + {'timezones': ['Pacific/Funafuti'], + 'alpha-2-code': 'TV', + 'alpha-3-code': 'TUV', + 'continent': 'Oceania', + 'name': 'Tuvalu', + 'capital': 'Funafuti'}, + {'timezones': ['Africa/Dar_es_Salaam'], + 'alpha-2-code': 'TZ', + 'alpha-3-code': 'TZA', + 'continent': 'Africa', + 'name': 'Tanzania', + 'capital': 'Dodoma'}, + {'timezones': ['Europe/Kiev', + 'Europe/Uzhgorod', + 'Europe/Zaporozhye', + 'Europe/Simferopol'], + 'alpha-2-code': 'UA', + 'alpha-3-code': 'UKR', + 'continent': 'Europe', + 'name': 'Ukraine', + 'capital': 'Kiev'}, + {'timezones': ['Africa/Kampala'], + 'alpha-2-code': 'UG', + 'alpha-3-code': 'UGA', + 'continent': 'Africa', + 'name': 'Uganda', + 'capital': 'Kampala'}, + {'timezones': ['America/New_York', + 'America/Detroit', + 'America/Kentucky/Louisville', + 'America/Kentucky/Monticello', + 'America/Indiana/Indianapolis', + 'America/Indiana/Marengo', + 'America/Indiana/Knox', + 'America/Indiana/Vevay', + 'America/Chicago', + 'America/Indiana/Vincennes', + 'America/Indiana/Petersburg', + 'America/Menominee', + 'America/North_Dakota/Center', + 'America/North_Dakota/New_Salem', + 'America/Denver', + 'America/Boise', + 'America/Shiprock', + 'America/Phoenix', + 'America/Los_Angeles', + 'America/Anchorage', + 'America/Juneau', + 'America/Yakutat', + 'America/Nome', + 'America/Adak', + 'Pacific/Honolulu'], + 'alpha-2-code': 'US', + 'alpha-3-code': 'USA', + 'continent': 'North America', + 'name': 'United States', + 'capital': 'Washington, D.C.'}, + {'timezones': ['America/Montevideo'], + 'alpha-2-code': 'UY', + 'alpha-3-code': 'URY', + 'continent': 'South America', + 'name': 'Uruguay', + 'capital': 'Montevideo'}, + {'timezones': ['Asia/Samarkand', + 'Asia/Tashkent'], + 'alpha-2-code': 'UZ', + 'alpha-3-code': 'UZB', + 'continent': 'Asia', + 'name': 'Uzbekistan', + 'capital': 'Tashkent'}, + {'timezones': ['Europe/Vatican'], + 'alpha-2-code': 'VA', + 'alpha-3-code': 'VAT', + 'continent': 'Europe', + 'name': 'Vatican City', + 'capital': 'Vatican City'}, + {'timezones': ['America/Caracas'], + 'alpha-2-code': 'VE', + 'alpha-3-code': 'VEN', + 'continent': 'South America', + 'name': 'Venezuela', + 'capital': 'Caracas'}, + {'timezones': ['Asia/Saigon'], + 'alpha-2-code': 'VN', + 'alpha-3-code': 'VNM', + 'continent': 'Asia', + 'name': 'Vietnam', + 'capital': 'Hanoi'}, + {'timezones': ['Pacific/Efate'], + 'alpha-2-code': 'VU', + 'alpha-3-code': 'VUT', + 'continent': 'Oceania', + 'name': 'Vanuatu', + 'capital': 'Port Vila'}, + {'timezones': ['Asia/Aden'], + 'alpha-2-code': 'YE', + 'alpha-3-code': 'YEM', + 'continent': 'Asia', + 'name': 'Yemen', + 'capital': "Sana'a"}, + {'timezones': ['Africa/Lusaka'], + 'alpha-2-code': 'ZM', + 'alpha-3-code': 'ZMB', + 'continent': 'Africa', + 'name': 'Zambia', + 'capital': 'Lusaka'}, + {'timezones': ['Africa/Harare'], + 'alpha-2-code': 'ZW', + 'alpha-3-code': 'ZWE', + 'continent': 'Africa', + 'name': 'Zimbabwe', + 'capital': 'Harare'}, + {'timezones': ['Africa/Algiers'], + 'alpha-2-code': 'DZ', + 'alpha-3-code': 'DZA', + 'continent': 'Africa', + 'name': 'Algeria', + 'capital': 'Algiers'}, + {'timezones': ['Europe/Sarajevo'], + 'alpha-2-code': 'BA', + 'alpha-3-code': 'BIH', + 'continent': 'Europe', + 'name': 'Bosnia and Herzegovina', + 'capital': 'Sarajevo'}, + {'timezones': ['Asia/Phnom_Penh'], + 'alpha-2-code': 'KH', + 'alpha-3-code': 'KHM', + 'continent': 'Asia', + 'name': 'Cambodia', + 'capital': 'Phnom Penh'}, + {'timezones': ['Africa/Bangui'], + 'alpha-2-code': 'CF', + 'alpha-3-code': 'CAF', + 'continent': 'Africa', + 'name': 'Central African Republic', + 'capital': 'Bangui'}, + {'timezones': ['Africa/Ndjamena'], + 'alpha-2-code': 'TD', + 'alpha-3-code': 'TCD', + 'continent': 'Africa', + 'name': 'Chad', + 'capital': "N'Djamena"}, + {'timezones': ['Indian/Comoro'], + 'alpha-2-code': 'KM', + 'alpha-3-code': 'COM', + 'continent': 'Africa', + 'name': 'Comoros', + 'capital': 'Moroni'}, + {'timezones': ['Europe/Zagreb'], + 'alpha-2-code': 'HR', + 'alpha-3-code': 'HRV', + 'continent': 'Europe', + 'name': 'Croatia', + 'capital': 'Zagreb'}, + {'timezones': ['Asia/Dili'], + 'alpha-2-code': 'TL', + 'alpha-3-code': 'TLS', + 'continent': 'Asia', + 'name': 'East Timor', + 'capital': 'Dili'}, + {'timezones': ['America/El_Salvador'], + 'alpha-2-code': 'SV', + 'alpha-3-code': 'SLV', + 'continent': 'North America', + 'name': 'El Salvador', + 'capital': 'San Salvador'}, + {'timezones': ['Africa/Malabo'], + 'alpha-2-code': 'GQ', + 'alpha-3-code': 'GNQ', + 'continent': 'Africa', + 'name': 'Equatorial Guinea', + 'capital': 'Malabo'}, + {'timezones': ['America/Grenada'], + 'alpha-2-code': 'GD', + 'alpha-3-code': 'GRD', + 'continent': 'North America', + 'name': 'Grenada', + 'capital': "St. George's"}, + {'timezones': ['Asia/Almaty', + 'Asia/Qyzylorda', + 'Asia/Aqtobe', + 'Asia/Aqtau', + 'Asia/Oral'], + 'alpha-2-code': 'KZ', + 'alpha-3-code': 'KAZ', + 'continent': 'Asia', + 'name': 'Kazakhstan', + 'capital': 'Astana'}, + {'timezones': ['Asia/Vientiane'], + 'alpha-2-code': 'LA', + 'alpha-3-code': 'LAO', + 'continent': 'Asia', + 'name': 'Laos', + 'capital': 'Vientiane'}, + {'timezones': ['Pacific/Truk', + 'Pacific/Ponape', + 'Pacific/Kosrae'], + 'alpha-2-code': 'FM', + 'alpha-3-code': 'FSM', + 'continent': 'Oceania', + 'name': 'Federated States of Micronesia', + 'capital': 'Palikir'}, + {'timezones': ['Europe/Chisinau'], + 'alpha-2-code': 'MD', + 'alpha-3-code': 'MDA', + 'continent': 'Europe', + 'name': 'Moldova', + 'capital': 'Chi\xc5\x9fin\xc4\x83u'}, + {'timezones': ['Europe/Monaco'], + 'alpha-2-code': 'MC', + 'alpha-3-code': 'MCO', + 'continent': 'Europe', + 'name': 'Monaco', + 'capital': 'Monaco'}, + {'timezones': ['Europe/Podgorica'], + 'alpha-2-code': 'ME', + 'alpha-3-code': 'MNE', + 'continent': 'Europe', + 'name': 'Montenegro', + 'capital': 'Podgorica'}, + {'timezones': ['Africa/Casablanca'], + 'alpha-2-code': 'MA', + 'alpha-3-code': 'MAR', + 'continent': 'Africa', + 'name': 'Morocco', + 'capital': 'Rabat'}, + {'timezones': ['America/St_Kitts'], + 'alpha-2-code': 'KN', + 'alpha-3-code': 'KNA', + 'continent': 'North America', + 'name': 'Saint Kitts and Nevis', + 'capital': 'Basseterre'}, + {'timezones': ['America/St_Lucia'], + 'alpha-2-code': 'LC', + 'alpha-3-code': 'LCA', + 'continent': 'North America', + 'name': 'Saint Lucia', + 'capital': 'Castries'}, + {'timezones': ['America/St_Vincent'], + 'alpha-2-code': 'VC', + 'alpha-3-code': 'VCT', + 'continent': 'North America', + 'name': 'Saint Vincent and the Grenadines', + 'capital': 'Kingstown'}, + {'timezones': ['Pacific/Apia'], + 'alpha-2-code': 'WS', + 'alpha-3-code': 'WSM', + 'continent': 'Oceania', + 'name': 'Samoa', + 'capital': 'Apia'}, + {'timezones': ['Europe/Belgrade'], + 'alpha-2-code': 'RS', + 'alpha-3-code': 'SRB', + 'continent': 'Europe', + 'name': 'Serbia', + 'capital': 'Belgrade'}, + {'timezones': ['Africa/Johannesburg'], + 'alpha-2-code': 'ZA', + 'alpha-3-code': 'ZAF', + 'continent': 'Africa', + 'name': 'South Africa', + 'capital': 'Pretoria'}, + {'timezones': ['Europe/Madrid', + 'Africa/Ceuta', + 'Atlantic/Canary'], + 'alpha-2-code': 'ES', + 'alpha-3-code': 'ESP', + 'continent': 'Europe', + 'name': 'Spain', + 'capital': 'Madrid'}, + {'timezones': ['Asia/Colombo'], + 'alpha-2-code': 'LK', + 'alpha-3-code': 'LKA', + 'continent': 'Asia', + 'name': 'Sri Lanka', + 'capital': 'Sri Jayewardenepura Kotte'}, + {'timezones': ['Africa/Mbabane'], + 'alpha-2-code': 'SZ', + 'alpha-3-code': 'SWZ', + 'continent': 'Africa', + 'name': 'Swaziland', + 'capital': 'Mbabane'}, + {'timezones': ['Europe/Zurich'], + 'alpha-2-code': 'CH', + 'alpha-3-code': 'CHE', + 'continent': 'Europe', + 'name': 'Switzerland', + 'capital': 'Bern'}, + {'timezones': ['Asia/Dubai'], + 'alpha-2-code': 'AE', + 'alpha-3-code': 'ARE', + 'continent': 'Asia', + 'name': 'United Arab Emirates', + 'capital': 'Abu Dhabi'}, + {'timezones': ['Europe/London'], + 'alpha-2-code': 'GB', + 'alpha-3-code': 'GBR', + 'continent': 'Europe', + 'name': 'United Kingdom', + 'capital': 'London'}, + ] + + regex = re.compile(timedelta_pattern) + + def unix_time(self, end_datetime=None, start_datetime=None): + """ + Get a timestamp between January 1, 1970 and now, unless passed + explicit start_datetime or end_datetime values. + :example 1061306726 + """ + start_datetime = self._parse_start_datetime(start_datetime) + end_datetime = self._parse_end_datetime(end_datetime) + return self.generator.random.randint(start_datetime, end_datetime) + + def time_delta(self, end_datetime=None): + """ + Get a timedelta object + """ + start_datetime = self._parse_start_datetime('now') + end_datetime = self._parse_end_datetime(end_datetime) + seconds = end_datetime - start_datetime + + ts = self.generator.random.randint(*sorted([0, seconds])) + return timedelta(seconds=ts) + + def date_time(self, tzinfo=None, end_datetime=None): + """ + Get a datetime object for a date between January 1, 1970 and now + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('2005-08-16 20:39:21') + :return datetime + """ + # NOTE: On windows, the lowest value you can get from windows is 86400 + # on the first day. Known python issue: + # https://bugs.python.org/issue30684 + return datetime(1970, 1, 1, tzinfo=tzinfo) + \ + timedelta(seconds=self.unix_time(end_datetime=end_datetime)) + + def date_time_ad(self, tzinfo=None, end_datetime=None, start_datetime=None): + """ + Get a datetime object for a date between January 1, 001 and now + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1265-03-22 21:15:52') + :return datetime + """ + + # 1970-01-01 00:00:00 UTC minus 62135596800 seconds is + # 0001-01-01 00:00:00 UTC. Since _parse_end_datetime() is used + # elsewhere where a default value of 0 is expected, we can't + # simply change that class method to use this magic number as a + # default value when None is provided. + + start_time = -62135596800 if start_datetime is None else self._parse_start_datetime(start_datetime) + end_datetime = self._parse_end_datetime(end_datetime) + + ts = self.generator.random.randint(start_time, end_datetime) + # NOTE: using datetime.fromtimestamp(ts) directly will raise + # a "ValueError: timestamp out of range for platform time_t" + # on some platforms due to system C functions; + # see http://stackoverflow.com/a/10588133/2315612 + # NOTE: On windows, the lowest value you can get from windows is 86400 + # on the first day. Known python issue: + # https://bugs.python.org/issue30684 + return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts) + + def iso8601(self, tzinfo=None, end_datetime=None): + """ + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example '2003-10-21T16:05:52+0000' + """ + return self.date_time(tzinfo, end_datetime=end_datetime).isoformat() + + def date(self, pattern='%Y-%m-%d', end_datetime=None): + """ + Get a date string between January 1, 1970 and now + :param pattern format + :example '2008-11-27' + """ + return self.date_time(end_datetime=end_datetime).strftime(pattern) + + def date_object(self, end_datetime=None): + """ + Get a date object between January 1, 1970 and now + :example datetime.date(2016, 9, 20) + """ + return self.date_time(end_datetime=end_datetime).date() + + def time(self, pattern='%H:%M:%S', end_datetime=None): + """ + Get a time string (24h format by default) + :param pattern format + :example '15:02:34' + """ + return self.date_time( + end_datetime=end_datetime).time().strftime(pattern) + + def time_object(self, end_datetime=None): + """ + Get a time object + :example datetime.time(15, 56, 56, 772876) + """ + return self.date_time(end_datetime=end_datetime).time() + + @classmethod + def _parse_start_datetime(cls, value): + if value is None: + return 0 + + return cls._parse_date_time(value) + + @classmethod + def _parse_end_datetime(cls, value): + if value is None: + return datetime_to_timestamp(datetime.now()) + + return cls._parse_date_time(value) + + @classmethod + def _parse_date_string(cls, value): + parts = cls.regex.match(value) + if not parts: + raise ParseError("Can't parse date string `{}`.".format(value)) + parts = parts.groupdict() + time_params = {} + for (name_, param_) in parts.items(): + if param_: + time_params[name_] = int(param_) + + if 'years' in time_params: + if 'days' not in time_params: + time_params['days'] = 0 + time_params['days'] += 365.24 * time_params.pop('years') + if 'months' in time_params: + if 'days' not in time_params: + time_params['days'] = 0 + time_params['days'] += 30.42 * time_params.pop('months') + + if not time_params: + raise ParseError("Can't parse date string `{}`.".format(value)) + return time_params + + @classmethod + def _parse_timedelta(cls, value): + if isinstance(value, timedelta): + return value.total_seconds() + if isinstance(value, str): + time_params = cls._parse_date_string(value) + return timedelta(**time_params).total_seconds() + if isinstance(value, (int, float)): + return value + raise ParseError("Invalid format for timedelta '{}'".format(value)) + + @classmethod + def _parse_date_time(cls, value, tzinfo=None): + if isinstance(value, (datetime, date, real_datetime, real_date)): + return datetime_to_timestamp(value) + now = datetime.now(tzinfo) + if isinstance(value, timedelta): + return datetime_to_timestamp(now + value) + if isinstance(value, str): + if value == 'now': + return datetime_to_timestamp(datetime.now(tzinfo)) + time_params = cls._parse_date_string(value) + return datetime_to_timestamp(now + timedelta(**time_params)) + if isinstance(value, int): + return datetime_to_timestamp(now + timedelta(value)) + raise ParseError("Invalid format for date '{}'".format(value)) + + @classmethod + def _parse_date(cls, value): + if isinstance(value, (datetime, real_datetime)): + return value.date() + elif isinstance(value, (date, real_date)): + return value + today = date.today() + if isinstance(value, timedelta): + return today + value + if isinstance(value, str): + if value in ('today', 'now'): + return today + time_params = cls._parse_date_string(value) + return today + timedelta(**time_params) + if isinstance(value, int): + return today + timedelta(value) + raise ParseError("Invalid format for date '{}'".format(value)) + + def date_time_between(self, start_date='-30y', end_date='now', tzinfo=None): + """ + Get a DateTime object based on a random date between two given dates. + Accepts date strings that can be recognized by strtotime(). + + :param start_date Defaults to 30 years ago + :param end_date Defaults to "now" + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1999-02-02 11:42:52') + :return DateTime + """ + start_date = self._parse_date_time(start_date, tzinfo=tzinfo) + end_date = self._parse_date_time(end_date, tzinfo=tzinfo) + if end_date - start_date <= 1: + ts = start_date + self.generator.random.random() + else: + ts = self.generator.random.randint(start_date, end_date) + if tzinfo is None: + return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts) + else: + return ( + datetime(1970, 1, 1, tzinfo=tzutc()) + timedelta(seconds=ts) + ).astimezone(tzinfo) + + def date_between(self, start_date='-30y', end_date='today'): + """ + Get a Date object based on a random date between two given dates. + Accepts date strings that can be recognized by strtotime(). + + :param start_date Defaults to 30 years ago + :param end_date Defaults to "today" + :example Date('1999-02-02') + :return Date + """ + + start_date = self._parse_date(start_date) + end_date = self._parse_date(end_date) + return self.date_between_dates(date_start=start_date, date_end=end_date) + + def future_datetime(self, end_date='+30d', tzinfo=None): + """ + Get a DateTime object based on a random date between 1 second form now + and a given date. + Accepts date strings that can be recognized by strtotime(). + + :param end_date Defaults to "+30d" + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1999-02-02 11:42:52') + :return DateTime + """ + return self.date_time_between( + start_date='+1s', end_date=end_date, tzinfo=tzinfo, + ) + + def future_date(self, end_date='+30d', tzinfo=None): + """ + Get a Date object based on a random date between 1 day from now and a + given date. + Accepts date strings that can be recognized by strtotime(). + + :param end_date Defaults to "+30d" + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1999-02-02 11:42:52') + :return DateTime + """ + return self.date_between(start_date='+1d', end_date=end_date) + + def past_datetime(self, start_date='-30d', tzinfo=None): + """ + Get a DateTime object based on a random date between a given date and 1 + second ago. + Accepts date strings that can be recognized by strtotime(). + + :param start_date Defaults to "-30d" + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1999-02-02 11:42:52') + :return DateTime + """ + return self.date_time_between( + start_date=start_date, end_date='-1s', tzinfo=tzinfo, + ) + + def past_date(self, start_date='-30d', tzinfo=None): + """ + Get a Date object based on a random date between a given date and 1 day + ago. + Accepts date strings that can be recognized by strtotime(). + + :param start_date Defaults to "-30d" + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1999-02-02 11:42:52') + :return DateTime + """ + return self.date_between(start_date=start_date, end_date='-1d') + + def date_time_between_dates( + self, + datetime_start=None, + datetime_end=None, + tzinfo=None): + """ + Takes two DateTime objects and returns a random datetime between the two + given datetimes. + Accepts DateTime objects. + + :param datetime_start: DateTime + :param datetime_end: DateTime + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('1999-02-02 11:42:52') + :return DateTime + """ + if datetime_start is None: + datetime_start = datetime.now(tzinfo) + + if datetime_end is None: + datetime_end = datetime.now(tzinfo) + + timestamp = self.generator.random.randint( + datetime_to_timestamp(datetime_start), + datetime_to_timestamp(datetime_end), + ) + try: + if tzinfo is None: + pick = datetime.fromtimestamp(timestamp, tzlocal()) + pick = pick.astimezone(tzutc()).replace(tzinfo=None) + else: + pick = datetime.fromtimestamp(timestamp, tzinfo) + except OverflowError: + raise OverflowError( + "You specified an end date with a timestamp bigger than the maximum allowed on this" + " system. Please specify an earlier date.", + ) + return pick + + def date_between_dates(self, date_start=None, date_end=None): + """ + Takes two Date objects and returns a random date between the two given dates. + Accepts Date or Datetime objects + + :param date_start: Date + :param date_end: Date + :return Date + """ + return self.date_time_between_dates(date_start, date_end).date() + + def date_time_this_century( + self, + before_now=True, + after_now=False, + tzinfo=None): + """ + Gets a DateTime object for the current century. + + :param before_now: include days in current century before today + :param after_now: include days in current century after today + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('2012-04-04 11:02:02') + :return DateTime + """ + now = datetime.now(tzinfo) + this_century_start = datetime( + now.year - (now.year % 100), 1, 1, tzinfo=tzinfo) + next_century_start = datetime( + min(this_century_start.year + 100, MAXYEAR), 1, 1, tzinfo=tzinfo) + + if before_now and after_now: + return self.date_time_between_dates( + this_century_start, next_century_start, tzinfo) + elif not before_now and after_now: + return self.date_time_between_dates(now, next_century_start, tzinfo) + elif not after_now and before_now: + return self.date_time_between_dates(this_century_start, now, tzinfo) + else: + return now + + def date_time_this_decade( + self, + before_now=True, + after_now=False, + tzinfo=None): + """ + Gets a DateTime object for the decade year. + + :param before_now: include days in current decade before today + :param after_now: include days in current decade after today + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('2012-04-04 11:02:02') + :return DateTime + """ + now = datetime.now(tzinfo) + this_decade_start = datetime( + now.year - (now.year % 10), 1, 1, tzinfo=tzinfo) + next_decade_start = datetime( + min(this_decade_start.year + 10, MAXYEAR), 1, 1, tzinfo=tzinfo) + + if before_now and after_now: + return self.date_time_between_dates( + this_decade_start, next_decade_start, tzinfo) + elif not before_now and after_now: + return self.date_time_between_dates(now, next_decade_start, tzinfo) + elif not after_now and before_now: + return self.date_time_between_dates(this_decade_start, now, tzinfo) + else: + return now + + def date_time_this_year( + self, + before_now=True, + after_now=False, + tzinfo=None): + """ + Gets a DateTime object for the current year. + + :param before_now: include days in current year before today + :param after_now: include days in current year after today + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('2012-04-04 11:02:02') + :return DateTime + """ + now = datetime.now(tzinfo) + this_year_start = now.replace( + month=1, day=1, hour=0, minute=0, second=0, microsecond=0) + next_year_start = datetime(now.year + 1, 1, 1, tzinfo=tzinfo) + + if before_now and after_now: + return self.date_time_between_dates( + this_year_start, next_year_start, tzinfo) + elif not before_now and after_now: + return self.date_time_between_dates(now, next_year_start, tzinfo) + elif not after_now and before_now: + return self.date_time_between_dates(this_year_start, now, tzinfo) + else: + return now + + def date_time_this_month( + self, + before_now=True, + after_now=False, + tzinfo=None): + """ + Gets a DateTime object for the current month. + + :param before_now: include days in current month before today + :param after_now: include days in current month after today + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('2012-04-04 11:02:02') + :return DateTime + """ + now = datetime.now(tzinfo) + this_month_start = now.replace( + day=1, hour=0, minute=0, second=0, microsecond=0) + + next_month_start = this_month_start + \ + relativedelta.relativedelta(months=1) + if before_now and after_now: + return self.date_time_between_dates( + this_month_start, next_month_start, tzinfo) + elif not before_now and after_now: + return self.date_time_between_dates(now, next_month_start, tzinfo) + elif not after_now and before_now: + return self.date_time_between_dates(this_month_start, now, tzinfo) + else: + return now + + def date_this_century(self, before_today=True, after_today=False): + """ + Gets a Date object for the current century. + + :param before_today: include days in current century before today + :param after_today: include days in current century after today + :example Date('2012-04-04') + :return Date + """ + today = date.today() + this_century_start = date(today.year - (today.year % 100), 1, 1) + next_century_start = date(this_century_start.year + 100, 1, 1) + + if before_today and after_today: + return self.date_between_dates( + this_century_start, next_century_start) + elif not before_today and after_today: + return self.date_between_dates(today, next_century_start) + elif not after_today and before_today: + return self.date_between_dates(this_century_start, today) + else: + return today + + def date_this_decade(self, before_today=True, after_today=False): + """ + Gets a Date object for the decade year. + + :param before_today: include days in current decade before today + :param after_today: include days in current decade after today + :example Date('2012-04-04') + :return Date + """ + today = date.today() + this_decade_start = date(today.year - (today.year % 10), 1, 1) + next_decade_start = date(this_decade_start.year + 10, 1, 1) + + if before_today and after_today: + return self.date_between_dates(this_decade_start, next_decade_start) + elif not before_today and after_today: + return self.date_between_dates(today, next_decade_start) + elif not after_today and before_today: + return self.date_between_dates(this_decade_start, today) + else: + return today + + def date_this_year(self, before_today=True, after_today=False): + """ + Gets a Date object for the current year. + + :param before_today: include days in current year before today + :param after_today: include days in current year after today + :example Date('2012-04-04') + :return Date + """ + today = date.today() + this_year_start = today.replace(month=1, day=1) + next_year_start = date(today.year + 1, 1, 1) + + if before_today and after_today: + return self.date_between_dates(this_year_start, next_year_start) + elif not before_today and after_today: + return self.date_between_dates(today, next_year_start) + elif not after_today and before_today: + return self.date_between_dates(this_year_start, today) + else: + return today + + def date_this_month(self, before_today=True, after_today=False): + """ + Gets a Date object for the current month. + + :param before_today: include days in current month before today + :param after_today: include days in current month after today + :param tzinfo: timezone, instance of datetime.tzinfo subclass + :example DateTime('2012-04-04 11:02:02') + :return DateTime + """ + today = date.today() + this_month_start = today.replace(day=1) + + next_month_start = this_month_start + \ + relativedelta.relativedelta(months=1) + if before_today and after_today: + return self.date_between_dates(this_month_start, next_month_start) + elif not before_today and after_today: + return self.date_between_dates(today, next_month_start) + elif not after_today and before_today: + return self.date_between_dates(this_month_start, today) + else: + return today + + def time_series( + self, + start_date='-30d', + end_date='now', + precision=None, + distrib=None, + tzinfo=None): + """ + Returns a generator yielding tuples of ``(, )``. + + The data points will start at ``start_date``, and be at every time interval specified by + ``precision``. + ``distrib`` is a callable that accepts ```` and returns ```` + + """ + start_date = self._parse_date_time(start_date, tzinfo=tzinfo) + end_date = self._parse_date_time(end_date, tzinfo=tzinfo) + + if end_date < start_date: + raise ValueError("`end_date` must be greater than `start_date`.") + + if precision is None: + precision = (end_date - start_date) / 30 + + precision = self._parse_timedelta(precision) + if distrib is None: + def distrib(dt): return self.generator.random.uniform(0, precision) # noqa + + if not callable(distrib): + raise ValueError( + "`distrib` must be a callable. Got {} instead.".format(distrib)) + + datapoint = start_date + while datapoint < end_date: + dt = timestamp_to_datetime(datapoint, tzinfo) + datapoint += precision + yield (dt, distrib(dt)) + + def am_pm(self): + return self.date('%p') + + def day_of_month(self): + return self.date('%d') + + def day_of_week(self): + return self.date('%A') + + def month(self): + return self.date('%m') + + def month_name(self): + return self.date('%B') + + def year(self): + return self.date('%Y') + + def century(self): + """ + :example 'XVII' + """ + return self.random_element(self.centuries) + + def timezone(self): + return self.generator.random.choice( + self.random_element(self.countries)['timezones']) + + def date_of_birth(self, tzinfo=None, minimum_age=0, maximum_age=115): + """ + Generate a random date of birth represented as a Date object, + constrained by optional miminimum_age and maximum_age + parameters. + + :param tzinfo Defaults to None. + :param minimum_age Defaults to 0. + :param maximum_age Defaults to 115. + + :example Date('1979-02-02') + :return Date + """ + + if not isinstance(minimum_age, int): + raise TypeError("minimum_age must be an integer.") + + if not isinstance(maximum_age, int): + raise TypeError("maximum_age must be an integer.") + + if (maximum_age < 0): + raise ValueError("maximum_age must be greater than or equal to zero.") + + if (minimum_age < 0): + raise ValueError("minimum_age must be greater than or equal to zero.") + + if (minimum_age > maximum_age): + raise ValueError("minimum_age must be less than or equal to maximum_age.") + + # In order to return the full range of possible dates of birth, add one + # year to the potential age cap and subtract one day if we land on the + # boundary. + + now = datetime.now(tzinfo).date() + start_date = now.replace(year=now.year - (maximum_age+1)) + end_date = now.replace(year=now.year - minimum_age) + + dob = self.date_time_ad(tzinfo=tzinfo, start_datetime=start_date, end_datetime=end_date).date() + + return dob if dob != start_date else dob + timedelta(days=1) diff --git a/testbed/joke2k__faker/faker/providers/date_time/ar_AA/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/ar_AA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19d32938d243ee5640c3e397d33956f1d738350d --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/ar_AA/__init__.py @@ -0,0 +1,1154 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + DAY_NAMES = { + '0': 'السبت', + '1': 'الأحد', + '2': 'الإثنين', + '3': 'الثلاثاء', + '4': 'الأربعاء', + '5': 'الخميس', + '6': 'الجمعة', + } + + MONTH_NAMES = { + '01': 'كانون الثّاني', + '02': 'شباط', + '03': 'آذار', + '04': 'نيسان', + '05': 'أيّار', + '06': 'حزيران', + '07': 'تمّوز', + '08': 'آب', + '09': 'أيلول', + '10': 'تشرين الأول', + '11': 'تشرين الثاني', + '12': 'كانون الأول', + } + + centuries = [ + 'الأول', 'الثاني', 'الثالث', 'الرابع', 'الخامس', 'السادس', + 'السابع', 'الثامن', 'التاسع', 'العاشر', 'الحادي عشر', + 'الثاني عشر', 'الثالث عشر', 'الرابع عشر', 'الخامس عشر', + 'السادس عشر', 'الثامن عشر', 'التاسع عشر', 'العشرين', + 'الحادي والعشرين', 'الثاني والعشرين', + ] + + countries = [{'timezones': ['أوروب/أندورا'], + 'alpha-2-code': 'AD', + 'continent': 'أوروبا', + 'name': 'أندورا', + 'capital': 'أندورا لا فيلا'}, + {'timezones': ['آسيا/كابل'], + 'alpha-2-code': 'AF', + 'continent': 'آسيا', + 'name': 'أفغانستان', + 'capital': 'كابل'}, + {'timezones': ['أمريكا/أنتيغوا'], + 'alpha-2-code': 'AG', + 'continent': 'أمريكا الشمالية', + 'name': 'أنتيغوا وباربودا', + 'capital': "سانت جونز"}, + {'timezones': ['أوروبا/تيرانا'], + 'alpha-2-code': 'AL', + 'continent': 'أوروبا', + 'name': 'ألبانيا', + 'capital': 'تيرانا'}, + {'timezones': ['آسيا/يريفان'], + 'alpha-2-code': 'AM', + 'continent': 'آسيا', + 'name': 'أرمينيا', + 'capital': 'يريفان'}, + {'timezones': ['إفريقيا/لواندا'], + 'alpha-2-code': 'AO', + 'continent': 'إفريقيا', + 'name': 'أنغولا', + 'capital': 'لواندا'}, + {'timezones': ['أمريكا/الأرجنتين/بوينس_آيرس', + 'أمريكا/الأرجنتين/Cordoba', + 'أمريكا/الأرجنتين/خوخوي', + 'أمريكا/الأرجنتين/توكومان', + 'أمريكا/الأرجنتين/كاتاماركا', + 'أمريكا/الأرجنتين/لا_ريوخا', + 'أمريكا/الأرجنتين/سان_خوان', + 'أمريكا/الأرجنتين/مندوزا', + 'أمريكا/الأرجنتين/ريو_غاليغوس', + 'أمريكا/الأرجنتين/أوشوايا'], + 'alpha-2-code': 'AR', + 'continent': 'أمريكا الجنوبية', + 'name': 'الأرجنتين', + 'capital': 'بوينس آيرس'}, + {'timezones': ['أوروبا/النمسا'], + 'alpha-2-code': 'AT', + 'continent': 'أوروبا', + 'name': 'النمسا', + 'capital': 'فيينا'}, + {'timezones': ['أستراليا/لورد_هاو', + 'أستراليا/هوبارت', + 'أستراليا/كري', + 'أستراليا/ملبورن', + 'أستراليا/سدني', + 'أستراليا/بروكن_هل', + 'أستراليا/بريزبن', + 'أستراليا/ليندمان', + 'أستراليا/أديلايد', + 'أستراليا/داروين', + 'أستراليا/برث'], + 'alpha-2-code': 'AU', + 'continent': 'أوقيانوسيا', + 'name': 'أستراليا', + 'capital': 'كانبرا'}, + {'timezones': ['آسيا/باكو'], + 'alpha-2-code': 'AZ', + 'continent': 'آسيا', + 'name': 'أذربيجان', + 'capital': 'باكو'}, + {'timezones': ['أمريكا/باربادوس'], + 'alpha-2-code': 'BB', + 'continent': 'أمريكا الشمالية', + 'name': 'باربادوس', + 'capital': 'بريدج تاون'}, + {'timezones': ['آسيا/دكا'], + 'alpha-2-code': 'BD', + 'continent': 'آسيا', + 'name': 'بنغلادش', + 'capital': 'دكا'}, + {'timezones': ['أوروبا/بروكسل'], + 'alpha-2-code': 'BE', + 'continent': 'أوروبا', + 'name': 'بلجيكا', + 'capital': 'بروكسل'}, + {'timezones': ['إفريقيا/واغادوغو'], + 'alpha-2-code': 'BF', + 'continent': 'إفريقيا', + 'name': 'بوركينا فاسو', + 'capital': 'واغادوغو'}, + {'timezones': ['أوروبا/صوفيا'], + 'alpha-2-code': 'BG', + 'continent': 'أوروبا', + 'name': 'بلغاريا', + 'capital': 'صوفيا'}, + {'timezones': ['آسيا/البحرين'], + 'alpha-2-code': 'BH', + 'continent': 'آسيا', + 'name': 'البحرين', + 'capital': 'المنامة'}, + {'timezones': ['إفريقيا/بوجمبورا'], + 'alpha-2-code': 'BI', + 'continent': 'إفريقيا', + 'name': 'بوروندي', + 'capital': 'بوجمبورا'}, + {'timezones': ['إفريقيا/بورتو نوفو'], + 'alpha-2-code': 'BJ', + 'continent': 'إفريقيا', + 'name': 'بنين', + 'capital': 'بورتو نوفو'}, + {'timezones': ['آسيا/بروناي'], + 'alpha-2-code': 'BN', + 'continent': 'آسيا', + 'name': 'اتحاد بروناي (دار السلام)', + 'capital': 'بندر سري بكاوان'}, + {'timezones': ['أمريكا/لاباز'], + 'alpha-2-code': 'BO', + 'continent': 'أمريكا الجنوبية', + 'name': 'بوليفيا', + 'capital': 'سوكري'}, + {'timezones': ['أمريكا/نورونها', + 'أمريكا/بليم', + 'أمريكا/فورتاليزا', + 'أمريكا/ريسيفي', + 'أمريكا/أراغوينا', + 'أمريكا/ماسايو', + 'أمريكا/باهيا', + 'أمريكا/ساو_باولو', + 'أمريكا/كامبو_غراندي', + 'أمريكا/كويابا', + 'أمريكا/بورتو_فاليو', + 'أمريكا/بوا_فيستا', + 'أمريكا/ماناوس', + 'أمريكا/إيرونيبي', + 'أمريكا/ريو_برانكو'], + 'alpha-2-code': 'BR', + 'continent': 'أمريكا الجنوبية', + 'name': 'البرازيل', + 'capital': 'برازيليا'}, + {'timezones': ['أمريكا/ناساو'], + 'alpha-2-code': 'BS', + 'continent': 'أمريكا الشمالية', + 'name': 'باهاماس', + 'capital': 'ناساو'}, + {'timezones': ['آسيا/تيمفو'], + 'alpha-2-code': 'BT', + 'continent': 'آسيا', + 'name': 'بوتان', + 'capital': 'تيمفو'}, + {'timezones': ['إفريقيا/غابورون'], + 'alpha-2-code': 'BW', + 'continent': 'إفريقيا', + 'name': 'بوتسوانا', + 'capital': 'غابورون'}, + {'timezones': ['أوروبا/مينسك'], + 'alpha-2-code': 'BY', + 'continent': 'أوروبا', + 'name': 'روسيا البيضاء', + 'capital': 'مينسك'}, + {'timezones': ['أمريكا/بليز'], + 'alpha-2-code': 'BZ', + 'continent': 'أمريكا الشمالية', + 'name': 'بليز', + 'capital': 'بلموبان'}, + {'timezones': ['أمريكا/سينت_جونز', + 'أمريكا/هاليفاكس', + 'أمريكا/جليس_باي', + 'أمريكا/مونكتون', + 'أمريكا/جووس_باي', + 'أمريكا/بلانك_سابلون', + 'أمريكا/مونتريال', + 'أمريكا/تورونتو', + 'أمريكا/نيبيغون', + 'أمريكا/ثاندر_باي', + 'أمريكا/بانغيرتانغ', + 'أمريكا/إيكواليوت', + 'أمريكا/أتيكوكان', + 'أمريكا/رانكن_إنلت', + 'أمريكا/وينيبيغ', + 'أمريكا/رايني_ريفر', + 'أمريكا/كامبريدج_باي', + 'أمريكا/ريجينا', + 'أمريكا/سويفت_كارنت', + 'أمريكا/إدمونتون', + 'أمريكا/يلو_نايف', + 'أمريكا/إنوفك', + 'أمريكا/دوسن_كريك', + 'أمريكا/فانكوفر', + 'أمريكا/وايت_هورس', + 'أمريكا/داوسون'], + 'alpha-2-code': 'CA', + 'continent': 'أمريكا الشمالية', + 'name': 'كندا', + 'capital': 'أوتاوا'}, + {'timezones': ['إفريقيا/كينشاسا', + 'إفريقيا/لوبومباشي'], + 'alpha-2-code': 'CD', + 'continent': 'إفريقيا', + 'name': 'جمهورية الكونغو الديمقراطية', + 'capital': 'كينشاسا'}, + {'timezones': ['إفريقيا/برازافيل'], + 'alpha-2-code': 'CG', + 'continent': 'إفريقيا', + 'name': 'جمهورية الكونغو', + 'capital': 'برازافيل'}, + {'timezones': ['إفريقيا/أبيدجان'], + 'alpha-2-code': 'CI', + 'continent': 'إفريقيا', + 'name': "ساحل العاج", + 'capital': 'ياموسوكرو'}, + {'timezones': ['أمريكا/سانتياغو', + 'المحيط_الهاديء/جزيرة_القيامة'], + 'alpha-2-code': 'CL', + 'continent': 'أمريكا الجنوبية', + 'name': 'تشيلي', + 'capital': 'سانتياغو'}, + {'timezones': ['إفريقيا/دوالا'], + 'alpha-2-code': 'CM', + 'continent': 'إفريقيا', + 'name': 'الكاميرون', + 'capital': 'ياوندي'}, + {'timezones': ['آسيا/شانغهاي', + 'آسيا/هاربن', + 'آسيا/تشونغتشينغ', + 'آسيا/أورومتشي', + 'آسيا/كاشغر'], + 'alpha-2-code': 'CN', + 'continent': 'آسيا', + 'name': "جمهورية الصين الشعبية", + 'capital': 'بكين'}, + {'timezones': ['أمريكا/بوغوتا'], + 'alpha-2-code': 'CO', + 'continent': 'أمريكا الجنوبية', + 'name': 'كولومبيا', + 'capital': 'بوغوتا'}, + {'timezones': ['أمريكا/كوستاريكا'], + 'alpha-2-code': 'CR', + 'continent': 'أمريكا الشمالية', + 'name': 'كوستاريكا', + 'capital': 'سان خوسيه'}, + {'timezones': ['أمريكا/هافانا'], + 'alpha-2-code': 'CU', + 'continent': 'أمريكا الشمالية', + 'name': 'كوبا', + 'capital': 'هافانا'}, + {'timezones': ['الأطلنطي/الرأس_الأخضر'], + 'alpha-2-code': 'CV', + 'continent': 'إفريقيا', + 'name': 'جمهورية الرأس الأخضر', + 'capital': 'برايا'}, + {'timezones': ['آسيا/نيقوسيا'], + 'alpha-2-code': 'CY', + 'continent': 'آسيا', + 'name': 'قبرص', + 'capital': 'نيقوسيا'}, + {'timezones': ['أوروبا/براغ'], + 'alpha-2-code': 'CZ', + 'continent': 'أوروبا', + 'name': 'جمهورية التشيك', + 'capital': 'براغ'}, + {'timezones': ['أوروبا/برلين'], + 'alpha-2-code': 'DE', + 'continent': 'أوروبا', + 'name': 'ألمانيا', + 'capital': 'برلين'}, + {'timezones': ['إفريقيا/جيبوتي'], + 'alpha-2-code': 'DJ', + 'continent': 'إفريقيا', + 'name': 'جيبوتي', + 'capital': 'جيبوتي'}, + {'timezones': ['أوروبا/كوبنهاغن'], + 'alpha-2-code': 'DK', + 'continent': 'أوروبا', + 'name': 'الدنمارك', + 'capital': 'كوبنهاغن'}, + {'timezones': ['أمريكا/دومينيكا'], + 'alpha-2-code': 'DM', + 'continent': 'أمريكا الشمالية', + 'name': 'دومينيكا', + 'capital': 'روسياو'}, + {'timezones': ['أمريكا/سانتو_دومينغو'], + 'alpha-2-code': 'DO', + 'continent': 'أمريكا الشمالية', + 'name': 'جمهورية الدومينيكان', + 'capital': 'سانتو دومينغو'}, + {'timezones': ['أمريكا/غواياكيل', + 'المحيط_الهاديء/أرخبيل_غالاباغوس'], + 'alpha-2-code': 'EC', + 'continent': 'أمريكا الجنوبية', + 'name': 'الإكوادور', + 'capital': 'كيتو'}, + {'timezones': ['أوروبا/تالين'], + 'alpha-2-code': 'EE', + 'continent': 'أوروبا', + 'name': 'إستونيا', + 'capital': 'تالين'}, + {'timezones': ['إفريقيا/القاهرة'], + 'alpha-2-code': 'EG', + 'continent': 'إفريقيا', + 'name': 'مصر', + 'capital': 'القاهرة'}, + {'timezones': ['إفريقيا/أسمرة'], + 'alpha-2-code': 'ER', + 'continent': 'إفريقيا', + 'name': 'إرتيريا', + 'capital': 'أسمرة'}, + {'timezones': ['إفريقيا/أديس أبابا'], + 'alpha-2-code': 'ET', + 'continent': 'إفريقيا', + 'name': 'إثيوبيا', + 'capital': 'أديس أبابا'}, + {'timezones': ['أوروبا/هلسنكي'], + 'alpha-2-code': 'FI', + 'continent': 'أوروبا', + 'name': 'فنلندا', + 'capital': 'هلسنكي'}, + {'timezones': ['المحيط_الهاديء/فيجي'], + 'alpha-2-code': 'FJ', + 'continent': 'أوقيانوسيا', + 'name': 'فيجي', + 'capital': 'سوفا'}, + {'timezones': ['أوروبا/باريس'], + 'alpha-2-code': 'FR', + 'continent': 'أوروبا', + 'name': 'فرنسا', + 'capital': 'باريس'}, + {'timezones': ['إفريقيا/ليبرفيل'], + 'alpha-2-code': 'GA', + 'continent': 'إفريقيا', + 'name': 'الغابون', + 'capital': 'ليبرفيل'}, + {'timezones': ['آسيا/تبليسي'], + 'alpha-2-code': 'GE', + 'continent': 'آسيا', + 'name': 'جورجيا', + 'capital': 'تبليسي'}, + {'timezones': ['إفريقيا/أكرا'], + 'alpha-2-code': 'GH', + 'continent': 'إفريقيا', + 'name': 'غانا', + 'capital': 'أكرا'}, + {'timezones': ['إفريقيا/بانجول'], + 'alpha-2-code': 'GM', + 'continent': 'إفريقيا', + 'name': 'غامبيا', + 'capital': 'بانجول'}, + {'timezones': ['إفريقيا/كوناكري'], + 'alpha-2-code': 'GN', + 'continent': 'إفريقيا', + 'name': 'غينيا', + 'capital': 'كوناكري'}, + {'timezones': ['أوروبا/أثينا'], + 'alpha-2-code': 'GR', + 'continent': 'أوروبا', + 'name': 'اليونان', + 'capital': 'أثينا'}, + {'timezones': ['أمريكا/غواتيمالا'], + 'alpha-2-code': 'GT', + 'continent': 'أمريكا الشمالية', + 'name': 'غواتيمالا', + 'capital': 'غواتيمالا سيتي'}, + {'timezones': ['أمريكا/غواتيمالا'], + 'alpha-2-code': 'GT', + 'continent': 'أمريكا الشمالية', + 'name': 'هايتي', + 'capital': 'بورت أو برانس'}, + {'timezones': ['إفريقيا/بيساو'], + 'alpha-2-code': 'GW', + 'continent': 'إفريقيا', + 'name': 'غينيا بيساو', + 'capital': 'بيساو'}, + {'timezones': ['أمريكا/غيانا'], + 'alpha-2-code': 'GY', + 'continent': 'أمريكا الجنوبية', + 'name': 'غيانا', + 'capital': 'جورج تاون'}, + {'timezones': ['أمريكا/تيجوسيجالبا'], + 'alpha-2-code': 'HN', + 'continent': 'أمريكا الشمالية', + 'name': 'هندوراس', + 'capital': 'تيجوسيجالبا'}, + {'timezones': ['أوروبا/بودابست'], + 'alpha-2-code': 'HU', + 'continent': 'أوروبا', + 'name': 'هنغاريا', + 'capital': 'بودابست'}, + {'timezones': ['آسيا/جاكرتا', + 'آسيا/بونتياناك', + 'آسيا/ماكاسار', + 'آسيا/جايابورا'], + 'alpha-2-code': 'ID', + 'continent': 'آسيا', + 'name': 'إندونسيا', + 'capital': 'جاكرتا'}, + {'timezones': ['أوروبا/دبلن'], + 'alpha-2-code': 'IE', + 'continent': 'أوروبا', + 'name': 'إيرلندا', + 'capital': 'دبلن'}, + {'timezones': ['آسيا/القدس'], + 'alpha-2-code': 'IL', + 'continent': 'آسيا', + 'name': 'فلسطين', + 'capital': 'القدس'}, + {'timezones': ['آسيا/كالكتا'], + 'alpha-2-code': 'IN', + 'continent': 'آسيا', + 'name': 'الهند', + 'capital': 'نيو دلهي'}, + {'timezones': ['آسيا/بغداد'], + 'alpha-2-code': 'IQ', + 'continent': 'آسيا', + 'name': 'العراق', + 'capital': 'بغداد'}, + {'timezones': ['آسيا/طهران'], + 'alpha-2-code': 'IR', + 'continent': 'آسيا', + 'name': 'إيران', + 'capital': 'طهران'}, + {'timezones': ['الأطلنطي/ريكيافيك'], + 'alpha-2-code': 'IS', + 'continent': 'أوروبا', + 'name': 'آيسلندا', + 'capital': 'ريكيافيك'}, + {'timezones': ['أوروبا/روما'], + 'alpha-2-code': 'IT', + 'continent': 'أوروبا', + 'name': 'إيطاليا', + 'capital': 'روما'}, + {'timezones': ['أمريكا/جامايكا'], + 'alpha-2-code': 'JM', + 'continent': 'أمريكا الشمالية', + 'name': 'جامايكا', + 'capital': 'كينغستون'}, + {'timezones': ['آسيا/عمّان'], + 'alpha-2-code': 'JO', + 'continent': 'آسيا', + 'name': 'الأردن', + 'capital': 'عمّان'}, + {'timezones': ['آسيا/طوكيو'], + 'alpha-2-code': 'JP', + 'continent': 'آسيا', + 'name': 'اليابان', + 'capital': 'طوكيو'}, + {'timezones': ['إفريقيا/نيروبي'], + 'alpha-2-code': 'KE', + 'continent': 'إفريقيا', + 'name': 'كينيا', + 'capital': 'نيروبي'}, + {'timezones': ['آسيا/بشكيك'], + 'alpha-2-code': 'KG', + 'continent': 'آسيا', + 'name': 'قيرغيزستان', + 'capital': 'بشكيك'}, + {'timezones': ['المحيط_الهاديء/تاراوا', + 'المحيط_الهاديء/إيديربيري', + 'المحيط_الهاديء/كريتيماتي'], + 'alpha-2-code': 'KI', + 'continent': 'أوقيانوسيا', + 'name': 'كيريباتي', + 'capital': 'جنوب تاراوا'}, + {'timezones': ['آسيا/بيونغ_يانغ'], + 'alpha-2-code': 'KP', + 'continent': 'آسيا', + 'name': 'كوريا الشمالية', + 'capital': 'بيونغ يانغ'}, + {'timezones': ['آسيا/سيؤول'], + 'alpha-2-code': 'KR', + 'continent': 'آسيا', + 'name': '؛كوريا الجنوبية', + 'capital': 'سيؤول'}, + {'timezones': ['آسيا/الكويت'], + 'alpha-2-code': 'KW', + 'continent': 'آسيا', + 'name': 'الكويت', + 'capital': 'الكويت'}, + {'timezones': ['آسيا/بيروت'], + 'alpha-2-code': 'LB', + 'continent': 'آسيا', + 'name': 'لبنان', + 'capital': 'بيروت'}, + {'timezones': ['أوروبا/فادوز'], + 'alpha-2-code': 'LI', + 'continent': 'أوروبا', + 'name': 'ليختنشتاين', + 'capital': 'فادوز'}, + {'timezones': ['إفريقيا/مونروفيا'], + 'alpha-2-code': 'LR', + 'continent': 'إفريقيا', + 'name': 'ليبيريا', + 'capital': 'مونروفيا'}, + {'timezones': ['إفريقيا/ماسيرو'], + 'alpha-2-code': 'LS', + 'continent': 'إفريقيا', + 'name': 'ليسوتو', + 'capital': 'ماسيرو'}, + {'timezones': ['أوروبا/فيلنيوس'], + 'alpha-2-code': 'LT', + 'continent': 'أوروبا', + 'name': 'ليتوانيا', + 'capital': 'فيلنيوس'}, + {'timezones': ['أوروبا/لوكسمبرغ'], + 'alpha-2-code': 'LU', + 'continent': 'أوروبا', + 'name': 'لوكسمبرغ', + 'capital': 'لوكسمبرغ سيتي'}, + {'timezones': ['أوروبا/ربيغ'], + 'alpha-2-code': 'LV', + 'continent': 'أوروبا', + 'name': 'لاتفيا', + 'capital': 'ربيغ'}, + {'timezones': ['إفريقيا/طرابلس'], + 'alpha-2-code': 'LY', + 'continent': 'إفريقيا', + 'name': 'ليبيا', + 'capital': 'طرابلس'}, + {'timezones': ['الهندي/أنتاناناريفو'], + 'alpha-2-code': 'MG', + 'continent': 'إفريقيا', + 'name': 'مدغشقر', + 'capital': 'أنتاناناريفو'}, + {'timezones': ['المحيط_الهاديء/ماجورو', + 'المحيط_الهاديء/كواجلين_أتول'], + 'alpha-2-code': 'MH', + 'continent': 'أوقيانوسيا', + 'name': 'جزر مارشال', + 'capital': 'ماجورو'}, + {'timezones': ['أوروبا/سكوبيه'], + 'alpha-2-code': 'MK', + 'continent': 'أوروبا', + 'name': 'جمهورية مقدونيا', + 'capital': 'سكوبيه'}, + {'timezones': ['إفريقيا/باماكو'], + 'alpha-2-code': 'ML', + 'continent': 'إفريقيا', + 'name': 'مالي', + 'capital': 'باماكو'}, + {'timezones': ['آسيا/رانغون'], + 'alpha-2-code': 'MM', + 'continent': 'آسيا', + 'name': 'ميانمار', + 'capital': 'نايبيداو'}, + {'timezones': ['آسيا/أولان_باتور', + 'آسيا/Hovd', + 'آسيا/تشويبالسان'], + 'alpha-2-code': 'MN', + 'continent': 'آسيا', + 'name': 'مانغوليا', + 'capital': 'أولان باتور'}, + {'timezones': ['إفريقيا/نواكشط'], + 'alpha-2-code': 'MR', + 'continent': 'إفريقيا', + 'name': 'موريتانيا', + 'capital': 'نواكشط'}, + {'timezones': ['أوروبا/مالطا'], + 'alpha-2-code': 'MT', + 'continent': 'أوروبا', + 'name': 'مالطا', + 'capital': 'فاليتا'}, + {'timezones': ['الهندي/موريشيوس'], + 'alpha-2-code': 'MU', + 'continent': 'إفريقيا', + 'name': 'موريشيوس', + 'capital': 'بور لويس'}, + {'timezones': ['الهندي/جزر_المالديف'], + 'alpha-2-code': 'MV', + 'continent': 'آسيا', + 'name': 'جمهورية المالديف', + 'capital': 'ماليه'}, + {'timezones': ['إفريقيا/بلانتاير'], + 'alpha-2-code': 'MW', + 'continent': 'إفريقيا', + 'name': 'ملاوي', + 'capital': 'ليلونغوي'}, + {'timezones': ['أمريكا/ميكسيكو_سيتي', + 'أمريكا/كانكون', + 'أمريكا/ميرديا', + 'أمريكا/مونتيري', + 'أمريكا/مازاتلان', + 'أمريكا/شيواوا', + 'أمريكا/ارموسييو_سونورا', + 'أمريكا/تيخوانا'], + 'alpha-2-code': 'MX', + 'continent': 'أمريكا الشمالية', + 'name': 'المكسيك', + 'capital': 'ميكسيكو سيتي§'}, + {'timezones': ['آسيا/كوالا_لامبور', + 'آسيا/Kuching'], + 'alpha-2-code': 'MY', + 'continent': 'آسيا', + 'name': 'ماليزيا', + 'capital': 'كوالا لامبور'}, + {'timezones': ['إفريقيا/مابوتو'], + 'alpha-2-code': 'MZ', + 'continent': 'إفريقيا', + 'name': 'موزمبيق', + 'capital': 'مابوتو'}, + {'timezones': ['إفريقيا/ويندهوك'], + 'alpha-2-code': 'NA', + 'continent': 'إفريقيا', + 'name': 'ناميبيا', + 'capital': 'ويندهوك'}, + {'timezones': ['إفريقيا/نيامي'], + 'alpha-2-code': 'NE', + 'continent': 'إفريقيا', + 'name': 'النيجر', + 'capital': 'نيامي'}, + {'timezones': ['إفريقيا/لاغوس'], + 'alpha-2-code': 'NG', + 'continent': 'إفريقيا', + 'name': 'نيجيريا', + 'capital': 'أبوجا'}, + {'timezones': ['أمريكا/ماناغوا'], + 'alpha-2-code': 'NI', + 'continent': 'أمريكا الشمالية', + 'name': 'نيكاراغوا', + 'capital': 'ماناغوا'}, + {'timezones': ['أوروبا/أمستردام'], + 'alpha-2-code': 'NL', + 'continent': 'أوروبا', + 'name': 'هولندا', + 'capital': 'أمستردام'}, + {'timezones': ['أوروبا/أوسلو'], + 'alpha-2-code': 'NO', + 'continent': 'أوروبا', + 'name': 'النرويج', + 'capital': 'أوسلو'}, + {'timezones': ['آسيا/كاتماندو'], + 'alpha-2-code': 'NP', + 'continent': 'آسيا', + 'name': 'النيبال', + 'capital': 'كاتماندو'}, + {'timezones': ['المحيط_الهاديء/ناورو'], + 'alpha-2-code': 'NR', + 'continent': 'أوقيانوسيا', + 'name': 'ناورو', + 'capital': 'يارين'}, + {'timezones': ['المحيط_الهاديء/أوكلاند', + 'المحيط_الهاديء/تشاتهام'], + 'alpha-2-code': 'NZ', + 'continent': 'أوقيانوسيا', + 'name': 'نيوزيلاندا', + 'capital': 'ويلينغتون'}, + {'timezones': ['آسيا/مسقط'], + 'alpha-2-code': 'OM', + 'continent': 'آسيا', + 'name': 'عمان', + 'capital': 'مسقط'}, + {'timezones': ['أمريكا/بنما'], + 'alpha-2-code': 'PA', + 'continent': 'أمريكا الشمالية', + 'name': 'بنما', + 'capital': 'بنما'}, + {'timezones': ['أمريكا/ليما'], + 'alpha-2-code': 'PE', + 'continent': 'أمريكا الجنوبية', + 'name': 'البيرو', + 'capital': 'ليما'}, + {'timezones': ['المحيط_الهاديء/بورت_مورسبي'], + 'alpha-2-code': 'PG', + 'continent': 'أوقيانوسيا', + 'name': 'بابوا غينيا الجديدة', + 'capital': 'بورت مورسبي'}, + {'timezones': ['آسيا/مانيلا'], + 'alpha-2-code': 'PH', + 'continent': 'آسيا', + 'name': 'الفيليبين', + 'capital': 'مانيلا'}, + {'timezones': ['آسيا/كاراتشي'], + 'alpha-2-code': 'PK', + 'continent': 'آسيا', + 'name': 'باكستان', + 'capital': 'إسلام أباد'}, + {'timezones': ['أوروبا/وارسو'], + 'alpha-2-code': 'PL', + 'continent': 'أوروبا', + 'name': 'بولندا', + 'capital': 'وارسو'}, + {'timezones': ['أوروبا/لشبونة', + 'الأطلنطي/ماديرا', + 'الأطلنطي/الأزور'], + 'alpha-2-code': 'PT', + 'continent': 'أوروبا', + 'name': 'البرتغال', + 'capital': 'لشبونة'}, + {'timezones': ['المحيط_الهاديء/بالاو'], + 'alpha-2-code': 'PW', + 'continent': 'أوقيانوسيا', + 'name': 'بالاو', + 'capital': 'نجيرولمد'}, + {'timezones': ['أمريكا/أسونسيون'], + 'alpha-2-code': 'PY', + 'continent': 'أمريكا الجنوبية', + 'name': 'بابرغوي', + 'capital': 'أسونسيون'}, + {'timezones': ['آسيا/قطر'], + 'alpha-2-code': 'QA', + 'continent': 'آسيا', + 'name': 'قطر', + 'capital': 'الدوحة'}, + {'timezones': ['أوروبا/بوخارست'], + 'alpha-2-code': 'RO', + 'continent': 'أوروبا', + 'name': 'رومانيا', + 'capital': 'بوخارست'}, + {'timezones': ['أوروبا/كالينينغراد', + 'أوروبا/موسكو', + 'أوروبا/Volgograd', + 'أوروبا/سمارة', + 'آسيا/يكاترينبورغ', + 'آسيا/أومسك', + 'آسيا/نوفوسيبيرسك', + 'آسيا/كراسنوياسك', + 'آسيا/إروتسك', + 'آسيا/ياكوتسك', + 'آسيا/فالديفوستوك', + 'آسيا/ساخالن', + 'آسيا/ماغادان', + 'آسيا/كامشتكا', + 'آسيا/أنادير'], + 'alpha-2-code': 'RU', + 'continent': 'أوروبا', + 'name': 'روسيا', + 'capital': 'موسكو'}, + {'timezones': ['إفريقيا/كيغالي'], + 'alpha-2-code': 'RW', + 'continent': 'إفريقيا', + 'name': 'رواندا', + 'capital': 'كيغالي'}, + {'timezones': ['آسيا/الرياض'], + 'alpha-2-code': 'SA', + 'continent': 'آسيا', + 'name': 'المملكة العربية السعودية', + 'capital': 'الرياض'}, + {'timezones': ['المحيط_الهاديء/غوادالكانال'], + 'alpha-2-code': 'SB', + 'continent': 'أوقيانوسيا', + 'name': 'جزر سولمون', + 'capital': 'هونيارا'}, + {'timezones': ['الهندي/ماهي'], + 'alpha-2-code': 'SC', + 'continent': 'إفريقيا', + 'name': 'سيشل', + 'capital': 'فيكتوريا'}, + {'timezones': ['إفريقيا/الخرطوم'], + 'alpha-2-code': 'SD', + 'continent': 'إفريقيا', + 'name': 'السودان', + 'capital': 'الخرطوم'}, + {'timezones': ['أوروبا/ستوكهولم'], + 'alpha-2-code': 'SE', + 'continent':'أوروبا', + 'name': 'السويد', + 'capital': 'ستوكهولم'}, + {'timezones': ['آسيا/سنغافورة'], + 'alpha-2-code': 'SG', + 'continent': 'آسيا', + 'name': 'سنغافورة', + 'capital': 'سنغافورة'}, + {'timezones': ['أوروبا/ليوبليانا'], + 'alpha-2-code': 'SI', + 'continent': 'أوروبا', + 'name': 'سلوفانيا', + 'capital': 'ليوبليانا'}, + {'timezones': ['أوروبا/براتيسلافا'], + 'alpha-2-code': 'SK', + 'continent': 'أوروبا', + 'name': 'سلوفاكيا', + 'capital': 'براتيسلافا'}, + {'timezones': ['إفريقيا/فريتاون'], + 'alpha-2-code': 'SL', + 'continent': 'إفريقيا', + 'name': 'سيراليون', + 'capital': 'فريتاون'}, + {'timezones': ['أوروبا/سان_مارينو'], + 'alpha-2-code': 'SM', + 'continent': 'أوروبا', + 'name': 'جمهورية سان مارينو', + 'capital': 'سان مارينو'}, + {'timezones': ['إفريقيا/داكار'], + 'alpha-2-code': 'SN', + 'continent': 'إفريقيا', + 'name': 'السنغال', + 'capital': 'داكار'}, + {'timezones': ['إفريقيا/مقديشو'], + 'alpha-2-code': 'SO', + 'continent': 'إفريقيا', + 'name': 'الصومال', + 'capital': 'مقديشو'}, + {'timezones': ['أمريكا/باراماريبو'], + 'alpha-2-code': 'SR', + 'continent': 'أمريكا الجنوبية', + 'name': 'Suriname', + 'capital': 'باراماريبو'}, + {'timezones': ['إفريقيا/ساو_تومي'], + 'alpha-2-code': 'ST', + 'continent': 'إفريقيا', + 'name': ' ساو تومي وبرينسيب', + 'capital': 'ساو تومي'}, + {'timezones': ['آسيا/دممشق'], + 'alpha-2-code': 'SY', + 'continent': 'آسيا', + 'name': 'سوريا', + 'capital': 'دمشق'}, + {'timezones': ['إفريقيا/لومي'], + 'alpha-2-code': 'TG', + 'continent': 'إفريقيا', + 'name': 'توغو', + 'capital': 'لومي'}, + {'timezones': ['آسيا/بانغوك'], + 'alpha-2-code': 'TH', + 'continent': 'آسيا', + 'name': 'تايلند', + 'capital': 'بناغوك'}, + {'timezones': ['آسيا/دوشنبه'], + 'alpha-2-code': 'TJ', + 'continent': 'آسيا', + 'name': 'طاجكيستان', + 'capital': 'دوشنبه'}, + {'timezones': ['آسيا/عشق_آباد'], + 'alpha-2-code': 'TM', + 'continent': 'آسيا', + 'name': 'تركمانستان', + 'capital': 'عشق آباد'}, + {'timezones': ['إفريقيا/تونس'], + 'alpha-2-code': 'TN', + 'continent': 'إفريقيا', + 'name': 'تونس', + 'capital': 'تونس'}, + {'timezones': ['المحيط_الهاديء/تونغاتابو'], + 'alpha-2-code': 'TO', + 'continent': 'أوقيانوسيا', + 'name': 'تونغا', + 'capital': 'نوكو ألوفا'}, + {'timezones': ['أوروبا/إسطنبول'], + 'alpha-2-code': 'TR', + 'continent': 'آسيا', + 'name': 'تركيا', + 'capital': 'أنقرة'}, + {'timezones': ['أمريكا/بورت_أوف_سبين'], + 'alpha-2-code': 'TT', + 'continent': 'أمريكا الشمالية', + 'name': 'ترينيداد وتوباغو', + 'capital': 'بورت أوف سبين'}, + {'timezones': ['المحيط_الهاديء/فونافوتي'], + 'alpha-2-code': 'TV', + 'continent': 'أوقيانوسيا', + 'name': 'توفالو', + 'capital': 'فونافوتي'}, + {'timezones': ['إفريقيا/دار_السلام'], + 'alpha-2-code': 'TZ', + 'continent': 'إفريقيا', + 'name': 'تانزانيا', + 'capital': 'دودوما'}, + {'timezones': ['أوروبا/كييف', + 'أوروبا/أوجهورود', + 'أوروبا/زاباروجيا', + 'أوروبا/سيمفروبول'], + 'alpha-2-code': 'UA', + 'continent': 'أوروبا', + 'name': 'أوكرانيا', + 'capital': 'كييف'}, + {'timezones': ['إفريقيا/كامبالا'], + 'alpha-2-code': 'UG', + 'continent': 'إفريقيا', + 'name': 'أوغندا', + 'capital': 'كامبالا'}, + {'timezones': ['أمريكا/نيويورك', + 'أمريكا/ديترويت', + 'أمريكا/كنتاكي/لويسفيل', + 'أمريكا/كنتاكي/مونتيسللو', + 'أمريكا/إنديانا/إنديانابولس', + 'أمريكا/إنديانا/مارنغو', + 'أمريكا/إنديانا/نوكس', + 'أمريكا/إنديانا/فيفاي', + 'أمريكا/شيكاغو', + 'أمريكا/إنديانا/فانسان', + 'أمريكا/إنديانا/بيترزبيرغ', + 'أمريكا/مينومني', + 'أمريكا/نورث_داكوتا/سينتر', + 'أمريكا/نورث_داكوتا/نيو_سالم', + 'أمريكا/دنفر', + 'أمريكا/بويسي', + 'أمريكا/شيبروك', + 'أمريكا/فينيكس', + 'أمريكا/لوس_أنجيلوس', + 'أمريكا/أنكوريج', + 'أمريكا/جونو', + 'أمريكا/ياكوتات', + 'أمريكا/نوم', + 'أمريكا/أداك', + 'المحيط_الهاديء/هونولولو'], + 'alpha-2-code': 'US', + 'continent': 'أمريكا الشمالية', + 'name': 'الولايات المتحدة الأمريكية', + 'capital': 'واشنطن'}, + {'timezones': ['أمريكا/مونتفيدو'], + 'alpha-2-code': 'UY', + 'continent': 'أمريكا الجنوبية', + 'name': 'أوروغواي', + 'capital': 'مونتفيدو'}, + {'timezones': ['آسيا/سمرقند', + 'آسيا/طشقند'], + 'alpha-2-code': 'UZ', + 'continent': 'آسيا', + 'name': 'أوزبكستان', + 'capital': 'طشقند'}, + {'timezones': ['أوروبا/الفاتيكان'], + 'alpha-2-code': 'VA', + 'continent': 'أوروبا', + 'name': 'الفاتيكان', + 'capital': 'الفاتيكان'}, + {'timezones': ['أمريكا/كاركاس'], + 'alpha-2-code': 'VE', + 'continent': 'أمريكا الجنوبية', + 'name': 'فنزويلا', + 'capital': 'كاركاس'}, + {'timezones': ['آسيا/سايغون'], + 'alpha-2-code': 'VN', + 'continent': 'آسيا', + 'name': 'فيتنام', + 'capital': 'هانوي'}, + {'timezones': ['المحيط_الهاديء/أيفاتي'], + 'alpha-2-code': 'VU', + 'continent': 'أوقيانوسيا', + 'name': 'فانواتو', + 'capital': 'بورت فيلا'}, + {'timezones': ['آسيا/عدن'], + 'alpha-2-code': 'YE', + 'continent': 'آسيا', + 'name': 'اليمن', + 'capital': "صنعاء"}, + {'timezones': ['إفريقيا/لوساكا'], + 'alpha-2-code': 'ZM', + 'continent': 'إفريقيا', + 'name': 'زامبيا', + 'capital': 'لوساكا'}, + {'timezones': ['إفريقيا/هراري'], + 'alpha-2-code': 'ZW', + 'continent': 'إفريقيا', + 'name': 'زيمبابوي', + 'capital': 'هراري'}, + {'timezones': ['إفريقيا/الجزائر'], + 'alpha-2-code': 'DZ', + 'continent': 'إفريقيا', + 'name': 'الجزائر', + 'capital': 'الجزائر'}, + {'timezones': ['أوروبا/سراييفو'], + 'alpha-2-code': 'BA', + 'continent': 'أوروبا', + 'name': 'البوسنة والهرسك', + 'capital': 'سراييفو'}, + {'timezones': ['آسيا/بنوم_بنه'], + 'alpha-2-code': 'KH', + 'continent': 'آسيا', + 'name': 'كمبوديا', + 'capital': 'بنوم بنه'}, + {'timezones': ['إفريقيا/بانغي'], + 'alpha-2-code': 'CF', + 'continent': 'إفريقيا', + 'name': 'جمهورية أفريقيا الوسطى', + 'capital': 'بانغي'}, + {'timezones': ['إفريقيا/نجامينا'], + 'alpha-2-code': 'TD', + 'continent': 'إفريقيا', + 'name': 'تشاد', + 'capital': "نجامينا"}, + {'timezones': ['الهندي/كومورو'], + 'alpha-2-code': 'KM', + 'continent': 'إفريقيا', + 'name': 'جزر القمر', + 'capital': 'موروني'}, + {'timezones': ['أوروبا/زغرب'], + 'alpha-2-code': 'HR', + 'continent': 'أوروبا', + 'name': 'كرواتيا', + 'capital': 'زغرب'}, + {'timezones': ['آسيا/ديلي'], + 'alpha-2-code': 'TL', + 'continent': 'آسيا', + 'name': 'تيمور الشرقية', + 'capital': 'ديلي'}, + {'timezones': ['أمريكا/السلفادور'], + 'alpha-2-code': 'SV', + 'continent': 'أمريكا الشمالية', + 'name': 'السلفادور', + 'capital': 'سان سلفادور'}, + {'timezones': ['إفريقيا/مالابو'], + 'alpha-2-code': 'GQ', + 'continent': 'إفريقيا', + 'name': 'غينيا الاستوائية', + 'capital': 'مالابو'}, + {'timezones': ['أمريكا/غرينادا'], + 'alpha-2-code': 'GD', + 'continent': 'أمريكا الشمالية', + 'name': 'غرينادا', + 'capital': "سانت جورجز"}, + {'timezones': ['آسيا/ألماتي', + 'آسيا/كيزيلوردا', + 'آسيا/أقتوبي', + 'آسيا/أقتاو', + 'آسيا/أورال'], + 'alpha-2-code': 'KZ', + 'continent': 'آسيا', + 'name': 'كازاخستان', + 'capital': 'أستانة'}, + {'timezones': ['آسيا/فيينتيان'], + 'alpha-2-code': 'LA', + 'continent': 'آسيا', + 'name': 'لاوس', + 'capital': 'فيينتيان'}, + {'timezones': ['المحيط_الهاديء/تشوك', + 'المحيط_الهاديء/بونابي', + 'المحيط_الهاديء/كورساي'], + 'alpha-2-code': 'FM', + 'continent': 'أوقيانوسيا', + 'name': 'ولايات ميكرونيسيا المتحدة', + 'capital': 'باليكير'}, + {'timezones': ['أوروبا/كيشيناو'], + 'alpha-2-code': 'MD', + 'continent': 'أوروبا', + 'name': 'مولدافيا', + 'capital': 'كيشيناو'}, + {'timezones': ['أوروبا/موناكو'], + 'alpha-2-code': 'MC', + 'continent': 'أوروبا', + 'name': 'موناكو', + 'capital': 'موناكو'}, + {'timezones': ['أوروبا/بودغوريتسا'], + 'alpha-2-code': 'ME', + 'continent': 'أوروبا', + 'name': 'الجبل الأسود', + 'capital': 'بودغوريتسا'}, + {'timezones': ['إفريقيا/الدار_البيضاء'], + 'alpha-2-code': 'MA', + 'continent': 'إفريقيا', + 'name': 'المغرب', + 'capital': 'الرباط'}, + {'timezones': ['أمريكا/سانت_كيتس'], + 'alpha-2-code': 'KN', + 'continent': 'أمريكا الشمالية', + 'name': 'سانت كيتس ونيفيس', + 'capital': 'باستير'}, + {'timezones': ['أمريكا/سانت_لوسيا'], + 'alpha-2-code': 'LC', + 'continent': 'أمريكا الشمالية', + 'name': 'سانت لوسيا', + 'capital': 'كاستريس'}, + {'timezones': ['أمريكا/سينت_فينسينت'], + 'alpha-2-code': 'VC', + 'continent': 'أمريكا الشمالية', + 'name': 'سانت فينسنت والغرينادين', + 'capital': 'كينغستاون'}, + {'timezones': ['المحيط_الهاديء/أبيا'], + 'alpha-2-code': 'WS', + 'continent': 'أوقيانوسيا', + 'name': 'ساموا', + 'capital': 'أبيا'}, + {'timezones': ['أوروبا/بلغراد'], + 'alpha-2-code': 'RS', + 'continent': 'أوروبا', + 'name': 'صربيا', + 'capital': 'بلغراد'}, + {'timezones': ['إفريقيا/جوهانسبرغ'], + 'alpha-2-code': 'ZA', + 'continent': 'إفريقيا', + 'name': 'جنوب إفريقيا', + 'capital': 'بريتوريا'}, + {'timezones': ['أوروبا/مدريد', + 'إفريقيا/سبتة', + 'الأطلنطي/الكناري'], + 'alpha-2-code': 'ES', + 'continent': 'أوروبا', + 'name': 'إسبانيا', + 'capital': 'مدريد'}, + {'timezones': ['آسيا/كولمبو'], + 'alpha-2-code': 'LK', + 'continent': 'آسيا', + 'name': 'سريلانكا', + 'capital': 'سري جاياواردنابورا كوتي'}, + {'timezones': ['إفريقيا/مبابان'], + 'alpha-2-code': 'SZ', + 'continent': 'إفريقيا', + 'name': 'سوازيلاند', + 'capital': 'مبابان'}, + {'timezones': ['أوروبا/زيورخ'], + 'alpha-2-code': 'CH', + 'continent': 'أوروبا', + 'name': 'سويسرا', + 'capital': 'برن'}, + {'timezones': ['آسيا/دبي'], + 'alpha-2-code': 'AE', + 'continent': 'آسيا', + 'name': 'الإمارات العربية المتحدة', + 'capital': 'أبو ظبي'}, + {'timezones': ['أوروبا/لندن'], + 'alpha-2-code': 'GB', + 'continent': 'أوروبا', + 'name': 'المملكة المتحدة', + 'capital': 'لندن'}, + ] + + AM_PM = { + 'AM': 'ص', + 'PM': 'م', + } + + def month_name(self): + month = self.date('%m') + return self.MONTH_NAMES[month] + + def am_pm(self): + date = self.date('%p') + return self.AM_PM[date] + + def day_of_week(self): + day = self.date('%w') + return self.DAY_NAMES[day] diff --git a/testbed/joke2k__faker/faker/providers/date_time/ar_EG/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/ar_EG/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1fb9a55b3c27d0118b5b1386ff02beddbeb03c --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/ar_EG/__init__.py @@ -0,0 +1,18 @@ +from ..ar_AA import Provider as ArabicDateTimeProvider + + +class Provider(ArabicDateTimeProvider): + MONTH_NAMES = { + '01': 'يناير', + '02': 'فبراير', + '03': 'مارس', + '04': 'أبريل', + '05': 'مايو', + '06': 'يونيو', + '07': 'يوليو', + '08': 'أغسطس', + '09': 'سبتمبر', + '10': 'أكتوبر', + '11': 'نوفمبر', + '12': 'ديسمبر', + } diff --git a/testbed/joke2k__faker/faker/providers/date_time/en_PH/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/en_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b71473d0176d5a3384048687bcea8669e8a332e --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/en_PH/__init__.py @@ -0,0 +1,6 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + """No difference from default DateTimeProvider""" + pass diff --git a/testbed/joke2k__faker/faker/providers/date_time/en_US/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/en_US/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..542b583cd7490ddc1aade911b324b030debfb017 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/en_US/__init__.py @@ -0,0 +1,5 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + pass diff --git a/testbed/joke2k__faker/faker/providers/date_time/fil_PH/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/fil_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42a736439193745ecd672678cc198a9d48ef49e4 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/fil_PH/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + """Provider for datetimes for fil_PH locale""" + + DAY_NAMES = { + '0': 'Linggo', + '1': 'Lunes', + '2': 'Martes', + '3': 'Miyerkules', + '4': 'Huwebes', + '5': 'Biyernes', + '6': 'Sabado', + } + MONTH_NAMES = { + '01': 'Enero', + '02': 'Pebrero', + '03': 'Marso', + '04': 'Abril', + '05': 'Mayo', + '06': 'Hunyo', + '07': 'Hulyo', + '08': 'Agosto', + '09': 'Setyembre', + '10': 'Oktubre', + '11': 'Nobyembre', + '12': 'Disyembre', + } + + def day_of_week(self): + day = self.date('%w') + return self.DAY_NAMES[day] + + def month_name(self): + month = self.month() + return self.MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/fr_FR/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/fr_FR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67d51fb803682ce214a482ee7ab40eda213f0f06 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/fr_FR/__init__.py @@ -0,0 +1,35 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "Dimanche", + "1": "Lundi", + "2": "Mardi", + "3": "Mercredi", + "4": "Jeudi", + "5": "Vendredi", + "6": "Samedi", + } + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "Janvier", + "02": "Février", + "03": "Mars", + "04": "Avril", + "05": "Mai", + "06": "Juin", + "07": "Juillet", + "08": "Août", + "09": "Septembre", + "10": "Octobre", + "11": "Novembre", + "12": "Décembre", + } + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/hi_IN/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/hi_IN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93ddf52d2d67e019200d8fcb8353a68599a43a50 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/hi_IN/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "सोमवार", + "1": "मंगलवार", + "2": "बुधवार", + "3": "गुरुवार", + "4": "जुम्मा", + "5": "शनिवार", + "6": "रविवार", + } + + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "जनवरी", + "02": "फ़रवरी", + "03": "मार्च", + "04": "अप्रैल", + "05": "मई", + "06": "जून", + "07": "जुलाई", + "08": "अगस्त", + "09": "सितंबर", + "10": "अक्टूबर", + "11": "नवंबर", + "12": "दिसंबर", + } + + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/hr_HR/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/hr_HR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f885a2f46474c935678f881ad2751cd27f746a7f --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/hr_HR/__init__.py @@ -0,0 +1,35 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "Nedjelja", + "1": "Ponedjeljak", + "2": "Utorak", + "3": "Srijeda", + "4": "Četvrtak", + "5": "Petak", + "6": "Subota", + } + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "Siječanj", + "02": "Veljača", + "03": "Ožujak", + "04": "Travanj", + "05": "Svibanj", + "06": "Lipanj", + "07": "Srpanj", + "08": "Kolovoz", + "09": "Rujan", + "10": "Listopad", + "11": "Studeni", + "12": "Prosinac", + } + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/hu_HU/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/hu_HU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b579af620e9390b47e5d6a18a1b43ad5a13df17 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/hu_HU/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "hétfő", + "1": "kedd", + "2": "szerda", + "3": "csütörtök", + "4": "péntek", + "5": "szombat", + "6": "vasárnap", + } + + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "január", + "02": "február", + "03": "március", + "04": "április", + "05": "május", + "06": "junius", + "07": "julius", + "08": "augusztus", + "09": "szeptember", + "10": "október", + "11": "november", + "12": "december", + } + + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/hy_AM/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/hy_AM/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad7f3cd686364dd61b01893dde35be1ef57af552 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/hy_AM/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + DAY_NAMES = { + "0": "Կիրակի", + "1": "Երկուշաբթի", + "2": "Երեքշաբթի", + "3": "Չորեքշաբթի", + "4": "Հինգշաբթի", + "5": "Ուրբաթ", + "6": "Շաբաթ", + } + + MONTH_NAMES = { + "01": "Հունվար", + "02": "Փետրվար", + "03": "Մարտ", + "04": "Ապրիլ", + "05": "Մայիս", + "06": "Հունիս", + "07": "Հուլիս", + "08": "Օգոստոս", + "09": "Սեպտեմբեր", + "10": "Հոկտեմբեր", + "11": "Նոյեմբեր", + "12": "Դեկտեմբեր", + } + + def day_of_week(self): + day = self.date('%w') + return self.DAY_NAMES[day] + + def month_name(self): + month = self.month() + return self.MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/id_ID/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/id_ID/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..943d2cf5b660ead5b4cbec9f8f0d400479476adf --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/id_ID/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "Senin", + "1": "Selasa", + "2": "Rabu", + "3": "Kamis", + "4": "Jumat", + "5": "Sabtu", + "6": "Minggu", + } + + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "Januari", + "02": "Februari", + "03": "Maret", + "04": "April", + "05": "Mei", + "06": "Juni", + "07": "Juli", + "08": "Agustus", + "09": "September", + "10": "Oktober", + "11": "November", + "12": "Desember", + } + + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/ko_KR/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/ko_KR/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2dbc623ec593b9b96bdb8ccd3e0ebc2dcbf347 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/ko_KR/__init__.py @@ -0,0 +1,35 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "일요일", + "1": "월요일", + "2": "화요일", + "3": "수요일", + "4": "목요일", + "5": "금요일", + "6": "토요일", + } + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "1월", + "02": "2월", + "03": "3월", + "04": "4월", + "05": "5월", + "06": "6월", + "07": "7월", + "08": "8월", + "09": "9월", + "10": "10월", + "11": "11월", + "12": "12월", + } + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/pl_PL/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/pl_PL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..907e8093fc05c6cf9cea93dc2b0f2f860e1f2109 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/pl_PL/__init__.py @@ -0,0 +1,37 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + DAY_NAMES = { + '0': 'poniedziałek', + '1': 'wtorek', + '2': 'środa', + '3': 'czwartek', + '4': 'piątek', + '5': 'sobota', + '6': 'niedziela', + } + + MONTH_NAMES = { + '01': 'styczeń', + '02': 'luty', + '03': 'marzec', + '04': 'kwiecień', + '05': 'maj', + '06': 'czerwiec', + '07': 'lipiec', + '08': 'sierpień', + '09': 'wrzesień', + '10': 'październik', + '11': 'listopad', + '12': 'grudzień', + } + + def day_of_week(self): + day = self.date('%w') + return self.DAY_NAMES[day] + + def month_name(self): + month = self.month() + return self.MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/ru_RU/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/ru_RU/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8618c5086ba3f4522d5d86e98b879b2edc69d940 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/ru_RU/__init__.py @@ -0,0 +1,1245 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + DAY_NAMES = { + "0": "Воскресенье", + "1": "Понедельник", + "2": "Вторник", + "3": "Среда", + "4": "Четверг", + "5": "Пятница", + "6": "Суббота", + } + + MONTH_NAMES = { + "01": "Январь", + "02": "Февраль", + "03": "Март", + "04": "Апрель", + "05": "Май", + "06": "Июнь", + "07": "Июль", + "08": "Август", + "09": "Сентябрь", + "10": "Октябрь", + "11": "Ноябрь", + "12": "Декабрь", + } + + # Timezone names are based on Wiki list, source: https://ru.wikipedia.org/wiki/Список_часовых_поясов_по_странам + countries = [{'timezones': ['Андорра (UTC+01)'], + 'alpha-2-code': 'AD', + 'alpha-3-code': 'AND', + 'continent': 'Европа', + 'name': 'Андорра', + 'capital': 'Андорра-ла-Велья'}, + {'timezones': ['Афганистан (UTC+04:30)'], + 'alpha-2-code': 'AF', + 'alpha-3-code': 'AFG', + 'continent': 'Азия', + 'name': 'Афганистан', + 'capital': 'Кабул'}, + {'timezones': ['Антигуа и Барбуда (UTC-04)'], + 'alpha-2-code': 'AG', + 'alpha-3-code': 'ATG', + 'continent': 'Северная Америка', + 'name': 'Антигуа и Барбуда', + 'capital': "Сент-Джонс"}, + {'timezones': ['Албания (UTC+01)'], + 'alpha-2-code': 'AL', + 'alpha-3-code': 'ALB', + 'continent': 'Европа', + 'name': 'Албания', + 'capital': 'Тирана'}, + {'timezones': ['Армения (UTC+04)'], + 'alpha-2-code': 'AM', + 'alpha-3-code': 'ARM', + 'continent': 'Азия', + 'name': 'Армения', + 'capital': 'Ереван'}, + {'timezones': ['Ангола (UTC+01)'], + 'alpha-2-code': 'AO', + 'alpha-3-code': 'AGO', + 'continent': 'Африка', + 'name': 'Ангола', + 'capital': 'Луанда'}, + {'timezones': ['Аргентина (UTC-03)'], + 'alpha-2-code': 'AR', + 'alpha-3-code': 'ARG', + 'continent': 'Южная Америка', + 'name': 'Аргентина', + 'capital': 'Буэнос Айрес'}, + {'timezones': ['Австрия (UTC+01)'], + 'alpha-2-code': 'AT', + 'alpha-3-code': 'AUT', + 'continent': 'Европа', + 'name': 'Австрия', + 'capital': 'Вена'}, + {'timezones': ['Австралия (UTC+05)', + 'Австралия (UTC+06:30)', + 'Австралия (UTC+07)', + 'Австралия (UTC+08)', + 'Австралия (UTC+9:30)', + 'Австралия (UTC+10)', + 'Австралия (UTC+10:30)', + 'Австралия (UTC+11:30)'], + 'alpha-2-code': 'AU', + 'alpha-3-code': 'AUS', + 'continent': 'Океания', + 'name': 'Австралия', + 'capital': 'Канберра'}, + {'timezones': ['Азербайджан (UTC+04)'], + 'alpha-2-code': 'AZ', + 'alpha-3-code': 'AZE', + 'continent': 'Азия', + 'name': 'Азербайджан', + 'capital': 'Баку'}, + {'timezones': ['Барбадос (UTC-04)'], + 'alpha-2-code': 'BB', + 'alpha-3-code': 'BRB', + 'continent': 'Северная Америка', + 'name': 'Барбадос', + 'capital': 'Бриджтаун'}, + {'timezones': ['Бангладеш (UTC+06)'], + 'alpha-2-code': 'BD', + 'alpha-3-code': 'BGD', + 'continent': 'Азия', + 'name': 'Бангладеш', + 'capital': 'Дака'}, + {'timezones': ['Бельгия (UTC+01)'], + 'alpha-2-code': 'BE', + 'alpha-3-code': 'BEL', + 'continent': 'Европа', + 'name': 'Бельгия', + 'capital': 'Брюссель'}, + {'timezones': ['Буркина-Фасо (UTC)'], + 'alpha-2-code': 'BF', + 'alpha-3-code': 'BFA', + 'continent': 'Африка', + 'name': 'Буркина-Фасо', + 'capital': 'Уагадугу'}, + {'timezones': ['Болгария (UTC+02)'], + 'alpha-2-code': 'BG', + 'alpha-3-code': 'BGR', + 'continent': 'Европа', + 'name': 'Болгария', + 'capital': 'София'}, + {'timezones': ['Бахрейн (UTC+03)'], + 'alpha-2-code': 'BH', + 'alpha-3-code': 'BHR', + 'continent': 'Азия', + 'name': 'Бахрейн', + 'capital': 'Манама'}, + {'timezones': ['Бурунди (UTC+02)'], + 'alpha-2-code': 'BI', + 'alpha-3-code': 'BDI', + 'continent': 'Африка', + 'name': 'Бурунди', + 'capital': 'Гитега'}, + {'timezones': ['Бенин (UTC+01)'], + 'alpha-2-code': 'BJ', + 'alpha-3-code': 'BEN', + 'continent': 'Африка', + 'name': 'Бенин', + 'capital': 'Порто-Ново'}, + {'timezones': ['Бруней (UTC+08)'], + 'alpha-2-code': 'BN', + 'alpha-3-code': 'BRN', + 'continent': 'Азия', + 'name': 'Бруней', + 'capital': 'Бандар-Сери-Бегаван'}, + {'timezones': ['Боливия (UTC-04)'], + 'alpha-2-code': 'BO', + 'alpha-3-code': 'BOL', + 'continent': 'Южная Америка', + 'name': 'Боливия', + 'capital': 'Сукре'}, + {'timezones': ['Бразилия (UTC-05)', + 'Бразилия (UTC-04)', + 'Бразилия (UTC-03)', + 'Бразилия (UTC-02)'], + 'alpha-2-code': 'BR', + 'alpha-3-code': 'BRA', + 'continent': 'Южная Америка', + 'name': 'Бразилия', + 'capital': 'Бразилиа'}, + {'timezones': ['Багамские Острова (UTC-05)'], + 'alpha-2-code': 'BS', + 'alpha-3-code': 'BHS', + 'continent': 'Северная Америка', + 'name': 'Багамские Острова', + 'capital': 'Нассау'}, + {'timezones': ['Бутан (UTC+06)'], + 'alpha-2-code': 'BT', + 'alpha-3-code': 'BTN', + 'continent': 'Азия', + 'name': 'Бутан', + 'capital': 'Тхимпху'}, + {'timezones': ['Ботсвана (UTC+02)'], + 'alpha-2-code': 'BW', + 'alpha-3-code': 'BWA', + 'continent': 'Африка', + 'name': 'Ботсвана', + 'capital': 'Габороне'}, + {'timezones': ['Белоруссия (UTC+03)'], + 'alpha-2-code': 'BY', + 'alpha-3-code': 'BLR', + 'continent': 'Европа', + 'name': 'Белоруссия', + 'capital': 'Минск'}, + {'timezones': ['Белиз (UTC-06)'], + 'alpha-2-code': 'BZ', + 'alpha-3-code': 'BLZ', + 'continent': 'Северная Америка', + 'name': 'Белиз', + 'capital': 'Бельмопан'}, + {'timezones': ['Канада (UTC-08)', + 'Канада (UTC-07)', + 'Канада (UTC-06)', + 'Канада (UTC-05)', + 'Канада (UTC-04)', + 'Канада (UTC-03:30)'], + 'alpha-2-code': 'CA', + 'alpha-3-code': 'CAN', + 'continent': 'Северная Америка', + 'name': 'Канада', + 'capital': 'Оттава'}, + {'timezones': ['Демократическая Республика Конго (UTC+01)', + 'Демократическая Республика Конго (UTC+02)'], + 'alpha-2-code': 'CD', + 'alpha-3-code': 'COD', + 'continent': 'Африка', + 'name': 'Демократическая Республика Конго', + 'capital': 'Киншаса'}, + {'timezones': ['Республика Конго (UTC+01)'], + 'alpha-2-code': 'CG', + 'alpha-3-code': 'COG', + 'continent': 'Африка', + 'name': 'Руспублика Конго', + 'capital': 'Браззавиль'}, + {'timezones': ["Кот-д'Ивуар (UTC)"], + 'alpha-2-code': 'CI', + 'alpha-3-code': 'CIV', + 'continent': 'Африка', + 'name': "Кот-д'Ивуар", + 'capital': 'Ямусукро'}, + {'timezones': ['Чили (UTC-06)', + 'Чили (UTC-04)'], + 'alpha-2-code': 'CL', + 'alpha-3-code': 'CHL', + 'continent': 'Южная Америка', + 'name': 'Чили', + 'capital': 'Сантьяго'}, + {'timezones': ['Камерун (UTC+01)'], + 'alpha-2-code': 'CM', + 'alpha-3-code': 'CMR', + 'continent': 'Африка', + 'name': 'Камерун', + 'capital': 'Яунде'}, + {'timezones': ['Китай (UTC+08)'], + 'alpha-2-code': 'CN', + 'alpha-3-code': 'CHN', + 'continent': 'Азия', + 'name': "Китайская Народная Республика", + 'capital': 'Пекин'}, + {'timezones': ['Колумбия (UTC-05)'], + 'alpha-2-code': 'CO', + 'alpha-3-code': 'COL', + 'continent': 'Южная Америка', + 'name': 'Колумбия', + 'capital': 'Богота'}, + {'timezones': ['Коста-Рика (UTC-06)'], + 'alpha-2-code': 'CR', + 'alpha-3-code': 'CRI', + 'continent': 'Северная Америка', + 'name': 'Коста-Рика', + 'capital': 'Сан-Хосе'}, + {'timezones': ['Куба (UTC-05)'], + 'alpha-2-code': 'CU', + 'alpha-3-code': 'CUB', + 'continent': 'Северная Америка', + 'name': 'Куба', + 'capital': 'Гавана'}, + {'timezones': ['Кабо-Верде (UTC-01)'], + 'alpha-2-code': 'CV', + 'alpha-3-code': 'CPV', + 'continent': 'Африка', + 'name': 'Кабо-Верде', + 'capital': 'Прая'}, + {'timezones': ['Кипр (UTC+02)'], + 'alpha-2-code': 'CY', + 'alpha-3-code': 'CYP', + 'continent': 'Азия', + 'name': 'Кипр', + 'capital': 'Никосия'}, + {'timezones': ['Чехия (UTC+01)'], + 'alpha-2-code': 'CZ', + 'alpha-3-code': 'CZE', + 'continent': 'Европа', + 'name': 'Чехия', + 'capital': 'Прага'}, + {'timezones': ['Германия (UTC+01)'], + 'alpha-2-code': 'DE', + 'alpha-3-code': 'DEU', + 'continent': 'Европа', + 'name': 'Германия', + 'capital': 'Берлин'}, + {'timezones': ['Джибути (UTC+03)'], + 'alpha-2-code': 'DJ', + 'alpha-3-code': 'DJI', + 'continent': 'Африка', + 'name': 'Джибути', + 'capital': 'Джибути'}, + {'timezones': ['Дания (UTC+01)'], + 'alpha-2-code': 'DK', + 'alpha-3-code': 'DNK', + 'continent': 'Европа', + 'name': 'Дания', + 'capital': 'Копенгаген'}, + {'timezones': ['Доминика (UTC-04)'], + 'alpha-2-code': 'DM', + 'alpha-3-code': 'DMA', + 'continent': 'Северная Америка', + 'name': 'Доминика', + 'capital': 'Розо'}, + {'timezones': ['Доминиканская Республика (UTC-04)'], + 'alpha-2-code': 'DO', + 'alpha-3-code': 'DOM', + 'continent': 'Северная Америка', + 'name': 'Доминиканская Республика', + 'capital': 'Санто-Доминго'}, + {'timezones': ['Эквадор (UTC-06)', + 'Эквадор (UTC-05)'], + 'alpha-2-code': 'EC', + 'alpha-3-code': 'ECU', + 'continent': 'Южная Америка', + 'name': 'Эквадор', + 'capital': 'Кито'}, + {'timezones': ['Эстония (UTC+02)'], + 'alpha-2-code': 'EE', + 'alpha-3-code': 'EST', + 'continent': 'Европа', + 'name': 'Эстония', + 'capital': 'Таллинн'}, + {'timezones': ['Египет (UTC+02)'], + 'alpha-2-code': 'EG', + 'alpha-3-code': 'EGY', + 'continent': 'Африка', + 'name': 'Египет', + 'capital': 'Каир'}, + {'timezones': ['Эритрея (UTC+03)'], + 'alpha-2-code': 'ER', + 'alpha-3-code': 'ERI', + 'continent': 'Африка', + 'name': 'Эритрея', + 'capital': 'Асмэра'}, + {'timezones': ['Эфиопия (UTC+03)'], + 'alpha-2-code': 'ET', + 'alpha-3-code': 'ETH', + 'continent': 'Африка', + 'name': 'Эфиопия', + 'capital': 'Аддис-Абеба'}, + {'timezones': ['Финляндия (UTC+02)'], + 'alpha-2-code': 'FI', + 'alpha-3-code': 'FIN', + 'continent': 'Европа', + 'name': 'Финляндия', + 'capital': 'Хельсинки'}, + {'timezones': ['Фиджи (UTC+12)'], + 'alpha-2-code': 'FJ', + 'alpha-3-code': 'FJI', + 'continent': 'Океания', + 'name': 'Фиджи', + 'capital': 'Сува'}, + {'timezones': ['Франция (UTC+01)'], + 'alpha-2-code': 'FR', + 'alpha-3-code': 'FRA', + 'continent': 'Европа', + 'name': 'Франция', + 'capital': 'Париж'}, + {'timezones': ['Габон (UTC+01)'], + 'alpha-2-code': 'GA', + 'alpha-3-code': 'GAB', + 'continent': 'Африка', + 'name': 'Габон', + 'capital': 'Либревиль'}, + {'timezones': ['Грузия (UTC+04)'], + 'alpha-2-code': 'GE', + 'alpha-3-code': 'GEO', + 'continent': 'Азия', + 'name': 'Грузия', + 'capital': 'Тбилиси'}, + {'timezones': ['Гана (UTC)'], + 'alpha-2-code': 'GH', + 'alpha-3-code': 'GHA', + 'continent': 'Африка', + 'name': 'Гана', + 'capital': 'Аккра'}, + {'timezones': ['Гамбия (UTC)'], + 'alpha-2-code': 'GM', + 'alpha-3-code': 'GMB', + 'continent': 'Африка', + 'name': 'Гамбия', + 'capital': 'Банджул'}, + {'timezones': ['Гвинея (UTC)'], + 'alpha-2-code': 'GN', + 'alpha-3-code': 'GIN', + 'continent': 'Африка', + 'name': 'Гвинея', + 'capital': 'Конакри'}, + {'timezones': ['Греция (UTC+02)'], + 'alpha-2-code': 'GR', + 'alpha-3-code': 'GRC', + 'continent': 'Европа', + 'name': 'Греция', + 'capital': 'Афины'}, + {'timezones': ['Гватемала (UTC-06)'], + 'alpha-2-code': 'GT', + 'alpha-3-code': 'GTM', + 'continent': 'Северная Америка', + 'name': 'Гватемала', + 'capital': 'Гватемала'}, + {'timezones': ['Гаити (UTC-05)'], + 'alpha-2-code': 'HT', + 'alpha-3-code': 'HTI', + 'continent': 'Северная Америка', + 'name': 'Гаити', + 'capital': 'Порт-о-Пренс'}, + {'timezones': ['Гвинея-Бисау (UTC)'], + 'alpha-2-code': 'GW', + 'alpha-3-code': 'GNB', + 'continent': 'Африка', + 'name': 'Гвинея-Бисау', + 'capital': 'Бисау'}, + {'timezones': ['Гайана (UTC-04)'], + 'alpha-2-code': 'GY', + 'alpha-3-code': 'GUY', + 'continent': 'Южная Америка', + 'name': 'Гайана', + 'capital': 'Джорджтаун'}, + {'timezones': ['Гондурас (UTC-06)'], + 'alpha-2-code': 'HN', + 'alpha-3-code': 'HND', + 'continent': 'Северная Америка', + 'name': 'Гондурас', + 'capital': 'Тегусигальпа'}, + {'timezones': ['Венгрия (UTC+01)'], + 'alpha-2-code': 'HU', + 'alpha-3-code': 'HUN', + 'continent': 'Европа', + 'name': 'Венгрия', + 'capital': 'Будапешт'}, + {'timezones': ['Индонезия (UTC+07)', + 'Индонезия (UTC+08)', + 'Индонезия (UTC+09)'], + 'alpha-2-code': 'ID', + 'alpha-3-code': 'IDN', + 'continent': 'Азия', + 'name': 'Индонезия', + 'capital': 'Джакарта'}, + {'timezones': ['Ирландия (UTC)'], + 'alpha-2-code': 'IE', + 'alpha-3-code': 'IRL', + 'continent': 'Европа', + 'name': 'Ирландия', + 'capital': 'Дублин'}, + {'timezones': ['Израиль (UTC+02)'], + 'alpha-2-code': 'IL', + 'alpha-3-code': 'ISR', + 'continent': 'Азия', + 'name': 'Израиль', + 'capital': 'Иерусалим'}, + {'timezones': ['Индия (UTC+05:30'], + 'alpha-2-code': 'IN', + 'alpha-3-code': 'IND', + 'continent': 'Азия', + 'name': 'Индия', + 'capital': 'Дели'}, + {'timezones': ['Ирак (UTC+03)'], + 'alpha-2-code': 'IQ', + 'alpha-3-code': 'IRQ', + 'continent': 'Азия', + 'name': 'Ирак', + 'capital': 'Багдад'}, + {'timezones': ['Иран (UTC+03:30)'], + 'alpha-2-code': 'IR', + 'alpha-3-code': 'IRN', + 'continent': 'Азия', + 'name': 'Иран', + 'capital': 'Тегеран'}, + {'timezones': ['Исландия (UTC)'], + 'alpha-2-code': 'IS', + 'alpha-3-code': 'ISL', + 'continent': 'Европа', + 'name': 'Исландия', + 'capital': 'Рейкьявик'}, + {'timezones': ['Италия (UTC+01)'], + 'alpha-2-code': 'IT', + 'alpha-3-code': 'ITA', + 'continent': 'Европа', + 'name': 'Италия', + 'capital': 'Рим'}, + {'timezones': ['Ямайка (UTC-05)'], + 'alpha-2-code': 'JM', + 'alpha-3-code': 'JAM', + 'continent': 'Северная Америка', + 'name': 'Ямайка', + 'capital': 'Кингстон'}, + {'timezones': ['Иордания (UTC+02)'], + 'alpha-2-code': 'JO', + 'alpha-3-code': 'JOR', + 'continent': 'Азия', + 'name': 'Иордания', + 'capital': 'Амман'}, + {'timezones': ['Япония (UTC+09)'], + 'alpha-2-code': 'JP', + 'alpha-3-code': 'JPN', + 'continent': 'Азия', + 'name': 'Япония', + 'capital': 'Токио'}, + {'timezones': ['Кения (UTC+03)'], + 'alpha-2-code': 'KE', + 'alpha-3-code': 'KEN', + 'continent': 'Африка', + 'name': 'Кения', + 'capital': 'Найроби'}, + {'timezones': ['Киргизия (UTC+06)'], + 'alpha-2-code': 'KG', + 'alpha-3-code': 'KGZ', + 'continent': 'Азия', + 'name': 'Киргизия', + 'capital': 'Бишкек'}, + {'timezones': ['Кирибати (UTC+12)', + 'Кирибати (UTC+13)', + 'Кирибати (UTC+14)'], + 'alpha-2-code': 'KI', + 'alpha-3-code': 'KIR', + 'continent': 'Океания', + 'name': 'Кирибати', + 'capital': 'Южная Тарава'}, + {'timezones': ['КНДР (UTC+09)'], + 'alpha-2-code': 'KP', + 'alpha-3-code': 'PRK', + 'continent': 'Азия', + 'name': 'КНДР', + 'capital': 'Пхеньян'}, + {'timezones': ['Республика Корея (UTC+09)'], + 'alpha-2-code': 'KR', + 'alpha-3-code': 'KOR', + 'continent': 'Азия', + 'name': 'Республика Корея', + 'capital': 'Сеул'}, + {'timezones': ['Кувейт (UTC+03)'], + 'alpha-2-code': 'KW', + 'alpha-3-code': 'KWT', + 'continent': 'Азия', + 'name': 'Кувейт', + 'capital': 'Эль-Кувейт'}, + {'timezones': ['Ливан (UTC+02)'], + 'alpha-2-code': 'LB', + 'alpha-3-code': 'LBN', + 'continent': 'Азия', + 'name': 'Ливан', + 'capital': 'Бейрут'}, + {'timezones': ['Лихтенштейн (UTC+01)'], + 'alpha-2-code': 'LI', + 'alpha-3-code': 'LIE', + 'continent': 'Европа', + 'name': 'Лихтенштейн', + 'capital': 'Вадуц'}, + {'timezones': ['Либерия (UTC)'], + 'alpha-2-code': 'LR', + 'alpha-3-code': 'LBR', + 'continent': 'Африка', + 'name': 'Либерия', + 'capital': 'Монровия'}, + {'timezones': ['Лесото (UTC+02)'], + 'alpha-2-code': 'LS', + 'alpha-3-code': 'LSO', + 'continent': 'Африка', + 'name': 'Лесото', + 'capital': 'Масеру'}, + {'timezones': ['Литва (UTC+02)'], + 'alpha-2-code': 'LT', + 'alpha-3-code': 'LTU', + 'continent': 'Европа', + 'name': 'Литва', + 'capital': 'Вильнюс'}, + {'timezones': ['Люксембург (UTC+01)'], + 'alpha-2-code': 'LU', + 'alpha-3-code': 'LUX', + 'continent': 'Европа', + 'name': 'Люксембург', + 'capital': 'Люксембург'}, + {'timezones': ['Латвия (UTC+02)'], + 'alpha-2-code': 'LV', + 'alpha-3-code': 'LVA', + 'continent': 'Европа', + 'name': 'Латвия', + 'capital': 'Рига'}, + {'timezones': ['Ливия (UTC+02)'], + 'alpha-2-code': 'LY', + 'alpha-3-code': 'LBY', + 'continent': 'Африка', + 'name': 'Ливия', + 'capital': 'Триполи'}, + {'timezones': ['Мадагаскар (UTC+03)'], + 'alpha-2-code': 'MG', + 'alpha-3-code': 'MDG', + 'continent': 'Африка', + 'name': 'Мадагаскар', + 'capital': 'Антананариву'}, + {'timezones': ['Маршалловы Острова (UTC+12)'], + 'alpha-2-code': 'MH', + 'alpha-3-code': 'MHL', + 'continent': 'Океания', + 'name': 'Маршалловы Острова', + 'capital': 'Маджуро'}, + {'timezones': ['Северная Македония (UTC+01)'], + 'alpha-2-code': 'MK', + 'alpha-3-code': 'MKD', + 'continent': 'Европа', + 'name': 'Северная Македония', + 'capital': 'Скопье'}, + {'timezones': ['Мали (UTC)'], + 'alpha-2-code': 'ML', + 'alpha-3-code': 'MLI', + 'continent': 'Африка', + 'name': 'Мали', + 'capital': 'Бамако'}, + {'timezones': ['Мьянма (UTC+06:30)'], + 'alpha-2-code': 'MM', + 'alpha-3-code': 'MMR', + 'continent': 'Азия', + 'name': 'Мьянма', + 'capital': 'Нейпьидо'}, + {'timezones': ['Монголия (UTC+07)', + 'Монголия (UTC+08)'], + 'alpha-2-code': 'MN', + 'alpha-3-code': 'MNG', + 'continent': 'Азия', + 'name': 'Монголия', + 'capital': 'Улан-Батор'}, + {'timezones': ['Мавритания (UTC)'], + 'alpha-2-code': 'MR', + 'alpha-3-code': 'MRT', + 'continent': 'Африка', + 'name': 'Мавритания', + 'capital': 'Нуакшот'}, + {'timezones': ['Мальта (UTC+01)'], + 'alpha-2-code': 'MT', + 'alpha-3-code': 'MLT', + 'continent': 'Европа', + 'name': 'Мальта', + 'capital': 'Валлетта'}, + {'timezones': ['Маврикий (UTC+04)'], + 'alpha-2-code': 'MU', + 'alpha-3-code': 'MUS', + 'continent': 'Африка', + 'name': 'Маврикий', + 'capital': 'Порт-Луи'}, + {'timezones': ['Мальдивы (UTC+05)'], + 'alpha-2-code': 'MV', + 'alpha-3-code': 'MDV', + 'continent': 'Азия', + 'name': 'Мальдивы', + 'capital': 'Мале'}, + {'timezones': ['Малави (UTC+02)'], + 'alpha-2-code': 'MW', + 'alpha-3-code': 'MWI', + 'continent': 'Африка', + 'name': 'Малави', + 'capital': 'Лилонгве'}, + {'timezones': ['Мексика (UTC-08)', + 'Мексика (UTC-07)', + 'Мексика (UTC-06)'], + 'alpha-2-code': 'MX', + 'alpha-3-code': 'MEX', + 'continent': 'Северная Америка', + 'name': 'Мексика', + 'capital': 'Мехико'}, + {'timezones': ['Малайзия (UTC+08)'], + 'alpha-2-code': 'MY', + 'alpha-3-code': 'MYS', + 'continent': 'Азия', + 'name': 'Малайзия', + 'capital': 'Куала-Лумпур'}, + {'timezones': ['Мозамбик (UTC+02)'], + 'alpha-2-code': 'MZ', + 'alpha-3-code': 'MOZ', + 'continent': 'Африка', + 'name': 'Мозамбик', + 'capital': 'Мапуту'}, + {'timezones': ['Намибия (UTC+01)'], + 'alpha-2-code': 'NA', + 'alpha-3-code': 'NAM', + 'continent': 'Африка', + 'name': 'Намибия', + 'capital': 'Виндхук'}, + {'timezones': ['Нигер (UTC+01)'], + 'alpha-2-code': 'NE', + 'alpha-3-code': 'NER', + 'continent': 'Африка', + 'name': 'Нигер', + 'capital': 'Ниамей'}, + {'timezones': ['Нигерия (UTC+01)'], + 'alpha-2-code': 'NG', + 'alpha-3-code': 'NGA', + 'continent': 'Африка', + 'name': 'Нигерия', + 'capital': 'Абуджа'}, + {'timezones': ['Никарагуа (UTC-06)'], + 'alpha-2-code': 'NI', + 'alpha-3-code': 'NIC', + 'continent': 'Северная Америка', + 'name': 'Никарагуа', + 'capital': 'Манагуа'}, + {'timezones': ['Нидерланды (UTC+01)'], + 'alpha-2-code': 'NL', + 'alpha-3-code': 'NLD', + 'continent': 'Европа', + 'name': 'Нидерланды', + 'capital': 'Амстердам'}, + {'timezones': ['Норвегия (UTC+01)'], + 'alpha-2-code': 'NO', + 'alpha-3-code': 'NOR', + 'continent': 'Европа', + 'name': 'Норвегия', + 'capital': 'Осло'}, + {'timezones': ['Непал (UTC+05:45'], + 'alpha-2-code': 'NP', + 'alpha-3-code': 'NPL', + 'continent': 'Азия', + 'name': 'Непал', + 'capital': 'Катманду'}, + {'timezones': ['Науру (UTC+12)'], + 'alpha-2-code': 'NR', + 'alpha-3-code': 'NRU', + 'continent': 'Океания', + 'name': 'Науру', + 'capital': 'Ярен'}, + {'timezones': ['Новая Зеландия (UTC+12)'], + 'alpha-2-code': 'NZ', + 'alpha-3-code': 'NZL', + 'continent': 'Океания', + 'name': 'Новая Зеландия', + 'capital': 'Веллингтон'}, + {'timezones': ['Оман (UTC+04'], + 'alpha-2-code': 'OM', + 'alpha-3-code': 'OMN', + 'continent': 'Азия', + 'name': 'Оман', + 'capital': 'Маскат'}, + {'timezones': ['Панама (UTC-05)'], + 'alpha-2-code': 'PA', + 'alpha-3-code': 'PAN', + 'continent': 'Северная Америка', + 'name': 'Панама', + 'capital': 'Панама'}, + {'timezones': ['Перу (UTC-05)'], + 'alpha-2-code': 'PE', + 'alpha-3-code': 'PER', + 'continent': 'Южная Америка', + 'name': 'Перу', + 'capital': 'Лима'}, + {'timezones': ['Папуа - Новая Гвинея (UTC+10)'], + 'alpha-2-code': 'PG', + 'alpha-3-code': 'PNG', + 'continent': 'Океания', + 'name': 'Папуа - Новая Гвинея', + 'capital': 'Порт-Морсби'}, + {'timezones': ['Филиппины (UTC+08)'], + 'alpha-2-code': 'PH', + 'alpha-3-code': 'PHL', + 'continent': 'Азия', + 'name': 'Филиппины', + 'capital': 'Манила'}, + {'timezones': ['Пакистан (UTC+05)'], + 'alpha-2-code': 'PK', + 'alpha-3-code': 'PAK', + 'continent': 'Азия', + 'name': 'Пакистан', + 'capital': 'Исламабад'}, + {'timezones': ['Польша (UTC+01)'], + 'alpha-2-code': 'PL', + 'alpha-3-code': 'POL', + 'continent': 'Европа', + 'name': 'Польша', + 'capital': 'Варшава'}, + {'timezones': ['Португалия (UTC)'], + 'alpha-2-code': 'PT', + 'alpha-3-code': 'PRT', + 'continent': 'Европа', + 'name': 'Португалия', + 'capital': 'Лиссабон'}, + {'timezones': ['Палау (UTC+09)'], + 'alpha-2-code': 'PW', + 'alpha-3-code': 'PLW', + 'continent': 'Океания', + 'name': 'Палау', + 'capital': 'Кампала'}, + {'timezones': ['Парагвай (UTC-04)'], + 'alpha-2-code': 'PY', + 'alpha-3-code': 'PRY', + 'continent': 'Южная Америка', + 'name': 'Парагвай', + 'capital': 'Асунсьон'}, + {'timezones': ['Катар (UTC+03)'], + 'alpha-2-code': 'QA', + 'alpha-3-code': 'QAT', + 'continent': 'Азия', + 'name': 'Катар', + 'capital': 'Доха'}, + {'timezones': ['Румыния (UTC+02)'], + 'alpha-2-code': 'RO', + 'alpha-3-code': 'ROU', + 'continent': 'Европа', + 'name': 'Румыния', + 'capital': 'Бухарест'}, + {'timezones': ['Россия (UTC+02)', + 'Россия (UTC+03)', + 'Россия (UTC+04)', + 'Россия (UTC+05)', + 'Россия (UTC+06)', + 'Россия (UTC+07)', + 'Россия (UTC+08)', + 'Россия (UTC+09)', + 'Россия (UTC+10)', + 'Россия (UTC+11)', + 'Россия (UTC+12)'], + 'alpha-2-code': 'RU', + 'alpha-3-code': 'RUS', + 'continent': 'Европа', + 'name': 'Россия', + 'capital': 'Москва'}, + {'timezones': ['Руанда (UTC+02)'], + 'alpha-2-code': 'RW', + 'alpha-3-code': 'RWA', + 'continent': 'Африка', + 'name': 'Руанда', + 'capital': 'Кигали'}, + {'timezones': ['Саудовская Аравия (UTC+03)'], + 'alpha-2-code': 'SA', + 'alpha-3-code': 'SAU', + 'continent': 'Азия', + 'name': 'Саудовская Аравия', + 'capital': 'Эр-Рияд'}, + {'timezones': ['Соломоновы Острова (UTC+11)'], + 'alpha-2-code': 'SB', + 'alpha-3-code': 'SLB', + 'continent': 'Океания', + 'name': 'Соломоновы Острова', + 'capital': 'Хониара'}, + {'timezones': ['Сейшельские острова (UTC+04)'], + 'alpha-2-code': 'SC', + 'alpha-3-code': 'SYC', + 'continent': 'Африка', + 'name': 'Сейшельские острова', + 'capital': 'Виктория'}, + {'timezones': ['Судан (UTC+03)'], + 'alpha-2-code': 'SD', + 'alpha-3-code': 'SDN', + 'continent': 'Африка', + 'name': 'Судан', + 'capital': 'Хартум'}, + {'timezones': ['Швеция (UTC+01)'], + 'alpha-2-code': 'SE', + 'alpha-3-code': 'SWE', + 'continent': 'Европа', + 'name': 'Швеци', + 'capital': 'Стокгольм'}, + {'timezones': ['Сингапур (UTC+08)'], + 'alpha-2-code': 'SG', + 'alpha-3-code': 'SGP', + 'continent': 'Азия', + 'name': 'Сингапур', + 'capital': 'Сингапур'}, + {'timezones': ['Словения (UTC+01)'], + 'alpha-2-code': 'SI', + 'alpha-3-code': 'SVN', + 'continent': 'Европа', + 'name': 'Словения', + 'capital': 'Любляна'}, + {'timezones': ['Словакия (UTC+01)'], + 'alpha-2-code': 'SK', + 'alpha-3-code': 'SVK', + 'continent': 'Европа', + 'name': 'Словакия', + 'capital': 'Братислава'}, + {'timezones': ['Сьерра-Леоне (UTC)'], + 'alpha-2-code': 'SL', + 'alpha-3-code': 'SLE', + 'continent': 'Африка', + 'name': 'Сьерра Леоне', + 'capital': 'Фритаун'}, + {'timezones': ['Сан-Марино (UTC+01)'], + 'alpha-2-code': 'SM', + 'alpha-3-code': 'SMR', + 'continent': 'Европа', + 'name': 'Сан-Марино', + 'capital': 'Сан-Марино'}, + {'timezones': ['Сенегал (UTC)'], + 'alpha-2-code': 'SN', + 'alpha-3-code': 'SEN', + 'continent': 'Африка', + 'name': 'Сенегал', + 'capital': 'Дакар'}, + {'timezones': ['Сомали (UTC+03)'], + 'alpha-2-code': 'SO', + 'alpha-3-code': 'SOM', + 'continent': 'Африка', + 'name': 'Сомали', + 'capital': 'Могадишо'}, + {'timezones': ['Суринам (UTC-03)'], + 'alpha-2-code': 'SR', + 'alpha-3-code': 'SUR', + 'continent': 'Южная Америка', + 'name': 'Суринам', + 'capital': 'Парамарибо'}, + {'timezones': ['Сан-Томе и Принсипи (UTC)'], + 'alpha-2-code': 'ST', + 'alpha-3-code': 'STP', + 'continent': 'Африка', + 'name': 'Сан-Томе и Принсипи', + 'capital': 'Сан-Томе'}, + {'timezones': ['Сирия (UTC+02)'], + 'alpha-2-code': 'SY', + 'alpha-3-code': 'SYR', + 'continent': 'Азия', + 'name': 'Сирия', + 'capital': 'Дамаск'}, + {'timezones': ['Того (UTC)'], + 'alpha-2-code': 'TG', + 'alpha-3-code': 'TGO', + 'continent': 'Африка', + 'name': 'Того', + 'capital': 'Ломе'}, + {'timezones': ['Таиланд (UTC+07)'], + 'alpha-2-code': 'TH', + 'alpha-3-code': 'THA', + 'continent': 'Азия', + 'name': 'Таиланд', + 'capital': 'Бангкок'}, + {'timezones': ['Таджикистан (UTC+05)'], + 'alpha-2-code': 'TJ', + 'alpha-3-code': 'TJK', + 'continent': 'Азия', + 'name': 'Таджикистан', + 'capital': 'Душанбе'}, + {'timezones': ['Туркмения (UTC+05)'], + 'alpha-2-code': 'TM', + 'alpha-3-code': 'TKM', + 'continent': 'Азия', + 'name': 'Туркмения', + 'capital': 'Ашхабад'}, + {'timezones': ['Тунис (UTC+01)'], + 'alpha-2-code': 'TN', + 'alpha-3-code': 'TUN', + 'continent': 'Африка', + 'name': 'Тунис', + 'capital': 'Тунис'}, + {'timezones': ['Тонга (UTC+13)'], + 'alpha-2-code': 'TO', + 'alpha-3-code': 'TON', + 'continent': 'Океания', + 'name': 'Тонга', + 'capital': 'Нукуалофа'}, + {'timezones': ['Турция (UTC+02)'], + 'alpha-2-code': 'TR', + 'alpha-3-code': 'TUR', + 'continent': 'Азия', + 'name': 'Турция', + 'capital': 'Анкара'}, + {'timezones': ['Тринидад и Тобаго (UTC-04)'], + 'alpha-2-code': 'TT', + 'alpha-3-code': 'TTO', + 'continent': 'Северная Америка', + 'name': 'Тринидад и Тобаго', + 'capital': 'Порт-оф-Спейн'}, + {'timezones': ['Тувалу (UTC+12)'], + 'alpha-2-code': 'TV', + 'alpha-3-code': 'TUV', + 'continent': 'Океания', + 'name': 'Тувалу', + 'capital': 'Фунафути'}, + {'timezones': ['Танзания (UTC+03)'], + 'alpha-2-code': 'TZ', + 'alpha-3-code': 'TZA', + 'continent': 'Африка', + 'name': 'Танзания', + 'capital': 'Додома'}, + {'timezones': ['Украина (UTC+02)', + 'Украина (UTC+03)'], + 'alpha-2-code': 'UA', + 'alpha-3-code': 'UKR', + 'continent': 'Европа', + 'name': 'Украина', + 'capital': 'Киев'}, + {'timezones': ['Уганда (UTC+03)'], + 'alpha-2-code': 'UG', + 'alpha-3-code': 'UGA', + 'continent': 'Африка', + 'name': 'Уганда', + 'capital': 'Кампала'}, + {'timezones': ['США (UTC-11)', + 'США (UTC-10)', + 'США (UTC-09)', + 'США (UTC-08)', + 'США (UTC-07)', + 'США (UTC-06)', + 'США (UTC-05)', + 'США (UTC-04)', + 'США (UTC+10)'], + 'alpha-2-code': 'US', + 'alpha-3-code': 'USA', + 'continent': 'Северная Америка', + 'name': 'США', + 'capital': 'Вашингтон'}, + {'timezones': ['Уругвай (UTC-03)'], + 'alpha-2-code': 'UY', + 'alpha-3-code': 'URY', + 'continent': 'Южная Америка', + 'name': 'Уругвай', + 'capital': 'Монтевидео'}, + {'timezones': ['Узбекистан (UTC+05)'], + 'alpha-2-code': 'UZ', + 'alpha-3-code': 'UZB', + 'continent': 'Азия', + 'name': 'Узбекистан', + 'capital': 'Ташкент'}, + {'timezones': ['Ватикан (UTC+01)'], + 'alpha-2-code': 'VA', + 'alpha-3-code': 'VAT', + 'continent': 'Европа', + 'name': 'Ватикан', + 'capital': 'Ватикан'}, + {'timezones': ['Венесуэла (UTC-04:30)'], + 'alpha-2-code': 'VE', + 'alpha-3-code': 'VEN', + 'continent': 'Южная Америка', + 'name': 'Венесуэла', + 'capital': 'Каракас'}, + {'timezones': ['Вьетнам (UTC+07)'], + 'alpha-2-code': 'VN', + 'alpha-3-code': 'VNM', + 'continent': 'Азия', + 'name': 'Вьетнам', + 'capital': 'Ханой'}, + {'timezones': ['Вануату (UTC+11)'], + 'alpha-2-code': 'VU', + 'alpha-3-code': 'VUT', + 'continent': 'Океания', + 'name': 'Вануату', + 'capital': 'Порт-Вила'}, + {'timezones': ['Йемен (UTC+03)'], + 'alpha-2-code': 'YE', + 'alpha-3-code': 'YEM', + 'continent': 'Азия', + 'name': 'Йемен', + 'capital': "Сана"}, + {'timezones': ['Замбия (UTC+02)'], + 'alpha-2-code': 'ZM', + 'alpha-3-code': 'ZMB', + 'continent': 'Африка', + 'name': 'Замбия', + 'capital': 'Лусака'}, + {'timezones': ['Зимбабве (UTC+02)'], + 'alpha-2-code': 'ZW', + 'alpha-3-code': 'ZWE', + 'continent': 'Африка', + 'name': 'Зимбабве', + 'capital': 'Хараре'}, + {'timezones': ['Алжир (UTC+01)'], + 'alpha-2-code': 'DZ', + 'alpha-3-code': 'DZA', + 'continent': 'Африка', + 'name': 'Алжир', + 'capital': 'Алжир'}, + {'timezones': ['Босния и Герцеговина (UTC+01)'], + 'alpha-2-code': 'BA', + 'alpha-3-code': 'BIH', + 'continent': 'Европа', + 'name': 'Босния и Герцеговина', + 'capital': 'Сараево'}, + {'timezones': ['Камбоджа (UTC+07)'], + 'alpha-2-code': 'KH', + 'alpha-3-code': 'KHM', + 'continent': 'Азия', + 'name': 'Камбоджа', + 'capital': 'Пномпень'}, + {'timezones': ['ЦАР (UTC+01)'], + 'alpha-2-code': 'CF', + 'alpha-3-code': 'CAF', + 'continent': 'Африка', + 'name': 'ЦАР', + 'capital': 'Банги'}, + {'timezones': ['Чад (UTC+01)'], + 'alpha-2-code': 'TD', + 'alpha-3-code': 'TCD', + 'continent': 'Африка', + 'name': 'Чад', + 'capital': "Нджамена"}, + {'timezones': ['Коморы (UTC+03)'], + 'alpha-2-code': 'KM', + 'alpha-3-code': 'COM', + 'continent': 'Африка', + 'name': 'Коморы', + 'capital': 'Морони'}, + {'timezones': ['Хорватия (UTC+01)'], + 'alpha-2-code': 'HR', + 'alpha-3-code': 'HRV', + 'continent': 'Европа', + 'name': 'Хорватия', + 'capital': 'Загреб'}, + {'timezones': ['Восточный Тимор (UTC+09)'], + 'alpha-2-code': 'TL', + 'alpha-3-code': 'TLS', + 'continent': 'Азия', + 'name': 'Восточный Тимор', + 'capital': 'Дили'}, + {'timezones': ['Сальвадор (UTC-06)'], + 'alpha-2-code': 'SV', + 'alpha-3-code': 'SLV', + 'continent': 'Северная Америка', + 'name': 'Сальвадор', + 'capital': 'Сан-Сальвадор'}, + {'timezones': ['Экваториальная Гвинея (UTC+01)'], + 'alpha-2-code': 'GQ', + 'alpha-3-code': 'GNQ', + 'continent': 'Африка', + 'name': 'Экваториальная Гвинея', + 'capital': 'Малабо'}, + {'timezones': ['Гренада (UTC-04)'], + 'alpha-2-code': 'GD', + 'alpha-3-code': 'GRD', + 'continent': 'Северная Америка', + 'name': 'Гренада', + 'capital': "Сент-Джорджес"}, + {'timezones': ['Казахстан (UTC+05)', + 'Казахстан (UTC+06)'], + 'alpha-2-code': 'KZ', + 'alpha-3-code': 'KAZ', + 'continent': 'Азия', + 'name': 'Казахстан', + 'capital': 'Нур-Султан (Астана)'}, + {'timezones': ['Лаос (UTC+07)'], + 'alpha-2-code': 'LA', + 'alpha-3-code': 'LAO', + 'continent': 'Азия', + 'name': 'Лаос', + 'capital': 'Вьентьян'}, + {'timezones': ['Микронезия (UTC+10)', + 'Микронезия (UTC+11)'], + 'alpha-2-code': 'FM', + 'alpha-3-code': 'FSM', + 'continent': 'Океания', + 'name': 'Микронезия', + 'capital': 'Паликир'}, + {'timezones': ['Молдавия (UTC+02)'], + 'alpha-2-code': 'MD', + 'alpha-3-code': 'MDA', + 'continent': 'Европа', + 'name': 'Молдавия', + 'capital': 'Кишинев'}, + {'timezones': ['Монако (UTC+01)'], + 'alpha-2-code': 'MC', + 'alpha-3-code': 'MCO', + 'continent': 'Европа', + 'name': 'Монако', + 'capital': 'Монако'}, + {'timezones': ['Черногория (UTC+01)'], + 'alpha-2-code': 'ME', + 'alpha-3-code': 'MNE', + 'continent': 'Европа', + 'name': 'Черногория', + 'capital': 'Подгорица'}, + {'timezones': ['Марокко (UTC)'], + 'alpha-2-code': 'MA', + 'alpha-3-code': 'MAR', + 'continent': 'Африка', + 'name': 'Марокко', + 'capital': 'Рабат'}, + {'timezones': ['Сент-Китс и Невис (UTC-04)'], + 'alpha-2-code': 'KN', + 'alpha-3-code': 'KNA', + 'continent': 'Северная Америка', + 'name': 'Сент-Китс и Невис', + 'capital': 'Бастер'}, + {'timezones': ['Сент-Люсия (UTC-04)'], + 'alpha-2-code': 'LC', + 'alpha-3-code': 'LCA', + 'continent': 'Северная Америка', + 'name': 'Сент-Люсия', + 'capital': 'Кастри'}, + {'timezones': ['Сент-Винсент и Гренадины (UTC-04)'], + 'alpha-2-code': 'VC', + 'alpha-3-code': 'VCT', + 'continent': 'Северная Америка', + 'name': 'Сент-Винсент и Гренадины', + 'capital': 'Кингстаун'}, + {'timezones': ['Самоа (UTC+13)'], + 'alpha-2-code': 'WS', + 'alpha-3-code': 'WSM', + 'continent': 'Океания', + 'name': 'Самоа', + 'capital': 'Апиа'}, + {'timezones': ['Сербия (UTC+01)'], + 'alpha-2-code': 'RS', + 'alpha-3-code': 'SRB', + 'continent': 'Европа', + 'name': 'Сербия', + 'capital': 'Белград'}, + {'timezones': ['ЮАР (UTC+02)'], + 'alpha-2-code': 'ZA', + 'alpha-3-code': 'ZAF', + 'continent': 'Африка', + 'name': 'ЮАР', + 'capital': 'Претория'}, + {'timezones': ['Испания (UTC)', + 'Испания (UTC+01)'], + 'alpha-2-code': 'ES', + 'alpha-3-code': 'ESP', + 'continent': 'Европа', + 'name': 'Испания', + 'capital': 'Мадрид'}, + {'timezones': ['Шри-Ланка (UTC+05:30)'], + 'alpha-2-code': 'LK', + 'alpha-3-code': 'LKA', + 'continent': 'Азия', + 'name': 'Шри-Ланка', + 'capital': 'Шри-Джаяварденепура-Котте'}, + {'timezones': ['Эсватини (Свазиленд) (UTC+02)'], + 'alpha-2-code': 'SZ', + 'alpha-3-code': 'SWZ', + 'continent': 'Африка', + 'name': 'Эсватини (Свазиленд)', + 'capital': 'Мбабане'}, + {'timezones': ['Швейцария (UTC+01)'], + 'alpha-2-code': 'CH', + 'alpha-3-code': 'CHE', + 'continent': 'Европа', + 'name': 'Швейцария', + 'capital': 'Берн'}, + {'timezones': ['ОАЭ (UTC+04)'], + 'alpha-2-code': 'AE', + 'alpha-3-code': 'ARE', + 'continent': 'Азия', + 'name': 'ОАЭ', + 'capital': 'Абу-Даби'}, + {'timezones': ['Великобритания (UTC)'], + 'alpha-2-code': 'GB', + 'alpha-3-code': 'GBR', + 'continent': 'Европа', + 'name': 'Великобритания', + 'capital': 'Лондон'}, + ] + + def day_of_week(self): + day = self.date('%w') + return self.DAY_NAMES[day] + + def month_name(self): + month = self.month() + return self.MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/sl_SI/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/sl_SI/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ead2972521328d46aead53d64868cf3ad1e6346 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/sl_SI/__init__.py @@ -0,0 +1,35 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + def day_of_week(self): + day = self.date('%w') + DAY_NAMES = { + "0": "Nedelja", + "1": "Ponedeljek", + "2": "Torek", + "3": "Sreda", + "4": "Četrtek", + "5": "Petek", + "6": "Sobota", + } + return DAY_NAMES[day] + + def month_name(self): + month = self.month() + MONTH_NAMES = { + "01": "Januar", + "02": "Februar", + "03": "Marec", + "04": "April", + "05": "Maj", + "06": "Junij", + "07": "Julij", + "08": "Avgust", + "09": "September", + "10": "Oktober", + "11": "November", + "12": "December", + } + return MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/ta_IN/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/ta_IN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..daf61f4a0d7dad23442e3523a340d070b0424170 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/ta_IN/__init__.py @@ -0,0 +1,38 @@ +from .. import Provider as DateTimeProvider + + +class Provider(DateTimeProvider): + + # Source: http://www.localeplanet.com/icu/ta-IN/index.html + DAY_NAMES = { + "0": "திங்கள்", + "1": "செவ்வாய்", + "2": "புதன்", + "3": "வியாழன்", + "4": "வெள்ளி", + "5": "சனி", + "6": "ஞாயிறு", + } + + MONTH_NAMES = { + "01": "ஜனவரி", + "02": "பிப்ரவரி", + "03": "மார்ச்", + "04": "ஏப்ரல்", + "05": "மே", + "06": "ஜூன்", + "07": "ஜூலை", + "08": "ஆகஸ்ட்", + "09": "செப்டம்பர்", + "10": "அக்டோபர்", + "11": "நவம்பர்", + "12": "டிசம்பர்", + } + + def day_of_week(self): + day = self.date('%w') + return self.DAY_NAMES[day] + + def month_name(self): + month = self.month() + return self.MONTH_NAMES[month] diff --git a/testbed/joke2k__faker/faker/providers/date_time/tl_PH/__init__.py b/testbed/joke2k__faker/faker/providers/date_time/tl_PH/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a44dbca4018b5f5fe41336e409a4fd69baab29f6 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/date_time/tl_PH/__init__.py @@ -0,0 +1,6 @@ +from ..fil_PH import Provider as FilPhProvider + + +class Provider(FilPhProvider): + """No difference from DateTime Provider for fil_PH locale""" + pass diff --git a/testbed/joke2k__faker/faker/providers/file/__init__.py b/testbed/joke2k__faker/faker/providers/file/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1279e760eec10b5f0461dfc7a385a672d6334f99 --- /dev/null +++ b/testbed/joke2k__faker/faker/providers/file/__init__.py @@ -0,0 +1,255 @@ +import string + +from collections import OrderedDict + +from .. import BaseProvider + + +class Provider(BaseProvider): + application_mime_types = ( + + "application/atom+xml", # Atom feeds + "application/ecmascript", + # ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to + # application/javascript but with stricter processing rules) + "application/EDI-X12", # EDI X12 data; Defined in RFC 1767 + "application/EDIFACT", # EDI EDIFACT data; Defined in RFC 1767 + "application/json", # JavaScript Object Notation JSON; Defined in RFC 4627 + # ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to + # application/ecmascript + "application/javascript", + # but with looser processing rules) It is not accepted in IE 8 + # or earlier - text/javascript is accepted but it is defined as obsolete in RFC 4329. + # The "type" attribute of the + + + + + + + + + + + diff --git a/testbed/lark-parser__lark/docs/ide/app.js b/testbed/lark-parser__lark/docs/ide/app.js new file mode 100644 index 0000000000000000000000000000000000000000..90e54f13d003920718b440dc3e18b9a93c31afcd --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app.js @@ -0,0 +1,105 @@ +class app { + + constructor(modules, invocation){ + languagePluginLoader.then(() => { + // If you don't require for pre-loaded Python packages, remove this promise below. + window.pyodide.runPythonAsync("import setuptools, micropip").then(()=>{ + window.pyodide.runPythonAsync("micropip.install('lark-parser')").then(()=>{ + this.fetchSources(modules).then(() => { + window.pyodide.runPythonAsync("import " + Object.keys(modules).join("\nimport ") + "\n" + invocation + "\n").then(() => this.initializingComplete()); + }); + }); + }); + }); + } + + loadSources(module, baseURL, files) { + let promises = []; + + for (let f in files) { + promises.push( + new Promise((resolve, reject) => { + let file = files[f]; + let url = (baseURL ? baseURL + "/" : "") + file; + + fetch(url, {}).then((response) => { + if (response.status === 200) + return response.text().then((code) => { + let path = ("/lib/python3.7/site-packages/" + module + "/" + file).split("/"); + let lookup = ""; + + for (let i in path) { + if (!path[i]) { + continue; + } + + lookup += (lookup ? "/" : "") + path[i]; + + if (parseInt(i) === path.length - 1) { + window.pyodide._module.FS.writeFile(lookup, code); + console.debug(`fetched ${lookup}`); + } else { + try { + window.pyodide._module.FS.lookupPath(lookup); + } catch { + window.pyodide._module.FS.mkdir(lookup); + console.debug(`created ${lookup}`); + } + } + } + + resolve(); + }); + else + reject(); + }); + }) + ); + } + + return Promise.all(promises); + } + + fetchSources(modules) { + let promises = []; + + for( let module of Object.keys(modules) ) + { + promises.push( + new Promise((resolve, reject) => { + fetch(`${modules[module]}/files.json`, {}).then((response) => { + if (response.status === 200) { + response.text().then((list) => { + let files = JSON.parse(list); + + this.loadSources(module, modules[module], files).then(() => { + resolve(); + }) + }) + } else { + reject(); + } + }) + })); + } + + return Promise.all(promises).then(() => { + for( let module of Object.keys(modules) ) { + window.pyodide.loadedPackages[module] = "default channel"; + } + + window.pyodide.runPython( + 'import importlib as _importlib\n' + + '_importlib.invalidate_caches()\n' + ); + }); + } + + initializingComplete() { + document.body.classList.remove("is-loading") + } +} + +(function () { + window.top.app = new app({"app": "app"}, "import app.app; app.app.start()"); +})(); diff --git a/testbed/lark-parser__lark/docs/ide/app/app.py b/testbed/lark-parser__lark/docs/ide/app/app.py new file mode 100644 index 0000000000000000000000000000000000000000..146aee988fcc6e29cd6dcb4d49ea3095b98515dd --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/app.py @@ -0,0 +1,83 @@ +from . import html5 +from .examples import examples + +from lark import Lark +from lark.tree import Tree + + +class App(html5.Div): + def __init__(self): + super().__init__(""" +

+ IDE +

+ +
+ + + + +
+
+
Grammar:
+ +
+
+
Input:
+ +
+
+
+
    +
+
+ """) + self.sinkEvent("onKeyUp", "onChange") + + self.parser = "earley" + + # Pre-load examples + for name, (grammar, input) in examples.items(): + option = html5.Option(name) + option.grammar = grammar + option.input = input + + self.examples.appendChild(option) + + def onChange(self, e): + if html5.utils.doesEventHitWidgetOrChildren(e, self.examples): + example = self.examples.children(self.examples["selectedIndex"]) + self.grammar["value"] = example.grammar.strip() + self.input["value"] = example.input.strip() + self.onKeyUp() + + elif html5.utils.doesEventHitWidgetOrChildren(e, self.parser): + self.parser = self.parser.children(self.parser["selectedIndex"])["value"] + self.onKeyUp() + + def onKeyUp(self, e=None): + l = Lark(self.grammar["value"], parser=self.parser) + + try: + ast = l.parse(self.input["value"]) + except Exception as e: + self.ast.appendChild( + html5.Li(str(e)), replace=True + ) + + print(ast) + traverse = lambda node: html5.Li([node.data, html5.Ul([traverse(c) for c in node.children])] if isinstance(node, Tree) else node) + self.ast.appendChild(traverse(ast), replace=True) + + +def start(): + html5.Body().appendChild( + App() + ) + diff --git a/testbed/lark-parser__lark/docs/ide/app/core.py b/testbed/lark-parser__lark/docs/ide/app/core.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebe6791ebdd8fbec0f92d4f58ba9daa689fb02a --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/core.py @@ -0,0 +1,3152 @@ +# -*- coding: utf-8 -* + +######################################################################################################################## +# DOM-access functions and variables +######################################################################################################################## + +try: + # Pyodide + from js import window, eval as jseval + document = window.document + +except: + print("Emulation mode") + from xml.dom.minidom import parseString + + jseval = None + window = None + document = parseString("") + + +def domCreateAttribute(tag, ns=None): + """ + Creates a new HTML/SVG/... attribute + :param ns: the namespace. Default: HTML. Possible values: HTML, SVG, XBL, XUL + """ + uri = None + + if ns == "SVG": + uri = "http://www.w3.org/2000/svg" + elif ns == "XBL": + uri = "http://www.mozilla.org/xbl" + elif ns == "XUL": + uri = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" + + if uri: + return document.createAttribute(uri, tag) + + return document.createAttribute(tag) + + +def domCreateElement(tag, ns=None): + """ + Creates a new HTML/SVG/... tag + :param ns: the namespace. Default: HTML. Possible values: HTML, SVG, XBL, XUL + """ + uri = None + + if ns == "SVG": + uri = "http://www.w3.org/2000/svg" + elif ns == "XBL": + uri = "http://www.mozilla.org/xbl" + elif ns == "XUL": + uri = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" + + if uri: + return document.createElementNS(uri, tag) + + return document.createElement(tag) + + +def domCreateTextNode(txt=""): + return document.createTextNode(txt) + + +def domGetElementById(idTag): + return document.getElementById(idTag) + + +def domElementFromPoint(x, y): + return document.elementFromPoint(x, y) + + +def domGetElementsByTagName(tag): + items = document.getElementsByTagName(tag) + return [items.item(i) for i in range(0, int(items.length))] #pyodide interprets items.length as float, so convert to int + + +######################################################################################################################## +# HTML Widgets +######################################################################################################################## + +# TextNode ------------------------------------------------------------------------------------------------------------- + +class TextNode(object): + """ + Represents a piece of text inside the DOM. + This is the *only* object not deriving from "Widget", as it does + not support any of its properties. + """ + + def __init__(self, txt=None, *args, **kwargs): + super().__init__() + self._parent = None + self._children = [] + self.element = domCreateTextNode(txt or "") + self._isAttached = False + + def _setText(self, txt): + self.element.data = txt + + def _getText(self): + return self.element.data + + def __str__(self): + return self.element.data + + def onAttach(self): + self._isAttached = True + + def onDetach(self): + self._isAttached = False + + def _setDisabled(self, disabled): + return + + def _getDisabled(self): + return False + + def children(self): + return [] + + +# _WidgetClassWrapper ------------------------------------------------------------------------------------------------- + +class _WidgetClassWrapper(list): + + def __init__(self, targetWidget): + super().__init__() + + self.targetWidget = targetWidget + + def _updateElem(self): + if len(self) == 0: + self.targetWidget.element.removeAttribute("class") + else: + self.targetWidget.element.setAttribute("class", " ".join(self)) + + def append(self, p_object): + list.append(self, p_object) + self._updateElem() + + def clear(self): + list.clear(self) + self._updateElem() + + def remove(self, value): + try: + list.remove(self, value) + except: + pass + self._updateElem() + + def extend(self, iterable): + list.extend(self, iterable) + self._updateElem() + + def insert(self, index, p_object): + list.insert(self, index, p_object) + self._updateElem() + + def pop(self, index=None): + list.pop(self, index) + self._updateElem() + + +# _WidgetDataWrapper --------------------------------------------------------------------------------------------------- + +class _WidgetDataWrapper(dict): + + def __init__(self, targetWidget): + super().__init__() + + self.targetWidget = targetWidget + alldata = targetWidget.element + + for data in dir(alldata.dataset): + dict.__setitem__(self, data, getattr(alldata.dataset, data)) + + def __setitem__(self, key, value): + dict.__setitem__(self, key, value) + self.targetWidget.element.setAttribute(str("data-" + key), value) + + def update(self, E=None, **F): + dict.update(self, E, **F) + if E is not None and "keys" in dir(E): + for key in E: + self.targetWidget.element.setAttribute(str("data-" + key), E["data-" + key]) + elif E: + for (key, val) in E: + self.targetWidget.element.setAttribute(str("data-" + key), "data-" + val) + for key in F: + self.targetWidget.element.setAttribute(str("data-" + key), F["data-" + key]) + + +# _WidgetStyleWrapper -------------------------------------------------------------------------------------------------- + +class _WidgetStyleWrapper(dict): + + def __init__(self, targetWidget): + super().__init__() + + self.targetWidget = targetWidget + style = targetWidget.element.style + + for key in dir(style): + # Convert JS-Style-Syntax to CSS Syntax (ie borderTop -> border-top) + realKey = "" + for currChar in key: + if currChar.isupper(): + realKey += "-" + realKey += currChar.lower() + val = style.getPropertyValue(realKey) + if val: + dict.__setitem__(self, realKey, val) + + def __setitem__(self, key, value): + dict.__setitem__(self, key, value) + self.targetWidget.element.style.setProperty(key, value) + + def update(self, E=None, **F): + dict.update(self, E, **F) + if E is not None and "keys" in dir(E): + for key in E: + self.targetWidget.element.style.setProperty(key, E[key]) + elif E: + for (key, val) in E: + self.targetWidget.element.style.setProperty(key, val) + for key in F: + self.targetWidget.element.style.setProperty(key, F[key]) + + +# Widget --------------------------------------------------------------------------------------------------------------- + +class Widget(object): + _tagName = None + _namespace = None + _parserTagName = None + style = [] + + def __init__(self, *args, appendTo=None, style=None, **kwargs): + if "_wrapElem" in kwargs.keys(): + self.element = kwargs["_wrapElem"] + del kwargs["_wrapElem"] + else: + assert self._tagName is not None + self.element = domCreateElement(self._tagName, ns=self._namespace) + + super().__init__() + self._widgetClassWrapper = _WidgetClassWrapper(self) + self.addClass(self.style) + + if style: + self.addClass(style) + + self._children = [] + self._catchedEvents = {} + self._disabledState = 0 + self._isAttached = False + self._parent = None + + self._lastDisplayState = None + + if args: + self.appendChild(*args, **kwargs) + + if appendTo: + appendTo.appendChild(self) + + def sinkEvent(self, *args): + for event_attrName in args: + event = event_attrName.lower() + + if event_attrName in self._catchedEvents or event in ["onattach", "ondetach"]: + continue + + eventFn = getattr(self, event_attrName, None) + assert eventFn and callable(eventFn), "{} must provide a {} method".format(str(self), event_attrName) + + self._catchedEvents[event_attrName] = eventFn + + if event.startswith("on"): + event = event[2:] + + self.element.addEventListener(event, eventFn) + + def unsinkEvent(self, *args): + for event_attrName in args: + event = event_attrName.lower() + + if event_attrName not in self._catchedEvents: + continue + + eventFn = self._catchedEvents[event_attrName] + del self._catchedEvents[event_attrName] + + if event.startswith("on"): + event = event[2:] + + self.element.removeEventListener(event, eventFn) + + def disable(self): + if not self["disabled"]: + self["disabled"] = True + + def enable(self): + if self["disabled"]: + self["disabled"] = False + + def _getDisabled(self): + return bool(self._disabledState) + + def _setDisabled(self, disable): + for child in self._children: + child._setDisabled(disable) + + if disable: + self._disabledState += 1 + self.addClass("is-disabled") + + if isinstance(self, _attrDisabled): + self.element.disabled = True + + elif self._disabledState: + self._disabledState -= 1 + + if not self._disabledState: + self.removeClass("is-disabled") + + if isinstance(self, _attrDisabled): + self.element.disabled = False + + def _getTargetfuncName(self, key, type): + assert type in ["get", "set"] + return "_{}{}{}".format(type, key[0].upper(), key[1:]) + + def __getitem__(self, key): + funcName = self._getTargetfuncName(key, "get") + + if funcName in dir(self): + return getattr(self, funcName)() + + return None + + def __setitem__(self, key, value): + funcName = self._getTargetfuncName(key, "set") + + if funcName in dir(self): + return getattr(self, funcName)(value) + + raise ValueError("{} is no valid attribute for {}".format(key, (self._tagName or str(self)))) + + def __str__(self): + return str(self.__class__.__name__) + + def __iter__(self): + return self._children.__iter__() + + def _getData(self): + """ + Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements. + :param name: + :returns: + """ + return _WidgetDataWrapper(self) + + def _getTranslate(self): + """ + Specifies whether an elements attribute values and contents of its children are to be translated when the page is localized, or whether to leave them unchanged. + :returns: True | False + """ + return True if self.element.translate == "yes" else False + + def _setTranslate(self, val): + """ + Specifies whether an elements attribute values and contents of its children are to be translated when the page is localized, or whether to leave them unchanged. + :param val: True | False + """ + self.element.translate = "yes" if val == True else "no" + + def _getTitle(self): + """ + Advisory information associated with the element. + :returns: str + """ + return self.element.title + + def _setTitle(self, val): + """ + Advisory information associated with the element. + :param val: str + """ + self.element.title = val + + def _getTabindex(self): + """ + Specifies whether the element represents an element that is is focusable (that is, an element which is part of the sequence of focusable elements in the document), and the relative order of the element in the sequence of focusable elements in the document. + :returns: number + """ + return self.element.getAttribute("tabindex") + + def _setTabindex(self, val): + """ + Specifies whether the element represents an element that is is focusable (that is, an element which is part of the sequence of focusable elements in the document), and the relative order of the element in the sequence of focusable elements in the document. + :param val: number + """ + self.element.setAttribute("tabindex", val) + + def _getSpellcheck(self): + """ + Specifies whether the element represents an element whose contents are subject to spell checking and grammar checking. + :returns: True | False + """ + return True if self.element.spellcheck == "true" else False + + def _setSpellcheck(self, val): + """ + Specifies whether the element represents an element whose contents are subject to spell checking and grammar checking. + :param val: True | False + """ + self.element.spellcheck = str(val).lower() + + def _getLang(self): + """ + Specifies the primary language for the contents of the element and for any of the elements attributes that contain text. + :returns: language tag e.g. de|en|fr|es|it|ru| + """ + return self.element.lang + + def _setLang(self, val): + """ + Specifies the primary language for the contents of the element and for any of the elements attributes that contain text. + :param val: language tag + """ + self.element.lang = val + + def _getHidden(self): + """ + Specifies that the element represents an element that is not yet, or is no longer, relevant. + :returns: True | False + """ + return True if self.element.hasAttribute("hidden") else False + + def _setHidden(self, val): + """ + Specifies that the element represents an element that is not yet, or is no longer, relevant. + :param val: True | False + """ + if val: + self.element.setAttribute("hidden", "") + else: + self.element.removeAttribute("hidden") + + def _getDropzone(self): + """ + Specifies what types of content can be dropped on the element, and instructs the UA about which actions to take with content when it is dropped on the element. + :returns: "copy" | "move" | "link" + """ + return self.element.dropzone + + def _setDropzone(self, val): + """ + Specifies what types of content can be dropped on the element, and instructs the UA about which actions to take with content when it is dropped on the element. + :param val: "copy" | "move" | "link" + """ + self.element.dropzone = val + + def _getDraggable(self): + """ + Specifies whether the element is draggable. + :returns: True | False | "auto" + """ + return (self.element.draggable if str(self.element.draggable) == "auto" else ( + True if str(self.element.draggable).lower() == "true" else False)) + + def _setDraggable(self, val): + """ + Specifies whether the element is draggable. + :param val: True | False | "auto" + """ + self.element.draggable = str(val).lower() + + def _getDir(self): + """ + Specifies the elements text directionality. + :returns: ltr | rtl | auto + """ + return self.element.dir + + def _setDir(self, val): + """ + Specifies the elements text directionality. + :param val: ltr | rtl | auto + """ + self.element.dir = val + + def _getContextmenu(self): + """ + The value of the id attribute on the menu with which to associate the element as a context menu. + :returns: + """ + return self.element.contextmenu + + def _setContextmenu(self, val): + """ + The value of the id attribute on the menu with which to associate the element as a context menu. + :param val: + """ + self.element.contextmenu = val + + def _getContenteditable(self): + """ + Specifies whether the contents of the element are editable. + :returns: True | False + """ + v = self.element.getAttribute("contenteditable") + return str(v).lower() == "true" + + def _setContenteditable(self, val): + """ + Specifies whether the contents of the element are editable. + :param val: True | False + """ + self.element.setAttribute("contenteditable", str(val).lower()) + + def _getAccesskey(self): + """ + A key label or list of key labels with which to associate the element; each key label represents a keyboard shortcut which UAs can use to activate the element or give focus to the element. + :param self: + :returns: + """ + return self.element.accesskey + + def _setAccesskey(self, val): + """ + A key label or list of key labels with which to associate the element; each key label represents a keyboard shortcut which UAs can use to activate the element or give focus to the element. + :param self: + :param val: + """ + self.element.accesskey = val + + def _getId(self): + """ + Specifies a unique id for an element + :param self: + :returns: + """ + return self.element.id + + def _setId(self, val): + """ + Specifies a unique id for an element + :param self: + :param val: + """ + self.element.id = val + + def _getClass(self): + """ + The class attribute specifies one or more classnames for an element. + :returns: + """ + return self._widgetClassWrapper + + def _setClass(self, value): + """ + The class attribute specifies one or more classnames for an element. + :param self: + :param value: + @raise ValueError: + """ + + if value is None: + self.element.setAttribute("class", " ") + elif isinstance(value, str): + self.element.setAttribute("class", value) + elif isinstance(value, list): + self.element.setAttribute("class", " ".join(value)) + else: + raise ValueError("Class must be a str, a List or None") + + def _getStyle(self): + """ + The style attribute specifies an inline style for an element. + :param self: + :returns: + """ + return _WidgetStyleWrapper(self) + + def _getRole(self): + """ + Specifies a role for an element + @param self: + @return: + """ + return self.element.getAttribute("role") + + def _setRole(self, val): + """ + Specifies a role for an element + @param self: + @param val: + """ + self.element.setAttribute("role", val) + + def hide(self): + """ + Hide element, if shown. + :return: + """ + state = self["style"].get("display", "") + + if state != "none": + self._lastDisplayState = state + self["style"]["display"] = "none" + + def show(self): + """ + Show element, if hidden. + :return: + """ + if self._lastDisplayState is not None: + self["style"]["display"] = self._lastDisplayState + self._lastDisplayState = None + + def isHidden(self): + """ + Checks if a widget is hidden. + :return: True if hidden, False otherwise. + """ + return self["style"].get("display", "") == "none" + + def isVisible(self): + """ + Checks if a widget is visible. + :return: True if visible, False otherwise. + """ + return not self.isHidden() + + def onBind(self, widget, name): + """ + Event function that is called on the widget when it is bound to another widget with a name. + This is only done by the HTML parser, a manual binding by the user is not triggered. + """ + return + + def onAttach(self): + self._isAttached = True + + for c in self._children: + c.onAttach() + + def onDetach(self): + self._isAttached = False + for c in self._children: + c.onDetach() + + def __collectChildren(self, *args, **kwargs): + assert not isinstance(self, _isVoid), "<%s> can't have children!" % self._tagName + + if kwargs.get("bindTo") is None: + kwargs["bindTo"] = self + + widgets = [] + for arg in args: + if isinstance(arg, (str, HtmlAst)): + widgets.extend(fromHTML(arg, **kwargs)) + + elif isinstance(arg, (list, tuple)): + for subarg in arg: + widgets.extend(self.__collectChildren(subarg, **kwargs)) + + elif not isinstance(arg, (Widget, TextNode)): + widgets.append(TextNode(str(arg))) + + else: + widgets.append(arg) + + return widgets + + def insertBefore(self, insert, child, **kwargs): + if not child: + return self.appendChild(insert) + + assert child in self._children, "{} is not a child of {}".format(child, self) + + toInsert = self.__collectChildren(insert, **kwargs) + + for insert in toInsert: + if insert._parent: + insert._parent.removeChild(insert) + + self.element.insertBefore(insert.element, child.element) + self._children.insert(self._children.index(child), insert) + + insert._parent = self + if self._isAttached: + insert.onAttach() + + return toInsert + + def prependChild(self, *args, **kwargs): + if kwargs.get("replace", False): + self.removeAllChildren() + del kwargs["replace"] + + toPrepend = self.__collectChildren(*args, **kwargs) + + for child in toPrepend: + if child._parent: + child._parent._children.remove(child) + child._parent = None + + if not self._children: + self.appendChild(child) + else: + self.insertBefore(child, self.children(0)) + + return toPrepend + + def appendChild(self, *args, **kwargs): + if kwargs.get("replace", False): + self.removeAllChildren() + del kwargs["replace"] + + toAppend = self.__collectChildren(*args, **kwargs) + + for child in toAppend: + if child._parent: + child._parent._children.remove(child) + + self._children.append(child) + self.element.appendChild(child.element) + child._parent = self + + if self._isAttached: + child.onAttach() + + return toAppend + + def removeChild(self, child): + assert child in self._children, "{} is not a child of {}".format(child, self) + + if child._isAttached: + child.onDetach() + + self.element.removeChild(child.element) + self._children.remove(child) + child._parent = None + + def removeAllChildren(self): + """ + Removes all child widgets of the current widget. + """ + for child in self._children[:]: + self.removeChild(child) + + def isParentOf(self, widget): + """ + Checks if an object is the parent of widget. + + :type widget: Widget + :param widget: The widget to check for. + :return: True, if widget is a child of the object, else False. + """ + + # You cannot be your own child! + if self == widget: + return False + + for child in self._children: + if child == widget: + return True + + if child.isParentOf(widget): + return True + + return False + + def isChildOf(self, widget): + """ + Checks if an object is the child of widget. + + :type widget: Widget + :param widget: The widget to check for. + :return: True, if object is a child of widget, else False. + """ + + # You cannot be your own parent! + if self == widget: + return False + + parent = self.parent() + while parent: + if parent == widget: + return True + + parent = widget.parent() + + return False + + def hasClass(self, className): + """ + Determine whether the current widget is assigned the given class + + :param className: The class name to search for. + :type className: str + """ + + if isinstance(className, str) or isinstance(className, unicode): + return className in self["class"] + else: + raise TypeError() + + def addClass(self, *args): + """ + Adds a class or a list of classes to the current widget. + If the widget already has the class, it is ignored. + + :param args: A list of class names. This can also be a list. + :type args: list of str | list of list of str + """ + + for item in args: + if isinstance(item, list): + self.addClass(*item) + + elif isinstance(item, str): + for sitem in item.split(" "): + if not self.hasClass(sitem): + self["class"].append(sitem) + else: + raise TypeError() + + def removeClass(self, *args): + """ + Removes a class or a list of classes from the current widget. + + :param args: A list of class names. This can also be a list. + :type args: list of str | list of list of str + """ + + for item in args: + if isinstance(item, list): + self.removeClass(item) + + elif isinstance(item, str): + for sitem in item.split(" "): + if self.hasClass(sitem): + self["class"].remove(sitem) + else: + raise TypeError() + + def toggleClass(self, on, off=None): + """ + Toggles the class ``on``. + + If the widget contains a class ``on``, it is toggled by ``off``. + ``off`` can either be a class name that is substituted, or nothing. + + :param on: Classname to test for. If ``on`` does not exist, but ``off``, ``off`` is replaced by ``on``. + :type on: str + + :param off: Classname to replace if ``on`` existed. + :type off: str + + :return: Returns True, if ``on`` was switched, else False. + :rtype: bool + """ + if self.hasClass(on): + self.removeClass(on) + + if off and not self.hasClass(off): + self.addClass(off) + + return False + + if off and self.hasClass(off): + self.removeClass(off) + + self.addClass(on) + return True + + def onBlur(self, event): + pass + + def onChange(self, event): + pass + + def onContextMenu(self, event): + pass + + def onFocus(self, event): + pass + + def onFocusIn(self, event): + pass + + def onFocusOut(self, event): + pass + + def onFormChange(self, event): + pass + + def onFormInput(self, event): + pass + + def onInput(self, event): + pass + + def onInvalid(self, event): + pass + + def onReset(self, event): + pass + + def onSelect(self, event): + pass + + def onSubmit(self, event): + pass + + def onKeyDown(self, event): + pass + + def onKeyPress(self, event): + pass + + def onKeyUp(self, event): + pass + + def onClick(self, event): + pass + + def onDblClick(self, event): + pass + + def onDrag(self, event): + pass + + def onDragEnd(self, event): + pass + + def onDragEnter(self, event): + pass + + def onDragLeave(self, event): + pass + + def onDragOver(self, event): + pass + + def onDragStart(self, event): + pass + + def onDrop(self, event): + pass + + def onMouseDown(self, event): + pass + + def onMouseMove(self, event): + pass + + def onMouseOut(self, event): + pass + + def onMouseOver(self, event): + pass + + def onMouseUp(self, event): + pass + + def onMouseWheel(self, event): + pass + + def onScroll(self, event): + pass + + def onTouchStart(self, event): + pass + + def onTouchEnd(self, event): + pass + + def onTouchMove(self, event): + pass + + def onTouchCancel(self, event): + pass + + def focus(self): + self.element.focus() + + def blur(self): + self.element.blur() + + def parent(self): + return self._parent + + def children(self, n=None): + """ + Access children of widget. + + If ``n`` is ommitted, it returns a list of all child-widgets; + Else, it returns the N'th child, or None if its out of bounds. + + :param n: Optional offset of child widget to return. + :type n: int + + :return: Returns all children or only the requested one. + :rtype: list | Widget | None + """ + if n is None: + return self._children[:] + + try: + return self._children[n] + except IndexError: + return None + + def sortChildren(self, key): + """ + Sorts our direct children. They are rearranged on DOM level. + Key must be a function accepting one widget as parameter and must return + the key used to sort these widgets. + """ + self._children.sort(key=key) + tmpl = self._children[:] + tmpl.reverse() + for c in tmpl: + self.element.removeChild(c.element) + self.element.insertBefore(c.element, self.element.children.item(0)) + + def fromHTML(self, html, appendTo=None, bindTo=None, replace=False, vars=None, **kwargs): + """ + Parses html and constructs its elements as part of self. + + :param html: HTML code. + :param appendTo: The entity where the HTML code is constructed below. This defaults to self in usual case. + :param bindTo: The entity where the named objects are bound to. This defaults to self in usual case. + :param replace: Clear entire content of appendTo before appending. + :param vars: Deprecated; Same as kwargs. + :param **kwargs: Additional variables provided as a dict for {{placeholders}} inside the HTML + + :return: + """ + if appendTo is None: + appendTo = self + + if bindTo is None: + bindTo = self + + if replace: + appendTo.removeAllChildren() + + # use of vars is deprecated! + if isinstance(vars, dict): + kwargs.update(vars) + + return fromHTML(html, appendTo=appendTo, bindTo=bindTo, **kwargs) + + +######################################################################################################################## +# Attribute Collectors +######################################################################################################################## + +# _attrLabel --------------------------------------------------------------------------------------------------------------- + +class _attrLabel(object): + def _getLabel(self): + return self.element.getAttribute("label") + + def _setLabel(self, val): + self.element.setAttribute("label", val) + + +# _attrCharset -------------------------------------------------------------------------------------------------------------- + +class _attrCharset(object): + def _getCharset(self): + return self.element._attrCharset + + def _setCharset(self, val): + self.element._attrCharset = val + + +# _attrCite ----------------------------------------------------------------------------------------------------------------- + +class _attrCite(object): + def _getCite(self): + return self.element._attrCite + + def _setCite(self, val): + self.element._attrCite = val + + +class _attrDatetime(object): + def _getDatetime(self): + return self.element.datetime + + def _setDatetime(self, val): + self.element.datetime = val + + +# Form ----------------------------------------------------------------------------------------------------------------- + +class _attrForm(object): + def _getForm(self): + return self.element.form + + def _setForm(self, val): + self.element.form = val + + +class _attrAlt(object): + def _getAlt(self): + return self.element.alt + + def _setAlt(self, val): + self.element.alt = val + + +class _attrAutofocus(object): + def _getAutofocus(self): + return True if self.element.hasAttribute("autofocus") else False + + def _setAutofocus(self, val): + if val: + self.element.setAttribute("autofocus", "") + else: + self.element.removeAttribute("autofocus") + + +class _attrDisabled(object): + pass + + +class _attrChecked(object): + def _getChecked(self): + return self.element.checked + + def _setChecked(self, val): + self.element.checked = val + + +class _attrIndeterminate(object): + def _getIndeterminate(self): + return self.element.indeterminate + + def _setIndeterminate(self, val): + self.element.indeterminate = val + + +class _attrName(object): + def _getName(self): + return self.element.getAttribute("name") + + def _setName(self, val): + self.element.setAttribute("name", val) + + +class _attrValue(object): + def _getValue(self): + return self.element.value + + def _setValue(self, val): + self.element.value = val + + +class _attrAutocomplete(object): + def _getAutocomplete(self): + return True if self.element.autocomplete == "on" else False + + def _setAutocomplete(self, val): + self.element.autocomplete = "on" if val == True else "off" + + +class _attrRequired(object): + def _getRequired(self): + return True if self.element.hasAttribute("required") else False + + def _setRequired(self, val): + if val: + self.element.setAttribute("required", "") + else: + self.element.removeAttribute("required") + + +class _attrMultiple(object): + def _getMultiple(self): + return True if self.element.hasAttribute("multiple") else False + + def _setMultiple(self, val): + if val: + self.element.setAttribute("multiple", "") + else: + self.element.removeAttribute("multiple") + + +class _attrSize(object): + def _getSize(self): + return self.element.size + + def _setSize(self, val): + self.element.size = val + + +class _attrFor(object): + def _getFor(self): + return self.element.getAttribute("for") + + def _setFor(self, val): + self.element.setAttribute("for", val) + + +class _attrInputs(_attrRequired): + def _getMaxlength(self): + return self.element.maxlength + + def _setMaxlength(self, val): + self.element.maxlength = val + + def _getPlaceholder(self): + return self.element.placeholder + + def _setPlaceholder(self, val): + self.element.placeholder = val + + def _getReadonly(self): + return True if self.element.hasAttribute("readonly") else False + + def _setReadonly(self, val): + if val: + self.element.setAttribute("readonly", "") + else: + self.element.removeAttribute("readonly") + + +class _attrFormhead(object): + def _getFormaction(self): + return self.element.formaction + + def _setFormaction(self, val): + self.element.formaction = val + + def _getFormenctype(self): + return self.element.formenctype + + def _setFormenctype(self, val): + self.element.formenctype = val + + def _getFormmethod(self): + return self.element.formmethod + + def _setFormmethod(self, val): + self.element.formmethod = val + + def _getFormtarget(self): + return self.element.formtarget + + def _setFormtarget(self, val): + self.element.formtarget = val + + def _getFormnovalidate(self): + return True if self.element.hasAttribute("formnovalidate") else False + + def _setFormnovalidate(self, val): + if val: + self.element.setAttribute("formnovalidate", "") + else: + self.element.removeAttribute("formnovalidate") + + +# _attrHref ----------------------------------------------------------------------------------------------------------------- + +class _attrHref(object): + def _getHref(self): + """ + Url of a Page + :param self: + """ + return self.element.href + + def _setHref(self, val): + """ + Url of a Page + :param val: URL + """ + self.element.href = val + + def _getHreflang(self): + return self.element.hreflang + + def _setHreflang(self, val): + self.element.hreflang = val + + +class _attrTarget(object): + def _getTarget(self): + return self.element.target + + def _setTarget(self, val): + self.element.target = val + + +# _attrMedia ---------------------------------------------------------------------------------------------------------------- + +class _attrType(object): + def _getType(self): + return self.element.type + + def _setType(self, val): + self.element.type = val + + +class _attrMedia(_attrType): + def _getMedia(self): + return self.element.media + + def _setMedia(self, val): + self.element.media = val + + +class _attrDimensions(object): + def _getWidth(self): + return self.element.width + + def _setWidth(self, val): + self.element.width = val + + def _getHeight(self): + return self.element.height + + def _setHeight(self, val): + self.element.height = val + + +class _attrUsemap(object): + def _getUsemap(self): + return self.element.usemap + + def _setUsemap(self, val): + self.element.usemap = val + + +class _attrMultimedia(object): + def _getAutoplay(self): + return True if self.element.hasAttribute("autoplay") else False + + def _setAutoplay(self, val): + if val: + self.element.setAttribute("autoplay", "") + else: + self.element.removeAttribute("autoplay") + + def _getPlaysinline(self): + return True if self.element.hasAttribute("playsinline") else False + + def _setPlaysinline(self, val): + if val: + self.element.setAttribute("playsinline", "") + else: + self.element.removeAttribute("playsinline") + + def _getControls(self): + return True if self.element.hasAttribute("controls") else False + + def _setControls(self, val): + if val: + self.element.setAttribute("controls", "") + else: + self.element.removeAttribute("controls") + + def _getLoop(self): + return True if self.element.hasAttribute("loop") else False + + def _setLoop(self, val): + if val: + self.element.setAttribute("loop", "") + else: + self.element.removeAttribute("loop") + + def _getMuted(self): + return True if self.element.hasAttribute("muted") else False + + def _setMuted(self, val): + if val: + self.element.setAttribute("muted", "") + else: + self.element.removeAttribute("muted") + + def _getPreload(self): + return self.element.preload + + def _setPreload(self, val): + self.element.preload = val + + +# _attrRel ------------------------------------------------------------------------------------------------------------------ + +class _attrRel(object): + def _getRel(self): + return self.element.rel + + def _setRel(self, val): + self.element.rel = val + + +# _attrSrc ------------------------------------------------------------------------------------------------------------------ + +class _attrSrc(object): + def _getSrc(self): + return self.element.src + + def _setSrc(self, val): + self.element.src = val + + +# Svg ------------------------------------------------------------------------------------------------------------------ + +class _attrSvgViewBox(object): + def _getViewbox(self): + viewBox = self.element.viewBox + try: + return " ".join([str(x) for x in [viewBox.baseVal.x, viewBox.baseVal.y, viewBox.baseVal.width, viewBox.baseVal.height]]) + except: + return "" + + def _setViewbox(self, val): + self.element.setAttribute("viewBox", val) + + def _getPreserveaspectratio(self): + return self.element.preserveAspectRatio + + def _setPreserveaspectratio(self, val): + self.element.setAttribute("preserveAspectRatio", val) + + +class _attrSvgDimensions(object): + def _getWidth(self): + return self.element.width + + def _setWidth(self, val): + self.element.setAttribute("width", val) + + def _getHeight(self): + return self.element.height + + def _setHeight(self, val): + self.element.setAttribute("height", val) + + def _getX(self): + return self.element.x + + def _setX(self, val): + self.element.setAttribute("x", val) + + def _getY(self): + return self.element.y + + def _setY(self, val): + self.element.setAttribute("y", val) + + def _getR(self): + return self.element.r + + def _setR(self, val): + self.element.setAttribute("r", val) + + def _getRx(self): + return self.element.rx + + def _setRx(self, val): + self.element.setAttribute("rx", val) + + def _getRy(self): + return self.element.ry + + def _setRy(self, val): + self.element.setAttribute("ry", val) + + def _getCx(self): + return self.element.cx + + def _setCx(self, val): + self.element.setAttribute("cx", val) + + def _getCy(self): + return self.element.cy + + def _setCy(self, val): + self.element.setAttribute("cy", val) + + +class _attrSvgPoints(object): + def _getPoints(self): + return self.element.points + + def _setPoints(self, val): + self.element.setAttribute("points", val) + + def _getX1(self): + return self.element.x1 + + def _setX1(self, val): + self.element.setAttribute("x1", val) + + def _getY1(self): + return self.element.y1 + + def _setY1(self, val): + self.element.setAttribute("y1", val) + + def _getX2(self): + return self.element.x2 + + def _setX2(self, val): + self.element.setAttribute("x2", val) + + def _getY2(self): + return self.element.y2 + + def _setY2(self, val): + self.element.setAttribute("y2", val) + + +class _attrSvgTransform(object): + def _getTransform(self): + return self.element.transform + + def _setTransform(self, val): + self.element.setAttribute("transform", val) + + +class _attrSvgXlink(object): + def _getXlinkhref(self): + return self.element.getAttribute("xlink:href") + + def _setXlinkhref(self, val): + self.element.setAttribute("xlink:href", val) + + +class _attrSvgStyles(object): + def _getFill(self): + return self.element.fill + + def _setFill(self, val): + self.element.setAttribute("fill", val) + + def _getStroke(self): + return self.element.stroke + + def _setStroke(self, val): + self.element.setAttribute("stroke", val) + + +class _isVoid(object): + pass + + +######################################################################################################################## +# HTML Elements +######################################################################################################################## + +# A -------------------------------------------------------------------------------------------------------------------- + +class A(Widget, _attrHref, _attrTarget, _attrMedia, _attrRel, _attrName): + _tagName = "a" + + def _getDownload(self): + """ + The download attribute specifies the path to a download + :returns: filename + """ + return self.element.download + + def _setDownload(self, val): + """ + The download attribute specifies the path to a download + :param val: filename + """ + self.element.download = val + + +# Area ----------------------------------------------------------------------------------------------------------------- + +class Area(A, _attrAlt, _isVoid): + _tagName = "area" + + def _getCoords(self): + return self.element.coords + + def _setCoords(self, val): + self.element.coords = val + + def _getShape(self): + return self.element.shape + + def _setShape(self, val): + self.element.shape = val + + +# Audio ---------------------------------------------------------------------------------------------------------------- + +class Audio(Widget, _attrSrc, _attrMultimedia): + _tagName = "audio" + +class Bdo(Widget): + _tagName = "bdo" + + +# Blockquote ----------------------------------------------------------------------------------------------------------- + +class Blockquote(Widget): + _tagName = "blockquote" + + def _getBlockquote(self): + return self.element.blockquote + + def _setBlockquote(self, val): + self.element.blockquote = val + + +# Body ----------------------------------------------------------------------------------------------------------------- + +class BodyCls(Widget): + + def __init__(self, *args, **kwargs): + super().__init__(_wrapElem=domGetElementsByTagName("body")[0], *args, **kwargs) + self._isAttached = True + + +_body = None + + +def Body(): + global _body + + if _body is None: + _body = BodyCls() + + return _body + + +# Canvas --------------------------------------------------------------------------------------------------------------- + +class Canvas(Widget, _attrDimensions): + _tagName = "canvas" + + +# Command -------------------------------------------------------------------------------------------------------------- + +class Command(Widget, _attrLabel, _attrType, _attrDisabled, _attrChecked): + _tagName = "command" + + def _getIcon(self): + return self.element.icon + + def _setIcon(self, val): + self.element.icon = val + + def _getRadiogroup(self): + return self.element.radiogroup + + def _setRadiogroup(self, val): + self.element.radiogroup = val + + +# _Del ----------------------------------------------------------------------------------------------------------------- + +class _Del(Widget, _attrCite, _attrDatetime): + _tagName = "_del" + + +# Dialog -------------------------------------------------------------------------------------------------------------- + +class Dialog(Widget): + _tagName = "dialog" + + def _getOpen(self): + return True if self.element.hasAttribute("open") else False + + def _setOpen(self, val): + if val: + self.element.setAttribute("open", "") + else: + self.element.removeAttribute("open") + +# Elements ------------------------------------------------------------------------------------------------------------- + +class Abbr(Widget): + _tagName = "abbr" + + +class Address(Widget): + _tagName = "address" + + +class Article(Widget): + _tagName = "article" + + +class Aside(Widget): + _tagName = "aside" + + +class B(Widget): + _tagName = "b" + + +class Bdi(Widget): + _tagName = "bdi" + + +class Br(Widget, _isVoid): + _tagName = "br" + + +class Caption(Widget): + _tagName = "caption" + + +class Cite(Widget): + _tagName = "cite" + + +class Code(Widget): + _tagName = "code" + + +class Datalist(Widget): + _tagName = "datalist" + + +class Dfn(Widget): + _tagName = "dfn" + + +class Div(Widget): + _tagName = "div" + + +class Em(Widget): + _tagName = "em" + + +class Embed(Widget, _attrSrc, _attrType, _attrDimensions, _isVoid): + _tagName = "embed" + + +class Figcaption(Widget): + _tagName = "figcaption" + + +class Figure(Widget): + _tagName = "figure" + + +class Footer(Widget): + _tagName = "footer" + + +class Header(Widget): + _tagName = "header" + + +class H1(Widget): + _tagName = "h1" + + +class H2(Widget): + _tagName = "h2" + + +class H3(Widget): + _tagName = "h3" + + +class H4(Widget): + _tagName = "h4" + + +class H5(Widget): + _tagName = "h5" + + +class H6(Widget): + _tagName = "h6" + + +class Hr(Widget, _isVoid): + _tagName = "hr" + + +class I(Widget): + _tagName = "i" + + +class Kdb(Widget): + _tagName = "kdb" + + +class Legend(Widget): + _tagName = "legend" + + +class Mark(Widget): + _tagName = "mark" + + +class Noscript(Widget): + _tagName = "noscript" + + +class P(Widget): + _tagName = "p" + + +class Rq(Widget): + _tagName = "rq" + + +class Rt(Widget): + _tagName = "rt" + + +class Ruby(Widget): + _tagName = "ruby" + + +class S(Widget): + _tagName = "s" + + +class Samp(Widget): + _tagName = "samp" + + +class Section(Widget): + _tagName = "section" + + +class Small(Widget): + _tagName = "small" + + +class Strong(Widget): + _tagName = "strong" + + +class Sub(Widget): + _tagName = "sub" + + +class Summery(Widget): + _tagName = "summery" + + +class Sup(Widget): + _tagName = "sup" + + +class U(Widget): + _tagName = "u" + + +class Var(Widget): + _tagName = "var" + + +class Wbr(Widget): + _tagName = "wbr" + + +# Form ----------------------------------------------------------------------------------------------------------------- + +class Button(Widget, _attrDisabled, _attrType, _attrForm, _attrAutofocus, _attrName, _attrValue, _attrFormhead): + _tagName = "button" + + +class Fieldset(Widget, _attrDisabled, _attrForm, _attrName): + _tagName = "fieldset" + + +class Form(Widget, _attrDisabled, _attrName, _attrTarget, _attrAutocomplete): + _tagName = "form" + + def _getNovalidate(self): + return True if self.element.hasAttribute("novalidate") else False + + def _setNovalidate(self, val): + if val: + self.element.setAttribute("novalidate", "") + else: + self.element.removeAttribute("novalidate") + + def _getAction(self): + return self.element.action + + def _setAction(self, val): + self.element.action = val + + def _getMethod(self): + return self.element.method + + def _setMethod(self, val): + self.element.method = val + + def _getEnctype(self): + return self.element.enctype + + def _setEnctype(self, val): + self.element.enctype = val + + def _getAccept_attrCharset(self): + return getattr(self.element, "accept-charset") + + def _setAccept_attrCharset(self, val): + self.element.setAttribute("accept-charset", val) + + +class Input(Widget, _attrDisabled, _attrType, _attrForm, _attrAlt, _attrAutofocus, _attrChecked, + _attrIndeterminate, _attrName, _attrDimensions, _attrValue, _attrFormhead, + _attrAutocomplete, _attrInputs, _attrMultiple, _attrSize, _attrSrc, _isVoid): + _tagName = "input" + + def _getAccept(self): + return self.element.accept + + def _setAccept(self, val): + self.element.accept = val + + def _getList(self): + return self.element.list + + def _setList(self, val): + self.element.list = val + + def _getMax(self): + return self.element.max + + def _setMax(self, val): + self.element.max = val + + def _getMin(self): + return self.element.min + + def _setMin(self, val): + self.element.min = val + + def _getPattern(self): + return self.element.pattern + + def _setPattern(self, val): + self.element.pattern = val + + def _getStep(self): + return self.element.step + + def _setStep(self, val): + self.element.step = val + + +class Label(Widget, _attrForm, _attrFor): + _tagName = "label" + autoIdCounter = 0 + + def __init__(self, *args, forElem=None, **kwargs): + super().__init__(*args, **kwargs) + + if forElem: + if not forElem["id"]: + idx = Label.autoIdCounter + Label.autoIdCounter += 1 + forElem["id"] = "label-autoid-for-{}".format(idx) + + self["for"] = forElem["id"] + + +class Optgroup(Widget, _attrDisabled, _attrLabel): + _tagName = "optgroup" + + +class Option(Widget, _attrDisabled, _attrLabel, _attrValue): + _tagName = "option" + + def _getSelected(self): + return True if self.element.selected else False + + def _setSelected(self, val): + if val: + self.element.selected = True + else: + self.element.selected = False + + +class Output(Widget, _attrForm, _attrName, _attrFor): + _tagName = "output" + + +class Select(Widget, _attrDisabled, _attrForm, _attrAutofocus, _attrName, _attrRequired, _attrMultiple, _attrSize): + _tagName = "select" + + def _getSelectedIndex(self): + return self.element.selectedIndex + + def _getOptions(self): + return self.element.options + + +class Textarea(Widget, _attrDisabled, _attrForm, _attrAutofocus, _attrName, _attrInputs, _attrValue): + _tagName = "textarea" + + def _getCols(self): + return self.element.cols + + def _setCols(self, val): + self.element.cols = val + + def _getRows(self): + return self.element.rows + + def _setRows(self, val): + self.element.rows = val + + def _getWrap(self): + return self.element.wrap + + def _setWrap(self, val): + self.element.wrap = val + + +# Head ----------------------------------------------------------------------------------------------------------------- + +class HeadCls(Widget): + + def __init__(self, *args, **kwargs): + super().__init__(_wrapElem=domGetElementsByTagName("head")[0], *args, **kwargs) + self._isAttached = True + + +_head = None + + +def Head(): + global _head + if _head is None: + _head = HeadCls() + return _head + + +# Iframe --------------------------------------------------------------------------------------------------------------- + +class Iframe(Widget, _attrSrc, _attrName, _attrDimensions): + _tagName = "iframe" + + def _getSandbox(self): + return self.element.sandbox + + def _setSandbox(self, val): + self.element.sandbox = val + + def _getSrcdoc(self): + return self.element.src + + def _setSrcdoc(self, val): + self.element.src = val + + def _getSeamless(self): + return True if self.element.hasAttribute("seamless") else False + + def _setSeamless(self, val): + if val: + self.element.setAttribute("seamless", "") + else: + self.element.removeAttribute("seamless") + + +# Img ------------------------------------------------------------------------------------------------------------------ + +class Img(Widget, _attrSrc, _attrDimensions, _attrUsemap, _attrAlt, _isVoid): + _tagName = "img" + + def __init__(self, src=None, *args, **kwargs): + super().__init__() + if src: + self["src"] = src + + def _getCrossorigin(self): + return self.element.crossorigin + + def _setCrossorigin(self, val): + self.element.crossorigin = val + + def _getIsmap(self): + return self.element.ismap + + def _setIsmap(self, val): + self.element.ismap = val + + +# Ins ------------------------------------------------------------------------------------------------------------------ + +class Ins(Widget, _attrCite, _attrDatetime): + _tagName = "ins" + + +# Keygen --------------------------------------------------------------------------------------------------------------- + +class Keygen(Form, _attrAutofocus, _attrDisabled): + _tagName = "keygen" + + def _getChallenge(self): + return True if self.element.hasAttribute("challenge") else False + + def _setChallenge(self, val): + if val: + self.element.setAttribute("challenge", "") + else: + self.element.removeAttribute("challenge") + + def _getKeytype(self): + return self.element.keytype + + def _setKeytype(self, val): + self.element.keytype = val + + +# Link ----------------------------------------------------------------------------------------------------------------- + +class Link(Widget, _attrHref, _attrMedia, _attrRel, _isVoid): + _tagName = "link" + + def _getSizes(self): + return self.element.sizes + + def _setSizes(self, val): + self.element.sizes = val + + +# List ----------------------------------------------------------------------------------------------------------------- + +class Ul(Widget): + _tagName = "ul" + + +class Ol(Widget): + _tagName = "ol" + + +class Li(Widget): + _tagName = "li" + + +class Dl(Widget): + _tagName = "dl" + + +class Dt(Widget): + _tagName = "dt" + + +class Dd(Widget): + _tagName = "dd" + + +# Map ------------------------------------------------------------------------------------------------------------------ + +class Map(Label, _attrType): + _tagName = "map" + + +# Menu ----------------------------------------------------------------------------------------------------------------- + +class Menu(Widget): + _tagName = "menu" + + +# Meta ----------------------------------------------------------------------------------------------------------------- + +class Meta(Widget, _attrName, _attrCharset, _isVoid): + _tagName = "meta" + + def _getContent(self): + return self.element.content + + def _setContent(self, val): + self.element.content = val + + +# Meter ---------------------------------------------------------------------------------------------------------------- + +class Meter(Form, _attrValue): + _tagName = "meter" + + def _getHigh(self): + return self.element.high + + def _setHigh(self, val): + self.element.high = val + + def _getLow(self): + return self.element.low + + def _setLow(self, val): + self.element.low = val + + def _getMax(self): + return self.element.max + + def _setMax(self, val): + self.element.max = val + + def _getMin(self): + return self.element.min + + def _setMin(self, val): + self.element.min = val + + def _getOptimum(self): + return self.element.optimum + + def _setOptimum(self, val): + self.element.optimum = val + + +# Nav ------------------------------------------------------------------------------------------------------------------ + +class Nav(Widget): + _tagName = "nav" + + +# Object ----------------------------------------------------------------------------------------------------------------- + +class Object(Form, _attrType, _attrName, _attrDimensions, _attrUsemap): + _tagName = "object" + + +# Param ----------------------------------------------------------------------------------------------------------------- + +class Param(Widget, _attrName, _attrValue, _isVoid): + _tagName = "param" + + +# Progress ------------------------------------------------------------------------------------------------------------- + +class Progress(Widget, _attrValue): + _tagName = "progress" + + def _getMax(self): + return self.element.max + + def _setMax(self, val): + self.element.max = val + + +# Q -------------------------------------------------------------------------------------------------------------------- + +class Q(Widget, _attrCite): + _tagName = "q" + + +# Script ---------------------------------------------------------------------------------------------------------------- + +class Script(Widget, _attrSrc, _attrCharset): + _tagName = "script" + + def _getAsync(self): + return True if self.element.hasAttribute("async") else False + + def _setAsync(self, val): + if val: + self.element.setAttribute("async", "") + else: + self.element.removeAttribute("async") + + def _getDefer(self): + return True if self.element.hasAttribute("defer") else False + + def _setDefer(self, val): + if val: + self.element.setAttribute("defer", "") + else: + self.element.removeAttribute("defer") + + +# Source --------------------------------------------------------------------------------------------------------------- + +class Source(Widget, _attrMedia, _attrSrc, _isVoid): + _tagName = "source" + + +# Span ----------------------------------------------------------------------------------------------------------------- + +class Span(Widget): + _tagName = "span" + + +# Style ---------------------------------------------------------------------------------------------------------------- + +class Style(Widget, _attrMedia): + _tagName = "style" + + def _getScoped(self): + return True if self.element.hasAttribute("scoped") else False + + def _setScoped(self, val): + if val: + self.element.setAttribute("scoped", "") + else: + self.element.removeAttribute("scoped") + + +# SVG ------------------------------------------------------------------------------------------------------------------ + +class Svg(Widget, _attrSvgViewBox, _attrSvgDimensions, _attrSvgTransform): + _tagName = "svg" + _namespace = "SVG" + + def _getVersion(self): + return self.element.version + + def _setVersion(self, val): + self.element.setAttribute("version", val) + + def _getXmlns(self): + return self.element.xmlns + + def _setXmlns(self, val): + self.element.setAttribute("xmlns", val) + + +class SvgCircle(Widget, _attrSvgTransform, _attrSvgDimensions): + _tagName = "circle" + _namespace = "SVG" + + +class SvgEllipse(Widget, _attrSvgTransform, _attrSvgDimensions): + _tagName = "ellipse" + _namespace = "SVG" + + +class SvgG(Widget, _attrSvgTransform, _attrSvgStyles): + _tagName = "g" + _namespace = "SVG" + + def _getSvgTransform(self): + return self.element.transform + + def _setSvgTransform(self, val): + self.element.setAttribute("transform", val) + + +class SvgImage(Widget, _attrSvgViewBox, _attrSvgDimensions, _attrSvgTransform, _attrSvgXlink): + _tagName = "image" + _namespace = "SVG" + + +class SvgLine(Widget, _attrSvgTransform, _attrSvgPoints): + _tagName = "line" + _namespace = "SVG" + + +class SvgPath(Widget, _attrSvgTransform): + _tagName = "path" + _namespace = "SVG" + + def _getD(self): + return self.element.d + + def _setD(self, val): + self.element.setAttribute("d", val) + + def _getPathLength(self): + return self.element.pathLength + + def _setPathLength(self, val): + self.element.setAttribute("pathLength", val) + + +class SvgPolygon(Widget, _attrSvgTransform, _attrSvgPoints): + _tagName = "polygon" + _namespace = "SVG" + + +class SvgPolyline(Widget, _attrSvgTransform, _attrSvgPoints): + _tagName = "polyline" + _namespace = "SVG" + + +class SvgRect(Widget, _attrSvgDimensions, _attrSvgTransform, _attrSvgStyles): + _tagName = "rect" + _namespace = "SVG" + + +class SvgText(Widget, _attrSvgDimensions, _attrSvgTransform, _attrSvgStyles): + _tagName = "text" + _namespace = "SVG" + + +# Table ---------------------------------------------------------------------------------------------------------------- + + +class Tr(Widget): + _tagName = "tr" + + def _getRowspan(self): + span = self.element.getAttribute("rowspan") + return span if span else 1 + + def _setRowspan(self, span): + assert span >= 1, "span may not be negative" + self.element.setAttribute("rowspan", span) + return self + + +class Td(Widget): + _tagName = "td" + + def _getColspan(self): + span = self.element.getAttribute("colspan") + return span if span else 1 + + def _setColspan(self, span): + assert span >= 1, "span may not be negative" + self.element.setAttribute("colspan", span) + return self + + def _getRowspan(self): + span = self.element.getAttribute("rowspan") + return span if span else 1 + + def _setRowspan(self, span): + assert span >= 1, "span may not be negative" + self.element.setAttribute("rowspan", span) + return self + + +class Th(Td): + _tagName = "th" + + +class Thead(Widget): + _tagName = "thead" + + +class Tbody(Widget): + _tagName = "tbody" + + +class ColWrapper(object): + def __init__(self, parentElem, *args, **kwargs): + super().__init__(*args, **kwargs) + self.parentElem = parentElem + + def __getitem__(self, item): + assert isinstance(item, int), "Invalid col-number. Expected int, got {}".format(str(type(item))) + if item < 0 or item > len(self.parentElem._children): + return None + + return self.parentElem._children[item] + + def __setitem__(self, key, value): + col = self[key] + assert col is not None, "Cannot assign widget to invalid column" + + col.removeAllChildren() + + if isinstance(value, list) or isinstance(value, tuple): + for el in value: + if isinstance(el, Widget) or isinstance(el, TextNode): + col.appendChild(value) + + elif isinstance(value, Widget) or isinstance(value, TextNode): + col.appendChild(value) + + +class RowWrapper(object): + def __init__(self, parentElem, *args, **kwargs): + super().__init__(*args, **kwargs) + self.parentElem = parentElem + + def __getitem__(self, item): + assert isinstance(item, int), "Invalid row-number. Expected int, got {}".format(str(type(item))) + if item < 0 or item > len(self.parentElem._children): + return None + + return ColWrapper(self.parentElem._children[item]) + + +class Table(Widget): + _tagName = "table" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.head = Thead() + self.body = Tbody() + self.appendChild(self.head) + self.appendChild(self.body) + + def prepareRow(self, row): + assert row >= 0, "Cannot create rows with negative index" + + for child in self.body._children: + row -= child["rowspan"] + if row < 0: + return + + while row >= 0: + self.body.appendChild(Tr()) + row -= 1 + + def prepareCol(self, row, col): + assert col >= 0, "Cannot create cols with negative index" + self.prepareRow(row) + + for rowChild in self.body._children: + row -= rowChild["rowspan"] + + if row < 0: + for colChild in rowChild._children: + col -= colChild["colspan"] + if col < 0: + return + + while col >= 0: + rowChild.appendChild(Td()) + col -= 1 + + return + + def prepareGrid(self, rows, cols): + for row in range(self.getRowCount(), self.getRowCount() + rows): + self.prepareCol(row, cols) + + def clear(self): + for row in self.body._children[:]: + + for col in row._children[:]: + row.removeChild(col) + + self.body.removeChild(row) + + def _getCell(self): + return RowWrapper(self.body) + + def getRowCount(self): + cnt = 0 + + for tr in self.body._children: + cnt += tr["rowspan"] + + return cnt + + +# Time ----------------------------------------------------------------------------------------------------------------- + +class Time(Widget, _attrDatetime): + _tagName = "time" + + +# Track ---------------------------------------------------------------------------------------------------------------- + +class Track(Label, _attrSrc, _isVoid): + _tagName = "track" + + def _getKind(self): + return self.element.kind + + def _setKind(self, val): + self.element.kind = val + + def _getSrclang(self): + return self.element.srclang + + def _setSrclang(self, val): + self.element.srclang = val + + def _getDefault(self): + return True if self.element.hasAttribute("default") else False + + def _setDefault(self, val): + if val: + self.element.setAttribute("default", "") + else: + self.element.removeAttribute("default") + + +# Video ---------------------------------------------------------------------------------------------------------------- + +class Video(Widget, _attrSrc, _attrDimensions, _attrMultimedia): + _tagName = "video" + + def _getPoster(self): + return self.element.poster + + def _setPoster(self, val): + self.element.poster = val + + +######################################################################################################################## +# Utilities +######################################################################################################################## + +def unescape(val, maxLength=0): + """ + Unquotes several HTML-quoted characters in a string. + + :param val: The value to be unescaped. + :type val: str + + :param maxLength: Cut-off after maxLength characters. + A value of 0 means "unlimited". (default) + :type maxLength: int + + :returns: The unquoted string. + :rtype: str + """ + val = val \ + .replace("<", "<") \ + .replace(">", ">") \ + .replace(""", "\"") \ + .replace("'", "'") + + if maxLength > 0: + return val[0:maxLength] + + return val + + +def doesEventHitWidgetOrParents(event, widget): + """ + Test if event 'event' hits widget 'widget' (or *any* of its parents) + """ + while widget: + if event.target == widget.element: + return True + + widget = widget.parent() + + return False + + +def doesEventHitWidgetOrChildren(event, widget): + """ + Test if event 'event' hits widget 'widget' (or *any* of its children) + """ + if event.target == widget.element: + return True + + for child in widget._children: + if doesEventHitWidgetOrChildren(event, child): + return True + + return False + + +def textToHtml(node, text): + """ + Generates html nodes from text by splitting text into content and into + line breaks html5.Br. + + :param node: The node where the nodes are appended to. + :param text: The text to be inserted. + """ + + for (i, part) in enumerate(text.split("\n")): + if i > 0: + node.appendChild(Br()) + + node.appendChild(TextNode(part)) + + +def parseInt(s, ret=0): + """ + Parses a value as int + """ + if not isinstance(s, str): + return int(s) + elif s: + if s[0] in "+-": + ts = s[1:] + else: + ts = s + + if ts and all([_ in "0123456789" for _ in ts]): + return int(s) + + return ret + + +def parseFloat(s, ret=0.0): + """ + Parses a value as float. + """ + if not isinstance(s, str): + return float(s) + elif s: + if s[0] in "+-": + ts = s[1:] + else: + ts = s + + if ts and ts.count(".") <= 1 and all([_ in ".0123456789" for _ in ts]): + return float(s) + + return ret + + +######################################################################################################################## +# Keycodes +######################################################################################################################## + +def getKey(event): + """ + Returns the Key Identifier of the given event + + Available Codes: https://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/keyset.html#KeySet-Set + """ + if hasattr(event, "key"): + return event.key + + elif hasattr(event, "keyIdentifier"): + if event.keyIdentifier in ["Esc", "U+001B"]: + return "Escape" + else: + return event.keyIdentifier + + return None + + +def isArrowLeft(event): + return getKey(event) in ["ArrowLeft", "Left"] + +def isArrowUp(event): + return getKey(event) in ["ArrowUp", "Up"] + +def isArrowRight(event): + return getKey(event) in ["ArrowRight", "Right"] + +def isArrowDown(event): + return getKey(event) in ["ArrowDown", "Down"] + +def isEscape(event): + return getKey(event) == "Escape" + +def isReturn(event): + return getKey(event) == "Enter" + +def isControl(event): # The Control (Ctrl) key. + return getKey(event) == "Control" + +def isShift(event): + return getKey(event) == "Shift" + + +######################################################################################################################## +# HTML parser +######################################################################################################################## + +# Global variables required by HTML parser +__tags = None +__domParser = None + + +def registerTag(tagName, widgetClass, override=True): + assert issubclass(widgetClass, Widget), "widgetClass must be a sub-class of Widget!" + global __tags + + if __tags is None: + _buildTags() + + if not override and tagName.lower() in __tags: + return + + attr = [] + + for fname in dir(widgetClass): + if fname.startswith("_set"): + attr.append(fname[4:].lower()) + + __tags[tagName.lower()] = (widgetClass, attr) + + +def tag(cls): + assert issubclass(cls, Widget) + registerTag(cls._parserTagName or cls.__name__, cls) # do NOT check for cls._tagName here!!! + return cls + + +def _buildTags(debug=False): + """ + Generates a dictionary of all to the html5-library + known tags and their associated objects and attributes. + """ + global __tags + + if __tags is not None: + return + + if __tags is None: + __tags = {} + + for cname in globals().keys(): + if cname.startswith("_"): + continue + + cls = globals()[cname] + + try: + if not issubclass(cls, Widget): + continue + except: + continue + + registerTag(cls._parserTagName or cls._tagName or cls.__name__, cls, override=False) + + if debug: + for tag in sorted(__tags.keys()): + print("{}: {}".format(tag, ", ".join(sorted(__tags[tag][1])))) + + +class HtmlAst(list): + pass + + +def parseHTML(html, debug=False): + """ + Parses the provided HTML-code according to the objects defined in the html5-library. + """ + + def convertEncodedText(txt): + """ + Convert HTML-encoded text into decoded string. + + The reason for this function is the handling of HTML entities, which is not + properly supported by native JavaScript. + + We use the browser's DOM parser to to this, according to + https://stackoverflow.com/questions/3700326/decode-amp-back-to-in-javascript + + :param txt: The encoded text. + :return: The decoded text. + """ + global __domParser + + if jseval is None: + return txt + + if __domParser is None: + __domParser = jseval("new DOMParser") + + dom = __domParser.parseFromString("" + str(txt), "text/html") + return dom.body.textContent + + def scanWhite(l): + """ + Scan and return whitespace. + """ + + ret = "" + while l and l[0] in " \t\r\n": + ret += l.pop(0) + + return ret + + def scanWord(l): + """ + Scan and return a word. + """ + + ret = "" + while l and l[0] not in " \t\r\n" + "<>=\"'": + ret += l.pop(0) + + return ret + + stack = [] + + # Obtain tag descriptions, if not already done! + global __tags + + if __tags is None: + _buildTags(debug=debug) + + # Prepare stack and input + stack.append((None, None, HtmlAst())) + html = [ch for ch in html] + + # Parse + while html: + tag = None + text = "" + + # Auto-close void elements (_isVoid), e.g.
,
, etc. + while stack and stack[-1][0] and issubclass(__tags[stack[-1][0]][0], _isVoid): + stack.pop() + + if not stack: + break + + parent = stack[-1][2] + + while html: + ch = html.pop(0) + + # Comment + if html and ch == "<" and "".join(html[:3]) == "!--": + html = html[3:] + while html and "".join(html[:3]) != "-->": + html.pop(0) + + html = html[3:] + + # Opening tag + elif html and ch == "<" and html[0] != "/": + tag = scanWord(html) + if tag.lower() in __tags: + break + + text += ch + tag + + # Closing tag + elif html and stack[-1][0] and ch == "<" and html[0] == "/": + junk = ch + junk += html.pop(0) + + tag = scanWord(html) + junk += tag + + if stack[-1][0] == tag.lower(): + junk += scanWhite(html) + if html and html[0] == ">": + html.pop(0) + stack.pop() + tag = None + break + + text += junk + tag = None + + else: + text += ch + + # Append plain text (if not only whitespace) + if (text and ((len(text) == 1 and text in ["\t "]) + or not all([ch in " \t\r\n" for ch in text]))): + # print("text", text) + parent.append(convertEncodedText(text)) + + # Create tag + if tag: + tag = tag.lower() + # print("tag", tag) + + elem = (tag, {}, HtmlAst()) + + stack.append(elem) + parent.append(elem) + + while html: + scanWhite(html) + if not html: + break + + # End of tag > + if html[0] == ">": + html.pop(0) + break + + # Closing tag at end /> + elif html[0] == "/": + html.pop(0) + scanWhite(html) + + if html[0] == ">": + stack.pop() + html.pop(0) + break + + val = att = scanWord(html).lower() + + if not att: + html.pop(0) + continue + + if att in __tags[tag][1] or att in ["[name]", "style", "disabled", "hidden"] or att.startswith("data-"): + scanWhite(html) + if html[0] == "=": + html.pop(0) + scanWhite(html) + + if html[0] in "\"'": + ch = html.pop(0) + + val = "" + while html and html[0] != ch: + val += html.pop(0) + + html.pop(0) + + if att not in elem[1]: + elem[1][att] = val + else: + elem[1][att] += " " + val + + continue + + while stack and stack[-1][0]: + stack.pop() + + return stack[0][2] + +def fromHTML(html, appendTo=None, bindTo=None, debug=False, vars=None, **kwargs): + """ + Parses the provided HTML code according to the objects defined in the html5-library. + html can also be pre-compiled by `parseHTML()` so that it executes faster. + + Constructs all objects as DOM nodes. The first level is chained into appendTo. + If no appendTo is provided, appendTo will be set to html5.Body(). + + If bindTo is provided, objects are bound to this widget. + + ```python + from vi import html5 + + div = html5.Div() + html5.parse.fromHTML(''' + ''', div) + + div.myLink.appendChild("appended!") + ``` + """ + + # Handle defaults + if bindTo is None: + bindTo = appendTo + + if isinstance(html, str): + html = parseHTML(html, debug=debug) + + assert isinstance(html, HtmlAst) + + if isinstance(vars, dict): + kwargs.update(vars) + + def replaceVars(txt): + for var, val in kwargs.items(): + txt = txt.replace("{{%s}}" % var, str(val) if val is not None else "") + + return txt + + def interpret(parent, items): + ret = [] + + for item in items: + if isinstance(item, str): + txt = TextNode(replaceVars(item)) + + if parent: + parent.appendChild(txt) + + ret.append(txt) + continue + + tag = item[0] + atts = item[1] + children = item[2] + + # Special handling for tables: A "thead" and "tbody" are already part of table! + if tag in ["thead", "tbody"] and isinstance(parent, Table): + wdg = getattr(parent, tag[1:]) + + # Usual way: Construct new element and chain it into the parent. + else: + wdg = __tags[tag][0]() + + for att, val in atts.items(): + val = replaceVars(val) + + if att == "[name]": + # Allow disable binding! + if not bindTo: + continue + + if getattr(bindTo, val, None): + print("Cannot assign name '{}' because it already exists in {}".format(val, bindTo)) + + elif not (any([val.startswith(x) for x in + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "_"]) + and all( + [x in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789" + "_" + for x in val[1:]])): + print("Cannot assign name '{}' because it contains invalid characters".format(val)) + + else: + setattr(bindTo, val, wdg) + wdg.onBind(bindTo, val) + + if debug: + print("name '{}' assigned to {}".format(val, bindTo)) + + elif att == "class": + # print(tag, att, val.split()) + wdg.addClass(*val.split()) + + elif att == "disabled": + # print(tag, att, val) + if val == "disabled": + wdg.disable() + + elif att == "hidden": + # print(tag, att, val) + if val == "hidden": + wdg.hide() + + elif att == "style": + for dfn in val.split(";"): + if ":" not in dfn: + continue + + att, val = dfn.split(":", 1) + + # print(tag, "style", att.strip(), val.strip()) + wdg["style"][att.strip()] = val.strip() + + elif att.startswith("data-"): + wdg["data"][att[5:]] = val + + else: + wdg[att] = parseInt(val, val) + + interpret(wdg, children) + + if parent and not wdg.parent(): + parent.appendChild(wdg) + + ret.append(wdg) + + return ret + + return interpret(appendTo, html) + + +if __name__ == '__main__': + print(globals()) diff --git a/testbed/lark-parser__lark/docs/ide/app/examples.py b/testbed/lark-parser__lark/docs/ide/app/examples.py new file mode 100644 index 0000000000000000000000000000000000000000..af9c38c479472069e7e9aee6fc9707bee52896a3 --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/examples.py @@ -0,0 +1,150 @@ + +# Examples formattet this way: +# "name": ("grammar", "demo-input") + +examples = { + + # --- hello.lark --- + "hello.lark": (""" +start: WORD "," WORD "!" + +%import common.WORD // imports from terminal library +%ignore " " // Disregard spaces in text +""", "Hello, World!"), + + # --- calc.lark --- +"calc.lark": (""" +?start: sum + | NAME "=" sum -> assign_var + +?sum: product + | sum "+" product -> add + | sum "-" product -> sub + +?product: atom + | product "*" atom -> mul + | product "/" atom -> div + +?atom: NUMBER -> number + | "-" atom -> neg + | NAME -> var + | "(" sum ")" + +%import common.CNAME -> NAME +%import common.NUMBER +%import common.WS_INLINE +%ignore WS_INLINE""", + "1 + 2 * 3 + 4"), + + # --- json.lark --- + "json.lark": (""" +?start: value +?value: object + | array + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null +array : "[" [value ("," value)*] "]" +object : "{" [pair ("," pair)*] "}" +pair : string ":" value +string : ESCAPED_STRING +%import common.ESCAPED_STRING +%import common.SIGNED_NUMBER +%import common.WS +%ignore WS""", +""" +[ + { + "_id": "5edb875cf3d764da55602437", + "index": 0, + "guid": "3dae2206-5d4d-41fe-b81d-dc8cdba7acaa", + "isActive": false, + "balance": "$2,872.54", + "picture": "http://placehold.it/32x32", + "age": 24, + "eyeColor": "blue", + "name": "Theresa Vargas", + "gender": "female", + "company": "GEEKOL", + "email": "theresavargas@geekol.com", + "phone": "+1 (930) 450-3445", + "address": "418 Herbert Street, Sexton, Florida, 1375", + "about": "Id minim deserunt laborum enim. Veniam commodo incididunt amet aute esse duis veniam occaecat nulla esse aute et deserunt eiusmod. Anim elit ullamco minim magna sint laboris. Est consequat quis deserunt excepteur in magna pariatur laborum quis eu. Ex quis tempor elit qui qui et culpa sunt sit esse mollit cupidatat. Fugiat cillum deserunt enim minim irure reprehenderit est. Voluptate nisi quis amet quis incididunt pariatur nostrud Lorem consectetur adipisicing voluptate.\\r\\n", + "registered": "2016-11-19T01:02:42 -01:00", + "latitude": -25.65267, + "longitude": 104.19531, + "tags": [ + "eiusmod", + "reprehenderit", + "anim", + "sunt", + "esse", + "proident", + "esse" + ], + "friends": [ + { + "id": 0, + "name": "Roth Herrera" + }, + { + "id": 1, + "name": "Callie Christian" + }, + { + "id": 2, + "name": "Gracie Whitfield" + } + ], + "greeting": "Hello, Theresa Vargas! You have 6 unread messages.", + "favoriteFruit": "banana" + }, + { + "_id": "5edb875c845eb08161a83e64", + "index": 1, + "guid": "a8ada2c1-e2c7-40d3-96b4-52c93baff7f0", + "isActive": false, + "balance": "$2,717.04", + "picture": "http://placehold.it/32x32", + "age": 23, + "eyeColor": "green", + "name": "Lily Ross", + "gender": "female", + "company": "RODEOMAD", + "email": "lilyross@rodeomad.com", + "phone": "+1 (941) 465-3561", + "address": "525 Beekman Place, Blodgett, Marshall Islands, 3173", + "about": "Aliquip duis proident excepteur eiusmod in quis officia consequat culpa eu et ut. Occaecat reprehenderit tempor mollit do eu magna qui et magna exercitation aliqua. Incididunt exercitation dolor proident eiusmod minim occaecat. Sunt et minim mollit et veniam sint ex. Duis ullamco elit aute eu excepteur reprehenderit officia.\\r\\n", + "registered": "2019-11-02T04:06:42 -01:00", + "latitude": 17.031701, + "longitude": -42.657106, + "tags": [ + "id", + "non", + "culpa", + "reprehenderit", + "esse", + "elit", + "sit" + ], + "friends": [ + { + "id": 0, + "name": "Ursula Maldonado" + }, + { + "id": 1, + "name": "Traci Huff" + }, + { + "id": 2, + "name": "Taylor Holt" + } + ], + "greeting": "Hello, Lily Ross! You have 3 unread messages.", + "favoriteFruit": "strawberry" + } +]""") +} \ No newline at end of file diff --git a/testbed/lark-parser__lark/docs/ide/app/ext.py b/testbed/lark-parser__lark/docs/ide/app/ext.py new file mode 100644 index 0000000000000000000000000000000000000000..330d032eddc632fcdb14814792971208a090c8e4 --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/ext.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +from . import core as html5 +from . import utils + +class Button(html5.Button): + + def __init__(self, txt=None, callback=None, className=None, *args, **kwargs): + super().__init__(*args, **kwargs) + self["class"] = "btn" + + if className: + self.addClass(className) + + self["type"] = "button" + + if txt is not None: + self.setText(txt) + + self.callback = callback + self.sinkEvent("onClick") + + def setText(self, txt): + if txt is not None: + self.element.innerHTML = txt + self["title"] = txt + else: + self.element.innerHTML = "" + self["title"] = "" + + def onClick(self, event): + event.stopPropagation() + event.preventDefault() + if self.callback is not None: + self.callback(self) + + +class Input(html5.Input): + def __init__(self, type="text", placeholder=None, callback=None, id=None, focusCallback=None, *args, **kwargs): + """ + + :param type: Input type. Default: "text + :param placeholder: Placeholder text. Default: None + :param callback: Function to be called onChanged: callback(id, value) + :param id: Optional id of the input element. Will be passed to callback + :return: + """ + super().__init__(*args, **kwargs) + self["class"] = "input" + self["type"] = type + if placeholder is not None: + self["placeholder"] = placeholder + + self.callback = callback + if id is not None: + self["id"] = id + self.sinkEvent("onChange") + + self.focusCallback = focusCallback + if focusCallback: + self.sinkEvent("onFocus") + + def onChange(self, event): + event.stopPropagation() + event.preventDefault() + if self.callback is not None: + self.callback(self, self["id"], self["value"]) + + def onFocus(self, event): + event.stopPropagation() + event.preventDefault() + if self.focusCallback is not None: + self.focusCallback(self, self["id"], self["value"]) + + def onDetach(self): + super().onDetach() + self.callback = None + + +class Popup(html5.Div): + def __init__(self, title=None, id=None, className=None, icon=None, enableShortcuts=True, closeable=True, *args, **kwargs): + super().__init__(""" +
+
+
+
+ +
+
+
+
+
+
+
+
+
+ """) + + self.appendChild = self.popupBody.appendChild + self.fromHTML = lambda *args, **kwargs: self.popupBody.fromHTML(*args, **kwargs) if kwargs.get("bindTo") else self.popupBody.fromHTML(bindTo=self, *args, **kwargs) + + self["class"] = "popup popup--center is-active" + if className: + self.addClass(className) + + if closeable: + closeBtn = Button("×", self.close, className="item-action") + closeBtn.removeClass("btn") + self.popupHeadItem.appendChild(closeBtn) + + if title: + self.popupHeadline.appendChild(title) + + if icon: + self.popupIcon.appendChild(icon[0]) + elif title: + self.popupIcon.appendChild(title[0]) + else: + self.popupIcon.appendChild("Vi") #fixme!!! this _LIBRARY_ is not only used in the Vi... + + # id can be used to pass information to callbacks + self.id = id + + #FIXME: Implement a global overlay! One popupOverlay next to a list of popups. + self.popupOverlay = html5.Div() + self.popupOverlay["class"] = "popup-overlay is-active" + + self.enableShortcuts = enableShortcuts + self.onDocumentKeyDownMethod = None + + self.popupOverlay.appendChild(self) + html5.Body().appendChild(self.popupOverlay) + + #FIXME: Close/Cancel every popup with click on popupCloseBtn without removing the global overlay. + + def onAttach(self): + super(Popup, self).onAttach() + + if self.enableShortcuts: + self.onDocumentKeyDownMethod = self.onDocumentKeyDown # safe reference to method + html5.document.addEventListener("keydown", self.onDocumentKeyDownMethod) + + def onDetach(self): + super(Popup, self).onDetach() + + if self.enableShortcuts: + html5.document.removeEventListener("keydown", self.onDocumentKeyDownMethod) + + def onDocumentKeyDown(self, event): + if html5.isEscape(event): + self.close() + + def close(self, *args, **kwargs): + html5.Body().removeChild(self.popupOverlay) + self.popupOverlay = None + + + +class InputDialog(Popup): + def __init__(self, text, value="", successHandler=None, abortHandler=None, + successLbl="OK", abortLbl="Cancel", placeholder="", *args, **kwargs): + + super().__init__(*args, **kwargs) + self.addClass("popup--inputdialog") + + self.sinkEvent("onKeyDown", "onKeyUp") + + self.successHandler = successHandler + self.abortHandler = abortHandler + + self.fromHTML( + """ +
+ + +
+ """, + vars={ + "text": text, + "value": value, + "placeholder": placeholder + } + ) + + # Cancel + self.popupFoot.appendChild(Button(abortLbl, self.onCancel, className="btn--cancel btn--danger")) + + # Okay + self.okayBtn = Button(successLbl, self.onOkay, className="btn--okay btn--primary") + if not value: + self.okayBtn.disable() + + self.popupFoot.appendChild(self.okayBtn) + + self.inputElem.focus() + + def onKeyDown(self, event): + if html5.isReturn(event) and self.inputElem["value"]: + event.stopPropagation() + event.preventDefault() + self.onOkay() + + def onKeyUp(self, event): + if self.inputElem["value"]: + self.okayBtn.enable() + else: + self.okayBtn.disable() + + def onDocumentKeyDown(self, event): + if html5.isEscape(event): + event.stopPropagation() + event.preventDefault() + self.onCancel() + + def onOkay(self, *args, **kwargs): + if self.successHandler: + self.successHandler(self, self.inputElem["value"]) + self.close() + + def onCancel(self, *args, **kwargs): + if self.abortHandler: + self.abortHandler(self, self.inputElem["value"]) + self.close() + + +class Alert(Popup): + """ + Just displaying an alerting message box with OK-button. + """ + + def __init__(self, msg, title=None, className=None, okCallback=None, okLabel="OK", icon="!", closeable=True, *args, **kwargs): + super().__init__(title, className=None, icon=icon, closeable=closeable, *args, **kwargs) + self.addClass("popup--alert") + + if className: + self.addClass(className) + + self.okCallback = okCallback + + message = html5.Span() + message.addClass("alert-msg") + self.popupBody.appendChild(message) + + if isinstance(msg, str): + msg = msg.replace("\n", "
") + + message.appendChild(msg, bindTo=False) + + self.sinkEvent("onKeyDown") + + if closeable: + okBtn = Button(okLabel, callback=self.onOkBtnClick) + okBtn.addClass("btn--okay btn--primary") + self.popupFoot.appendChild(okBtn) + + okBtn.focus() + + def drop(self): + self.okCallback = None + self.close() + + def onOkBtnClick(self, sender=None): + if self.okCallback: + self.okCallback(self) + + self.drop() + + def onKeyDown(self, event): + if html5.isReturn(event): + event.stopPropagation() + event.preventDefault() + self.onOkBtnClick() + + +class YesNoDialog(Popup): + def __init__(self, question, title=None, yesCallback=None, noCallback=None, + yesLabel="Yes", noLabel="No", icon="?", + closeable=False, *args, **kwargs): + super().__init__(title, closeable=closeable, icon=icon, *args, **kwargs) + self.addClass("popup--yesnodialog") + + self.yesCallback = yesCallback + self.noCallback = noCallback + + lbl = html5.Span() + lbl["class"].append("question") + self.popupBody.appendChild(lbl) + + if isinstance(question, html5.Widget): + lbl.appendChild(question) + else: + utils.textToHtml(lbl, question) + + if len(noLabel): + btnNo = Button(noLabel, className="btn--no", callback=self.onNoClicked) + #btnNo["class"].append("btn--no") + self.popupFoot.appendChild(btnNo) + + btnYes = Button(yesLabel, callback=self.onYesClicked) + btnYes["class"].append("btn--yes") + self.popupFoot.appendChild(btnYes) + + self.sinkEvent("onKeyDown") + btnYes.focus() + + def onKeyDown(self, event): + if html5.isReturn(event): + event.stopPropagation() + event.preventDefault() + self.onYesClicked() + + def onDocumentKeyDown(self, event): + if html5.isEscape(event): + event.stopPropagation() + event.preventDefault() + self.onNoClicked() + + def drop(self): + self.yesCallback = None + self.noCallback = None + self.close() + + def onYesClicked(self, *args, **kwargs): + if self.yesCallback: + self.yesCallback(self) + + self.drop() + + def onNoClicked(self, *args, **kwargs): + if self.noCallback: + self.noCallback(self) + + self.drop() + + +class SelectDialog(Popup): + + def __init__(self, prompt, items=None, title=None, okBtn="OK", cancelBtn="Cancel", forceSelect=False, + callback=None, *args, **kwargs): + super().__init__(title, *args, **kwargs) + self["class"].append("popup--selectdialog") + + self.callback = callback + self.items = items + assert isinstance(self.items, list) + + # Prompt + if prompt: + lbl = html5.Span() + lbl["class"].append("prompt") + + if isinstance(prompt, html5.Widget): + lbl.appendChild(prompt) + else: + utils.textToHtml(lbl, prompt) + + self.popupBody.appendChild(lbl) + + # Items + if not forceSelect and len(items) <= 3: + for idx, item in enumerate(items): + if isinstance(item, dict): + title = item.get("title") + cssc = item.get("class") + elif isinstance(item, tuple): + title = item[1] + cssc = None + else: + title = item + + btn = Button(title, callback=self.onAnyBtnClick) + btn.idx = idx + + if cssc: + btn.addClass(cssc) + + self.popupBody.appendChild(btn) + else: + self.select = html5.Select() + self.popupBody.appendChild(self.select) + + for idx, item in enumerate(items): + if isinstance(item, dict): + title = item.get("title") + elif isinstance(item, tuple): + title = item[1] + else: + title = item + + opt = html5.Option(title) + opt["value"] = str(idx) + + self.select.appendChild(opt) + + if okBtn: + self.popupFoot.appendChild(Button(okBtn, callback=self.onOkClick)) + + if cancelBtn: + self.popupFoot.appendChild(Button(cancelBtn, callback=self.onCancelClick)) + + def onAnyBtnClick(self, sender): + item = self.items[sender.idx] + + if isinstance(item, dict) and item.get("callback") and callable(item["callback"]): + item["callback"](item) + + if self.callback: + self.callback(item) + + self.items = None + self.close() + + def onCancelClick(self, sender=None): + self.close() + + def onOkClick(self, sender=None): + assert self.select["selectedIndex"] >= 0 + item = self.items[int(self.select.children(self.select["selectedIndex"])["value"])] + + if isinstance(item, dict) and item.get("callback") and callable(item["callback"]): + item["callback"](item) + + if self.callback: + self.callback(item) + + self.items = None + self.select = None + self.close() + + +class TextareaDialog(Popup): + def __init__(self, text, value="", successHandler=None, abortHandler=None, successLbl="OK", abortLbl="Cancel", + *args, **kwargs): + super().__init__(*args, **kwargs) + self["class"].append("popup--textareadialog") + + self.successHandler = successHandler + self.abortHandler = abortHandler + + span = html5.Span() + span.element.innerHTML = text + self.popupBody.appendChild(span) + + self.inputElem = html5.Textarea() + self.inputElem["value"] = value + self.popupBody.appendChild(self.inputElem) + + okayBtn = Button(successLbl, self.onOkay) + okayBtn["class"].append("btn--okay") + self.popupFoot.appendChild(okayBtn) + + cancelBtn = Button(abortLbl, self.onCancel) + cancelBtn["class"].append("btn--cancel") + self.popupFoot.appendChild(cancelBtn) + + self.sinkEvent("onKeyDown") + + self.inputElem.focus() + + def onDocumentKeyDown(self, event): + if html5.isEscape(event): + event.stopPropagation() + event.preventDefault() + self.onCancel() + + def onOkay(self, *args, **kwargs): + if self.successHandler: + self.successHandler(self, self.inputElem["value"]) + self.close() + + def onCancel(self, *args, **kwargs): + if self.abortHandler: + self.abortHandler(self, self.inputElem["value"]) + self.close() diff --git a/testbed/lark-parser__lark/docs/ide/app/files.json b/testbed/lark-parser__lark/docs/ide/app/files.json new file mode 100644 index 0000000000000000000000000000000000000000..b23089995a2e9d1fb0c0f830c3366fb48b51d3ad --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/files.json @@ -0,0 +1,9 @@ +[ + "app.py", + "examples.py", + "html5.py", + "core.py", + "ext.py", + "ignite.py", + "utils.py" +] \ No newline at end of file diff --git a/testbed/lark-parser__lark/docs/ide/app/html5.py b/testbed/lark-parser__lark/docs/ide/app/html5.py new file mode 100644 index 0000000000000000000000000000000000000000..b62a821bf0d734638a107e9db470d30241ebef96 --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/html5.py @@ -0,0 +1,6 @@ +#-*- coding: utf-8 -*- + +from .core import * +from . import ext, utils, ignite + + diff --git a/testbed/lark-parser__lark/docs/ide/app/ignite.py b/testbed/lark-parser__lark/docs/ide/app/ignite.py new file mode 100644 index 0000000000000000000000000000000000000000..61c10a068eeffcd6b5751ab1b079e1d1a5fd7f59 --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/ignite.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +from . import core as html5 + + +@html5.tag +class Label(html5.Label): + _parserTagName = "ignite-label" + + def __init__(self, *args, **kwargs): + super(Label, self).__init__(style="label ignt-label", *args, **kwargs) + + +@html5.tag +class Input(html5.Input): + _parserTagName = "ignite-input" + + def __init__(self, *args, **kwargs): + super(Input, self).__init__(style="input ignt-input", *args, **kwargs) + + +@html5.tag +class Switch(html5.Div): + _parserTagName = "ignite-switch" + + def __init__(self, *args, **kwargs): + super(Switch, self).__init__(style="switch ignt-switch", *args, **kwargs) + + self.input = html5.Input(style="switch-input") + self.appendChild(self.input) + self.input["type"] = "checkbox" + + switchLabel = html5.Label(forElem=self.input) + switchLabel.addClass("switch-label") + self.appendChild(switchLabel) + + def _setChecked(self, value): + self.input["checked"] = bool(value) + + def _getChecked(self): + return self.input["checked"] + + +@html5.tag +class Check(html5.Input): + _parserTagName = "ignite-check" + + def __init__(self, *args, **kwargs): + super(Check, self).__init__(style="check ignt-check", *args, **kwargs) + + checkInput = html5.Input() + checkInput.addClass("check-input") + checkInput["type"] = "checkbox" + self.appendChild(checkInput) + + checkLabel = html5.Label(forElem=checkInput) + checkLabel.addClass("check-label") + self.appendChild(checkLabel) + + +@html5.tag +class Radio(html5.Div): + _parserTagName = "ignite-radio" + + def __init__(self, *args, **kwargs): + super(Radio, self).__init__(style="radio ignt-radio", *args, **kwargs) + + radioInput = html5.Input() + radioInput.addClass("radio-input") + radioInput["type"] = "radio" + self.appendChild(radioInput) + + radioLabel = html5.Label(forElem=radioInput) + radioLabel.addClass("radio-label") + self.appendChild(radioLabel) + + +@html5.tag +class Select(html5.Select): + _parserTagName = "ignite-select" + + def __init__(self, *args, **kwargs): + super(Select, self).__init__(style="select ignt-select", *args, **kwargs) + + defaultOpt = html5.Option() + defaultOpt["selected"] = True + defaultOpt["disabled"] = True + defaultOpt.element.innerHTML = "" + self.appendChild(defaultOpt) + + +@html5.tag +class Textarea(html5.Textarea): + _parserTagName = "ignite-textarea" + + def __init__(self, *args, **kwargs): + super(Textarea, self).__init__(style="textarea ignt-textarea", *args, **kwargs) + + +@html5.tag +class Progress(html5.Progress): + _parserTagName = "ignite-progress" + + def __init__(self, *args, **kwargs): + super(Progress, self).__init__(style="progress ignt-progress", *args, **kwargs) + + +@html5.tag +class Item(html5.Div): + _parserTagName = "ignite-item" + + def __init__(self, title=None, descr=None, className=None, *args, **kwargs): + super(Item, self).__init__(style="item ignt-item", *args, **kwargs) + if className: + self.addClass(className) + + self.fromHTML(""" +
+
+
+
+
+
+ """) + + if title: + self.itemHeadline.appendChild(html5.TextNode(title)) + + if descr: + self.itemSubline = html5.Div() + self.addClass("item-subline ignt-item-subline") + self.itemSubline.appendChild(html5.TextNode(descr)) + self.appendChild(self.itemSubline) + + +@html5.tag +class Table(html5.Table): + _parserTagName = "ignite-table" + + def __init__(self, *args, **kwargs): + super(Table, self).__init__(*args, **kwargs) + self.head.addClass("ignt-table-head") + self.body.addClass("ignt-table-body") + + def prepareRow(self, row): + assert row >= 0, "Cannot create rows with negative index" + + for child in self.body._children: + row -= child["rowspan"] + if row < 0: + return + + while row >= 0: + tableRow = html5.Tr() + tableRow.addClass("ignt-table-body-row") + self.body.appendChild(tableRow) + row -= 1 + + def prepareCol(self, row, col): + assert col >= 0, "Cannot create cols with negative index" + self.prepareRow(row) + + for rowChild in self.body._children: + row -= rowChild["rowspan"] + + if row < 0: + for colChild in rowChild._children: + col -= colChild["colspan"] + if col < 0: + return + + while col >= 0: + tableCell = html5.Td() + tableCell.addClass("ignt-table-body-cell") + rowChild.appendChild(tableCell) + col -= 1 + + return + def fastGrid( self, rows, cols, createHidden=False ): + colsstr = "".join(['' for i in range(0, cols)]) + tblstr = '' + + for r in range(0, rows): + tblstr += '%s' %("is-hidden" if createHidden else "",colsstr) + tblstr +="" + + self.fromHTML(tblstr) diff --git a/testbed/lark-parser__lark/docs/ide/app/utils.py b/testbed/lark-parser__lark/docs/ide/app/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d80f67270a515ae2fd7873cfd7669687b3fcb995 --- /dev/null +++ b/testbed/lark-parser__lark/docs/ide/app/utils.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +from . import core as html5 + +def unescape(val, maxLength = 0): + """ + Unquotes several HTML-quoted characters in a string. + + :param val: The value to be unescaped. + :type val: str + + :param maxLength: Cut-off after maxLength characters. + A value of 0 means "unlimited". (default) + :type maxLength: int + + :returns: The unquoted string. + :rtype: str + """ + val = val \ + .replace("<", "<") \ + .replace(">", ">") \ + .replace(""", "\"") \ + .replace("'", "'") + + if maxLength > 0: + return val[0:maxLength] + + return val + +def doesEventHitWidgetOrParents(event, widget): + """ + Test if event 'event' hits widget 'widget' (or *any* of its parents) + """ + while widget: + if event.target == widget.element: + return widget + + widget = widget.parent() + + return None + +def doesEventHitWidgetOrChildren(event, widget): + """ + Test if event 'event' hits widget 'widget' (or *any* of its children) + """ + if event.target == widget.element: + return widget + + for child in widget.children(): + if doesEventHitWidgetOrChildren(event, child): + return child + + return None + +def textToHtml(node, text): + """ + Generates html nodes from text by splitting text into content and into + line breaks html5.Br. + + :param node: The node where the nodes are appended to. + :param text: The text to be inserted. + """ + + for (i, part) in enumerate(text.split("\n")): + if i > 0: + node.appendChild(html5.Br()) + + node.appendChild(html5.TextNode(part)) + +def parseInt(s, ret = 0): + """ + Parses a value as int + """ + if not isinstance(s, str): + return int(s) + elif s: + if s[0] in "+-": + ts = s[1:] + else: + ts = s + + if ts and all([_ in "0123456789" for _ in ts]): + return int(s) + + return ret + +def parseFloat(s, ret = 0.0): + """ + Parses a value as float. + """ + if not isinstance(s, str): + return float(s) + elif s: + if s[0] in "+-": + ts = s[1:] + else: + ts = s + + if ts and ts.count(".") <= 1 and all([_ in ".0123456789" for _ in ts]): + return float(s) + + return ret diff --git a/testbed/lark-parser__lark/docs/index.rst b/testbed/lark-parser__lark/docs/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..9bef29dfeff248197e4ad4345d709b9778c6e165 --- /dev/null +++ b/testbed/lark-parser__lark/docs/index.rst @@ -0,0 +1,117 @@ +.. Lark documentation master file, created by + sphinx-quickstart on Sun Aug 16 13:09:41 2020. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Lark's documentation! +================================ + +.. toctree:: + :maxdepth: 2 + :caption: Overview + :hidden: + + philosophy + features + parsers + +.. toctree:: + :maxdepth: 2 + :caption: Tutorials & Guides + :hidden: + + json_tutorial + how_to_use + how_to_develop + recipes + examples/index + + +.. toctree:: + :maxdepth: 2 + :caption: Reference + :hidden: + + grammar + tree_construction + classes + visitors + forest + nearley + + + +Lark is a modern parsing library for Python. Lark can parse any context-free grammar. + +Lark provides: + +- Advanced grammar language, based on EBNF +- Three parsing algorithms to choose from: Earley, LALR(1) and CYK +- Automatic tree construction, inferred from your grammar +- Fast unicode lexer with regexp support, and automatic line-counting + + +Install Lark +-------------- + +.. code:: bash + + $ pip install lark-parser + +Syntax Highlighting +------------------- + +- `Sublime Text & TextMate`_ +- `Visual Studio Code`_ (Or install through the vscode plugin system) +- `Intellij & PyCharm`_ +- `Vim`_ + +.. _Sublime Text & TextMate: https://github.com/lark-parser/lark_syntax +.. _Visual Studio Code: https://github.com/lark-parser/vscode-lark +.. _Intellij & PyCharm: https://github.com/lark-parser/intellij-syntax-highlighting +.. _Vim: https://github.com/lark-parser/vim-lark-syntax + +Resources +--------- + +- :doc:`philosophy` +- :doc:`features` +- `Examples`_ +- `Online IDE`_ +- Tutorials + + - `How to write a DSL`_ - Implements a toy LOGO-like language with + an interpreter + - :doc:`json_tutorial` - Teaches you how to use Lark + - Unofficial + + - `Program Synthesis is Possible`_ - Creates a DSL for Z3 + +- Guides + + - :doc:`how_to_use` + - :doc:`how_to_develop` + +- Reference + + - :doc:`grammar` + - :doc:`tree_construction` + - :doc:`visitors` + - :doc:`forest` + - :doc:`classes` + - :doc:`nearley` + - `Cheatsheet (PDF)`_ + +- Discussion + + - `Gitter`_ + - `Forum (Google Groups)`_ + + +.. _Examples: https://github.com/lark-parser/lark/tree/master/examples +.. _Online IDE: https://lark-parser.github.io/lark/ide/app.html +.. _How to write a DSL: http://blog.erezsh.com/how-to-write-a-dsl-in-python-with-lark/ +.. _Program Synthesis is Possible: https://www.cs.cornell.edu/~asampson/blog/minisynth.html +.. _Cheatsheet (PDF): _static/lark_cheatsheet.pdf +.. _Gitter: https://gitter.im/lark-parser/Lobby +.. _Forum (Google Groups): https://groups.google.com/forum/#!forum/lark-parser diff --git a/testbed/lark-parser__lark/docs/json_tutorial.md b/testbed/lark-parser__lark/docs/json_tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..2c46606cb1e316d03dc08625265b78602d7316e5 --- /dev/null +++ b/testbed/lark-parser__lark/docs/json_tutorial.md @@ -0,0 +1,448 @@ +# JSON parser - Tutorial + +Lark is a parser - a program that accepts a grammar and text, and produces a structured tree that represents that text. +In this tutorial we will write a JSON parser in Lark, and explore Lark's various features in the process. + +It has 5 parts. + + 1. Writing the grammar + 2. Creating the parser + 3. Shaping the tree + 4. Evaluating the tree + 5. Optimizing + +Knowledge assumed: +- Using Python +- A basic understanding of how to use regular expressions + +## Part 1 - The Grammar + +Lark accepts its grammars in a format called [EBNF](https://www.wikiwand.com/en/Extended_Backus%E2%80%93Naur_form). It basically looks like this: + + rule_name : list of rules and TERMINALS to match + | another possible list of items + | etc. + + TERMINAL: "some text to match" + +(*a terminal is a string or a regular expression*) + +The parser will try to match each rule (left-part) by matching its items (right-part) sequentially, trying each alternative (In practice, the parser is predictive so we don't have to try every alternative). + +How to structure those rules is beyond the scope of this tutorial, but often it's enough to follow one's intuition. + +In the case of JSON, the structure is simple: A json document is either a list, or a dictionary, or a string/number/etc. + +The dictionaries and lists are recursive, and contain other json documents (or "values"). + +Let's write this structure in EBNF form: + + value: dict + | list + | STRING + | NUMBER + | "true" | "false" | "null" + + list : "[" [value ("," value)*] "]" + + dict : "{" [pair ("," pair)*] "}" + pair : STRING ":" value + + +A quick explanation of the syntax: + - Parenthesis let us group rules together. + - rule\* means *any amount*. That means, zero or more instances of that rule. + - [rule] means *optional*. That means zero or one instance of that rule. + +Lark also supports the rule+ operator, meaning one or more instances. It also supports the rule? operator which is another way to say *optional*. + +Of course, we still haven't defined "STRING" and "NUMBER". Luckily, both these literals are already defined in Lark's common library: + + %import common.ESCAPED_STRING -> STRING + %import common.SIGNED_NUMBER -> NUMBER + +The arrow (->) renames the terminals. But that only adds obscurity in this case, so going forward we'll just use their original names. + +We'll also take care of the white-space, which is part of the text. + + %import common.WS + %ignore WS + +We tell our parser to ignore whitespace. Otherwise, we'd have to fill our grammar with WS terminals. + +By the way, if you're curious what these terminals signify, they are roughly equivalent to this: + + NUMBER : /-?\d+(\.\d+)?([eE][+-]?\d+)?/ + STRING : /".*?(?>> text = '{"key": ["item0", "item1", 3.14]}' +>>> json_parser.parse(text) +Tree(value, [Tree(dict, [Tree(pair, [Token(STRING, "key"), Tree(value, [Tree(list, [Tree(value, [Token(STRING, "item0")]), Tree(value, [Token(STRING, "item1")]), Tree(value, [Token(NUMBER, 3.14)])])])])])]) +>>> print( _.pretty() ) +value + dict + pair + "key" + value + list + value "item0" + value "item1" + value 3.14 +``` + +As promised, Lark automagically creates a tree that represents the parsed text. + +But something is suspiciously missing from the tree. Where are the curly braces, the commas and all the other punctuation literals? + +Lark automatically filters out literals from the tree, based on the following criteria: + +- Filter out string literals without a name, or with a name that starts with an underscore. +- Keep regexps, even unnamed ones, unless their name starts with an underscore. + +Unfortunately, this means that it will also filter out literals like "true" and "false", and we will lose that information. The next section, "Shaping the tree" deals with this issue, and others. + +## Part 3 - Shaping the Tree + +We now have a parser that can create a parse tree (or: AST), but the tree has some issues: + +1. "true", "false" and "null" are filtered out (test it out yourself!) +2. Is has useless branches, like *value*, that clutter-up our view. + +I'll present the solution, and then explain it: + + ?value: dict + | list + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + + ... + + string : ESCAPED_STRING + +1. Those little arrows signify *aliases*. An alias is a name for a specific part of the rule. In this case, we will name the *true/false/null* matches, and this way we won't lose the information. We also alias *SIGNED_NUMBER* to mark it for later processing. + +2. The question-mark prefixing *value* ("?value") tells the tree-builder to inline this branch if it has only one member. In this case, *value* will always have only one member, and will always be inlined. + +3. We turned the *ESCAPED_STRING* terminal into a rule. This way it will appear in the tree as a branch. This is equivalent to aliasing (like we did for the number), but now *string* can also be used elsewhere in the grammar (namely, in the *pair* rule). + +Here is the new grammar: + +```python +from lark import Lark +json_parser = Lark(r""" + ?value: dict + | list + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + + list : "[" [value ("," value)*] "]" + + dict : "{" [pair ("," pair)*] "}" + pair : string ":" value + + string : ESCAPED_STRING + + %import common.ESCAPED_STRING + %import common.SIGNED_NUMBER + %import common.WS + %ignore WS + + """, start='value') +``` + +And let's test it out: + +```python +>>> text = '{"key": ["item0", "item1", 3.14, true]}' +>>> print( json_parser.parse(text).pretty() ) +dict + pair + string "key" + list + string "item0" + string "item1" + number 3.14 + true +``` + +Ah! That is much much nicer. + +## Part 4 - Evaluating the tree + +It's nice to have a tree, but what we really want is a JSON object. + +The way to do it is to evaluate the tree, using a Transformer. + +A transformer is a class with methods corresponding to branch names. For each branch, the appropriate method will be called with the children of the branch as its argument, and its return value will replace the branch in the tree. + +So let's write a partial transformer, that handles lists and dictionaries: + +```python +from lark import Transformer + +class MyTransformer(Transformer): + def list(self, items): + return list(items) + def pair(self, key_value): + k, v = key_value + return k, v + def dict(self, items): + return dict(items) +``` + +And when we run it, we get this: +```python +>>> tree = json_parser.parse(text) +>>> MyTransformer().transform(tree) +{Tree(string, [Token(ANONRE_1, "key")]): [Tree(string, [Token(ANONRE_1, "item0")]), Tree(string, [Token(ANONRE_1, "item1")]), Tree(number, [Token(ANONRE_0, 3.14)]), Tree(true, [])]} +``` + +This is pretty close. Let's write a full transformer that can handle the terminals too. + +Also, our definitions of list and dict are a bit verbose. We can do better: + +```python +from lark import Transformer + +class TreeToJson(Transformer): + def string(self, s): + (s,) = s + return s[1:-1] + def number(self, n): + (n,) = n + return float(n) + + list = list + pair = tuple + dict = dict + + null = lambda self, _: None + true = lambda self, _: True + false = lambda self, _: False +``` + +And when we run it: + +```python +>>> tree = json_parser.parse(text) +>>> TreeToJson().transform(tree) +{u'key': [u'item0', u'item1', 3.14, True]} +``` +Magic! + +## Part 5 - Optimizing + +### Step 1 - Benchmark + +By now, we have a fully working JSON parser, that can accept a string of JSON, and return its Pythonic representation. + +But how fast is it? + +Now, of course there are JSON libraries for Python written in C, and we can never compete with them. But since this is applicable to any parser you would write in Lark, let's see how far we can take this. + +The first step for optimizing is to have a benchmark. For this benchmark I'm going to take data from [json-generator.com/](http://www.json-generator.com/). I took their default suggestion and changed it to 5000 objects. The result is a 6.6MB sparse JSON file. + +Our first program is going to be just a concatenation of everything we've done so far: + +```python +import sys +from lark import Lark, Transformer + +json_grammar = r""" + ?value: dict + | list + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + + list : "[" [value ("," value)*] "]" + + dict : "{" [pair ("," pair)*] "}" + pair : string ":" value + + string : ESCAPED_STRING + + %import common.ESCAPED_STRING + %import common.SIGNED_NUMBER + %import common.WS + %ignore WS + """ + +class TreeToJson(Transformer): + def string(self, s): + (s,) = s + return s[1:-1] + def number(self, n): + (n,) = n + return float(n) + + list = list + pair = tuple + dict = dict + + null = lambda self, _: None + true = lambda self, _: True + false = lambda self, _: False + +json_parser = Lark(json_grammar, start='value', lexer='standard') + +if __name__ == '__main__': + with open(sys.argv[1]) as f: + tree = json_parser.parse(f.read()) + print(TreeToJson().transform(tree)) +``` + +We run it and get this: + + $ time python tutorial_json.py json_data > /dev/null + + real 0m36.257s + user 0m34.735s + sys 0m1.361s + + +That's unsatisfactory time for a 6MB file. Maybe if we were parsing configuration or a small DSL, but we're trying to handle large amount of data here. + +Well, turns out there's quite a bit we can do about it! + +### Step 2 - LALR(1) + +So far we've been using the Earley algorithm, which is the default in Lark. Earley is powerful but slow. But it just so happens that our grammar is LR-compatible, and specifically LALR(1) compatible. + +So let's switch to LALR(1) and see what happens: + +```python +json_parser = Lark(json_grammar, start='value', parser='lalr') +``` + $ time python tutorial_json.py json_data > /dev/null + + real 0m7.554s + user 0m7.352s + sys 0m0.148s + +Ah, that's much better. The resulting JSON is of course exactly the same. You can run it for yourself and see. + +It's important to note that not all grammars are LR-compatible, and so you can't always switch to LALR(1). But there's no harm in trying! If Lark lets you build the grammar, it means you're good to go. + +### Step 3 - Tree-less LALR(1) + +So far, we've built a full parse tree for our JSON, and then transformed it. It's a convenient method, but it's not the most efficient in terms of speed and memory. Luckily, Lark lets us avoid building the tree when parsing with LALR(1). + +Here's the way to do it: + +```python +json_parser = Lark(json_grammar, start='value', parser='lalr', transformer=TreeToJson()) + +if __name__ == '__main__': + with open(sys.argv[1]) as f: + print( json_parser.parse(f.read()) ) +``` + +We've used the transformer we've already written, but this time we plug it straight into the parser. Now it can avoid building the parse tree, and just send the data straight into our transformer. The *parse()* method now returns the transformed JSON, instead of a tree. + +Let's benchmark it: + + real 0m4.866s + user 0m4.722s + sys 0m0.121s + +That's a measurable improvement! Also, this way is more memory efficient. Check out the benchmark table at the end to see just how much. + +As a general practice, it's recommended to work with parse trees, and only skip the tree-builder when your transformer is already working. + +### Step 4 - PyPy + +PyPy is a JIT engine for running Python, and it's designed to be a drop-in replacement. + +Lark is written purely in Python, which makes it very suitable for PyPy. + +Let's get some free performance: + + $ time pypy tutorial_json.py json_data > /dev/null + + real 0m1.397s + user 0m1.296s + sys 0m0.083s + +PyPy is awesome! + +### Conclusion + +We've brought the run-time down from 36 seconds to 1.1 seconds, in a series of small and simple steps. + +Now let's compare the benchmarks in a nicely organized table. + +I measured memory consumption using a little script called [memusg](https://gist.github.com/netj/526585) + +| Code | CPython Time | PyPy Time | CPython Mem | PyPy Mem +|:-----|:-------------|:------------|:----------|:--------- +| Lark - Earley *(with lexer)* | 42s | 4s | 1167M | 608M | +| Lark - LALR(1) | 8s | 1.53s | 453M | 266M | +| Lark - LALR(1) tree-less | 4.76s | 1.23s | 70M | 134M | +| PyParsing ([Parser](http://pyparsing.wikispaces.com/file/view/jsonParser.py)) | 32s | 3.53s | 443M | 225M | +| funcparserlib ([Parser](https://github.com/vlasovskikh/funcparserlib/blob/master/funcparserlib/tests/json.py)) | 8.5s | 1.3s | 483M | 293M | +| Parsimonious ([Parser](https://gist.githubusercontent.com/reclosedev/5222560/raw/5e97cf7eb62c3a3671885ec170577285e891f7d5/parsimonious_json.py)) | ? | 5.7s | ? | 1545M | + + +I added a few other parsers for comparison. PyParsing and funcparselib fair pretty well in their memory usage (they don't build a tree), but they can't compete with the run-time speed of LALR(1). + +These benchmarks are for Lark's alpha version. I already have several optimizations planned that will significantly improve run-time speed. + +Once again, shout-out to PyPy for being so effective. + +## Afterword + +This is the end of the tutorial. I hoped you liked it and learned a little about Lark. + +To see what else you can do with Lark, check out the [examples](examples). + +For questions or any other subject, feel free to email me at erezshin at gmail dot com. + diff --git a/testbed/lark-parser__lark/docs/make.bat b/testbed/lark-parser__lark/docs/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..4f2e2868d7e8491f540189170c20cbf499a82f4c --- /dev/null +++ b/testbed/lark-parser__lark/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=Lark + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/testbed/lark-parser__lark/docs/nearley.md b/testbed/lark-parser__lark/docs/nearley.md new file mode 100644 index 0000000000000000000000000000000000000000..4ab8595aafc88bc50cdf26d932c1b979a42e62c4 --- /dev/null +++ b/testbed/lark-parser__lark/docs/nearley.md @@ -0,0 +1,47 @@ +# Importing grammars from Nearley + +Lark comes with a tool to convert grammars from [Nearley](https://github.com/Hardmath123/nearley), a popular Earley library for Javascript. It uses [Js2Py](https://github.com/PiotrDabkowski/Js2Py) to convert and run the Javascript postprocessing code segments. + +## Requirements + +1. Install Lark with the `nearley` component: +```bash +pip install lark-parser[nearley] +``` + +2. Acquire a copy of the nearley codebase. This can be done using: +```bash +git clone https://github.com/Hardmath123/nearley +``` + +## Usage + +Here's an example of how to import nearley's calculator example into Lark: + +```bash +git clone https://github.com/Hardmath123/nearley +python -m lark.tools.nearley nearley/examples/calculator/arithmetic.ne main nearley > ncalc.py +``` + +You can use the output as a regular python module: + +```python +>>> import ncalc +>>> ncalc.parse('sin(pi/4) ^ e') +0.38981434460254655 +``` + +The Nearley converter also supports an experimental converter for newer JavaScript (ES6+), using the `--es6` flag: + +```bash +git clone https://github.com/Hardmath123/nearley +python -m lark.tools.nearley nearley/examples/calculator/arithmetic.ne main nearley --es6 > ncalc.py +``` + +## Notes + +- Lark currently cannot import templates from Nearley + +- Lark currently cannot export grammars to Nearley + +These might get added in the future, if enough users ask for them. \ No newline at end of file diff --git a/testbed/lark-parser__lark/docs/parsers.md b/testbed/lark-parser__lark/docs/parsers.md new file mode 100644 index 0000000000000000000000000000000000000000..85fd35e4e1c46cc278f0e96f1ce66e353b0df0d1 --- /dev/null +++ b/testbed/lark-parser__lark/docs/parsers.md @@ -0,0 +1,48 @@ +# Parsers +Lark implements the following parsing algorithms: Earley, LALR(1), and CYK + +## Earley + +An [Earley Parser](https://www.wikiwand.com/en/Earley_parser) is a chart parser capable of parsing any context-free grammar at O(n^3), and O(n^2) when the grammar is unambiguous. It can parse most LR grammars at O(n). Most programming languages are LR, and can be parsed at a linear time. + +Lark's Earley implementation runs on top of a skipping chart parser, which allows it to use regular expressions, instead of matching characters one-by-one. This is a huge improvement to Earley that is unique to Lark. This feature is used by default, but can also be requested explicitly using `lexer='dynamic'`. + +It's possible to bypass the dynamic lexing, and use the regular Earley parser with a traditional lexer, that tokenizes as an independent first step. Doing so will provide a speed benefit, but will tokenize without using Earley's ambiguity-resolution ability. So choose this only if you know why! Activate with `lexer='standard'` + +**SPPF & Ambiguity resolution** + +Lark implements the Shared Packed Parse Forest data-structure for the Earley parser, in order to reduce the space and computation required to handle ambiguous grammars. + +You can read more about SPPF [here](https://web.archive.org/web/20191229100607/www.bramvandersanden.com/post/2014/06/shared-packed-parse-forest) + +As a result, Lark can efficiently parse and store every ambiguity in the grammar, when using Earley. + +Lark provides the following options to combat ambiguity: + +1) Lark will choose the best derivation for you (default). Users can choose between different disambiguation strategies, and can prioritize (or demote) individual rules over others, using the rule-priority syntax. + +2) Users may choose to receive the set of all possible parse-trees (using ambiguity='explicit'), and choose the best derivation themselves. While simple and flexible, it comes at the cost of space and performance, and so it isn't recommended for highly ambiguous grammars, or very long inputs. + +3) As an advanced feature, users may use specialized visitors to iterate the SPPF themselves. + +**dynamic_complete** + +**TODO: Add documentation on dynamic_complete** + +## LALR(1) + +[LALR(1)](https://www.wikiwand.com/en/LALR_parser) is a very efficient, true-and-tested parsing algorithm. It's incredibly fast and requires very little memory. It can parse most programming languages (For example: Python and Java). + +Lark comes with an efficient implementation that outperforms every other parsing library for Python (including PLY) + +Lark extends the traditional YACC-based architecture with a *contextual lexer*, which automatically provides feedback from the parser to the lexer, making the LALR(1) algorithm stronger than ever. + +The contextual lexer communicates with the parser, and uses the parser's lookahead prediction to narrow its choice of tokens. So at each point, the lexer only matches the subgroup of terminals that are legal at that parser state, instead of all of the terminals. It’s surprisingly effective at resolving common terminal collisions, and allows to parse languages that LALR(1) was previously incapable of parsing. + +This is an improvement to LALR(1) that is unique to Lark. + +## CYK Parser + +A [CYK parser](https://www.wikiwand.com/en/CYK_algorithm) can parse any context-free grammar at O(n^3*|G|). + +Its too slow to be practical for simple grammars, but it offers good performance for highly ambiguous grammars. diff --git a/testbed/lark-parser__lark/docs/philosophy.md b/testbed/lark-parser__lark/docs/philosophy.md new file mode 100644 index 0000000000000000000000000000000000000000..a1d8f8c4cbaa262778eeaa2358c6b7b814d1bcc4 --- /dev/null +++ b/testbed/lark-parser__lark/docs/philosophy.md @@ -0,0 +1,63 @@ +# Philosophy + +Parsers are innately complicated and confusing. They're difficult to understand, difficult to write, and difficult to use. Even experts on the subject can become baffled by the nuances of these complicated state-machines. + +Lark's mission is to make the process of writing them as simple and abstract as possible, by following these design principles: + +## Design Principles + +1. Readability matters + +2. Keep the grammar clean and simple + +2. Don't force the user to decide on things that the parser can figure out on its own + +4. Usability is more important than performance + +5. Performance is still very important + +6. Follow the Zen Of Python, whenever possible and applicable + + +In accordance with these principles, I arrived at the following design choices: + +----------- + +## Design Choices + +### 1. Separation of code and grammar + +Grammars are the de-facto reference for your language, and for the structure of your parse-tree. For any non-trivial language, the conflation of code and grammar always turns out convoluted and difficult to read. + +The grammars in Lark are EBNF-inspired, so they are especially easy to read & work with. + +### 2. Always build a parse-tree (unless told not to) + +Trees are always simpler to work with than state-machines. + +1. Trees allow you to see the "state-machine" visually + +2. Trees allow your computation to be aware of previous and future states + +3. Trees allow you to process the parse in steps, instead of forcing you to do it all at once. + +And anyway, every parse-tree can be replayed as a state-machine, so there is no loss of information. + +See this answer in more detail [here](https://github.com/erezsh/lark/issues/4). + +To improve performance, you can skip building the tree for LALR(1), by providing Lark with a transformer (see the [JSON example](https://github.com/erezsh/lark/blob/master/examples/json_parser.py)). + +### 3. Earley is the default + +The Earley algorithm can accept *any* context-free grammar you throw at it (i.e. any grammar you can write in EBNF, it can parse). That makes it extremely friendly to beginners, who are not aware of the strange and arbitrary restrictions that LALR(1) places on its grammars. + +As the users grow to understand the structure of their grammar, the scope of their target language, and their performance requirements, they may choose to switch over to LALR(1) to gain a huge performance boost, possibly at the cost of some language features. + +In short, "Premature optimization is the root of all evil." + +### Other design features + +- Automatically resolve terminal collisions whenever possible + +- Automatically keep track of line & column numbers + diff --git a/testbed/lark-parser__lark/docs/recipes.md b/testbed/lark-parser__lark/docs/recipes.md new file mode 100644 index 0000000000000000000000000000000000000000..18fed3772e72cef94a09fa18a0b1c5813b0fff6f --- /dev/null +++ b/testbed/lark-parser__lark/docs/recipes.md @@ -0,0 +1,147 @@ +# Recipes + +A collection of recipes to use Lark and its various features + + +## Use a transformer to parse integer tokens + +Transformers are the common interface for processing matched rules and tokens. + +They can be used during parsing for better performance. + +```python +from lark import Lark, Transformer + +class T(Transformer): + def INT(self, tok): + "Convert the value of `tok` from string to int, while maintaining line number & column." + return tok.update(value=int(tok)) + +parser = Lark(""" +start: INT* +%import common.INT +%ignore " " +""", parser="lalr", transformer=T()) + +print(parser.parse('3 14 159')) +``` + +Prints out: + +```python +Tree(start, [Token(INT, 3), Token(INT, 14), Token(INT, 159)]) +``` + + +## Collect all comments with lexer_callbacks + +`lexer_callbacks` can be used to interface with the lexer as it generates tokens. + +It accepts a dictionary of the form + + {TOKEN_TYPE: callback} + +Where callback is of type `f(Token) -> Token` + +It only works with the standard and contextual lexers. + +This has the same effect of using a transformer, but can also process ignored tokens. + +```python +from lark import Lark + +comments = [] + +parser = Lark(""" + start: INT* + + COMMENT: /#.*/ + + %import common (INT, WS) + %ignore COMMENT + %ignore WS +""", parser="lalr", lexer_callbacks={'COMMENT': comments.append}) + +parser.parse(""" +1 2 3 # hello +# world +4 5 6 +""") + +print(comments) +``` + +Prints out: + +```python +[Token(COMMENT, '# hello'), Token(COMMENT, '# world')] +``` + +*Note: We don't have to return a token, because comments are ignored* + +## CollapseAmbiguities + +Parsing ambiguous texts with earley and `ambiguity='explicit'` produces a single tree with `_ambig` nodes to mark where the ambiguity occured. + +However, it's sometimes more convenient instead to work with a list of all possible unambiguous trees. + +Lark provides a utility transformer for that purpose: + +```python +from lark import Lark, Tree, Transformer +from lark.visitors import CollapseAmbiguities + +grammar = """ + !start: x y + + !x: "a" "b" + | "ab" + | "abc" + + !y: "c" "d" + | "cd" + | "d" + +""" +parser = Lark(grammar, ambiguity='explicit') + +t = parser.parse('abcd') +for x in CollapseAmbiguities().transform(t): + print(x.pretty()) +``` + +This prints out: + + start + x + a + b + y + c + d + + start + x ab + y cd + + start + x abc + y d + +While convenient, this should be used carefully, as highly ambiguous trees will soon create an exponential explosion of such unambiguous derivations. + + +## Keeping track of parents when visiting + +The following visitor assigns a `parent` attribute for every node in the tree. + +If your tree nodes aren't unique (if there is a shared Tree instance), the assert will fail. + +```python +class Parent(Visitor): + def __default__(self, tree): + for subtree in tree.children: + if isinstance(subtree, Tree): + assert not hasattr(subtree, 'parent') + subtree.parent = tree +``` \ No newline at end of file diff --git a/testbed/lark-parser__lark/docs/requirements.txt b/testbed/lark-parser__lark/docs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed224a60ebfe7de3aa02f86d0c10cf7da0b6eb48 --- /dev/null +++ b/testbed/lark-parser__lark/docs/requirements.txt @@ -0,0 +1,3 @@ +# https://docs.readthedocs.io/en/stable/guides/specifying-dependencies.html#specifying-a-requirements-file +sphinx-gallery +sphinx_markdown_tables \ No newline at end of file diff --git a/testbed/lark-parser__lark/docs/tree_construction.md b/testbed/lark-parser__lark/docs/tree_construction.md new file mode 100644 index 0000000000000000000000000000000000000000..50ce0ee5b8421c0188ff4eb7c900ca0aeb4321c5 --- /dev/null +++ b/testbed/lark-parser__lark/docs/tree_construction.md @@ -0,0 +1,153 @@ +# Tree Construction Reference + + +Lark builds a tree automatically based on the structure of the grammar, where each rule that is matched becomes a branch (node) in the tree, and its children are its matches, in the order of matching. + +For example, the rule `node: child1 child2` will create a tree node with two children. If it is matched as part of another rule (i.e. if it isn't the root), the new rule's tree node will become its parent. + +Using `item+` or `item*` will result in a list of items, equivalent to writing `item item item ..`. + +Using `item?` will return the item if it matched, or nothing. + +If `maybe_placeholders=False` (the default), then `[]` behaves like `()?`. + +If `maybe_placeholders=True`, then using `[item]` will return the item if it matched, or the value `None`, if it didn't. + +## Terminals + +Terminals are always values in the tree, never branches. + +Lark filters out certain types of terminals by default, considering them punctuation: + +- Terminals that won't appear in the tree are: + + - Unnamed literals (like `"keyword"` or `"+"`) + - Terminals whose name starts with an underscore (like `_DIGIT`) + +- Terminals that *will* appear in the tree are: + + - Unnamed regular expressions (like `/[0-9]/`) + - Named terminals whose name starts with a letter (like `DIGIT`) + +Note: Terminals composed of literals and other terminals always include the entire match without filtering any part. + +**Example:** +``` +start: PNAME pname + +PNAME: "(" NAME ")" +pname: "(" NAME ")" + +NAME: /\w+/ +%ignore /\s+/ +``` +Lark will parse "(Hello) (World)" as: + + start + (Hello) + pname World + +Rules prefixed with `!` will retain all their literals regardless. + + + + +**Example:** + +```perl + expr: "(" expr ")" + | NAME+ + + NAME: /\w+/ + + %ignore " " +``` + +Lark will parse "((hello world))" as: + + expr + expr + expr + "hello" + "world" + +The brackets do not appear in the tree by design. The words appear because they are matched by a named terminal. + + +## Shaping the tree + +Users can alter the automatic construction of the tree using a collection of grammar features. + + +* Rules whose name begins with an underscore will be inlined into their containing rule. + +**Example:** + +```perl + start: "(" _greet ")" + _greet: /\w+/ /\w+/ +``` + +Lark will parse "(hello world)" as: + + start + "hello" + "world" + + +* Rules that receive a question mark (?) at the beginning of their definition, will be inlined if they have a single child, after filtering. + +**Example:** + +```ruby + start: greet greet + ?greet: "(" /\w+/ ")" + | /\w+/ /\w+/ +``` + +Lark will parse "hello world (planet)" as: + + start + greet + "hello" + "world" + "planet" + +* Rules that begin with an exclamation mark will keep all their terminals (they won't get filtered). + +```perl + !expr: "(" expr ")" + | NAME+ + NAME: /\w+/ + %ignore " " +``` + +Will parse "((hello world))" as: + + expr + ( + expr + ( + expr + hello + world + ) + ) + +Using the `!` prefix is usually a "code smell", and may point to a flaw in your grammar design. + +* Aliases - options in a rule can receive an alias. It will be then used as the branch name for the option, instead of the rule name. + +**Example:** + +```ruby + start: greet greet + greet: "hello" + | "world" -> planet +``` + +Lark will parse "hello world" as: + + start + greet + planet diff --git a/testbed/lark-parser__lark/docs/visitors.rst b/testbed/lark-parser__lark/docs/visitors.rst new file mode 100644 index 0000000000000000000000000000000000000000..aa3189ef4946358082c766d7f36d0c05e9bfbf10 --- /dev/null +++ b/testbed/lark-parser__lark/docs/visitors.rst @@ -0,0 +1,102 @@ +Transformers & Visitors +======================= + +Transformers & Visitors provide a convenient interface to process the +parse-trees that Lark returns. + +They are used by inheriting from the correct class (visitor or transformer), +and implementing methods corresponding to the rule you wish to process. Each +method accepts the children as an argument. That can be modified using the +``v_args`` decorator, which allows to inline the arguments (akin to ``*args``), +or add the tree ``meta`` property as an argument. + +See: `visitors.py`_ + +.. _visitors.py: https://github.com/lark-parser/lark/blob/master/lark/visitors.py + +Visitor +------- + +Visitors visit each node of the tree, and run the appropriate method on it according to the node's data. + +They work bottom-up, starting with the leaves and ending at the root of the tree. + +There are two classes that implement the visitor interface: + +- ``Visitor``: Visit every node (without recursion) +- ``Visitor_Recursive``: Visit every node using recursion. Slightly faster. + +Example: + :: + + class IncreaseAllNumbers(Visitor): + def number(self, tree): + assert tree.data == "number" + tree.children[0] += 1 + + IncreaseAllNumbers().visit(parse_tree) + +.. autoclass:: lark.visitors.Visitor + +.. autoclass:: lark.visitors.Visitor_Recursive + +Interpreter +----------- + +.. autoclass:: lark.visitors.Interpreter + + +Example: + :: + + class IncreaseSomeOfTheNumbers(Interpreter): + def number(self, tree): + tree.children[0] += 1 + + def skip(self, tree): + # skip this subtree. don't change any number node inside it. + pass + + IncreaseSomeOfTheNumbers().visit(parse_tree) + +Transformer +----------- + +.. autoclass:: lark.visitors.Transformer + :members: __default__, __default_token__ + +Example: + :: + + from lark import Tree, Transformer + + class EvalExpressions(Transformer): + def expr(self, args): + return eval(args[0]) + + t = Tree('a', [Tree('expr', ['1+2'])]) + print(EvalExpressions().transform( t )) + + # Prints: Tree(a, [3]) + +Example: + :: + + class T(Transformer): + INT = int + NUMBER = float + def NAME(self, name): + return lookup_dict.get(name, name) + + T(visit_tokens=True).transform(tree) + + +v_args +------ + +.. autofunction:: lark.visitors.v_args + +Discard +------- + +.. autoclass:: lark.visitors.Discard \ No newline at end of file diff --git a/testbed/lark-parser__lark/examples/README.rst b/testbed/lark-parser__lark/examples/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..f2b0125f8117ad00dc48c27f639c47ea6bea9738 --- /dev/null +++ b/testbed/lark-parser__lark/examples/README.rst @@ -0,0 +1,21 @@ +Examples for Lark +================= + +**How to run the examples**: + +After cloning the repo, open the terminal into the root directory of the +project, and run the following: + +.. code:: bash + + [lark]$ python -m examples. + +For example, the following will parse all the Python files in the +standard library of your local installation: + +.. code:: bash + + [lark]$ python -m examples.python_parser + +Beginner Examples +~~~~~~~~~~~~~~~~~ diff --git a/testbed/lark-parser__lark/examples/__init__.py b/testbed/lark-parser__lark/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/lark-parser__lark/examples/advanced/README.rst b/testbed/lark-parser__lark/examples/advanced/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..96054863d999d74f127b6728c51946354e682a5e --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/README.rst @@ -0,0 +1,2 @@ +Advanced Examples +~~~~~~~~~~~~~~~~~ diff --git a/testbed/lark-parser__lark/examples/advanced/_json_parser.py b/testbed/lark-parser__lark/examples/advanced/_json_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..80d9101f9f33eaf7898e230874bb9ee97741a7a8 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/_json_parser.py @@ -0,0 +1,64 @@ +""" +Simple JSON Parser +================== + +The code is short and clear, and outperforms every other parser (that's written in Python). +For an explanation, check out the JSON parser tutorial at /docs/json_tutorial.md + +(this is here for use by the other examples) +""" +import sys + +from lark import Lark, Transformer, v_args + +json_grammar = r""" + ?start: value + + ?value: object + | array + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + + array : "[" [value ("," value)*] "]" + object : "{" [pair ("," pair)*] "}" + pair : string ":" value + + string : ESCAPED_STRING + + %import common.ESCAPED_STRING + %import common.SIGNED_NUMBER + %import common.WS + + %ignore WS +""" + + +class TreeToJson(Transformer): + @v_args(inline=True) + def string(self, s): + return s[1:-1].replace('\\"', '"') + + array = list + pair = tuple + object = dict + number = v_args(inline=True)(float) + + null = lambda self, _: None + true = lambda self, _: True + false = lambda self, _: False + + +### Create the JSON parser with Lark, using the LALR algorithm +json_parser = Lark(json_grammar, parser='lalr', + # Using the standard lexer isn't required, and isn't usually recommended. + # But, it's good enough for JSON, and it's slightly faster. + lexer='standard', + # Disabling propagate_positions and placeholders slightly improves speed + propagate_positions=False, + maybe_placeholders=False, + # Using an internal transformer is faster and more memory efficient + transformer=TreeToJson()) + diff --git a/testbed/lark-parser__lark/examples/advanced/conf_earley.py b/testbed/lark-parser__lark/examples/advanced/conf_earley.py new file mode 100644 index 0000000000000000000000000000000000000000..b21c1acb59f1c33b9beacd3d557930c6a8fe8c5f --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/conf_earley.py @@ -0,0 +1,44 @@ +""" +Earley’s dynamic lexer +====================== + +Demonstrates the power of Earley’s dynamic lexer on a toy configuration language + +Using a lexer for configuration files is tricky, because values don't +have to be surrounded by delimiters. Using a standard lexer for this just won't work. + +In this example we use a dynamic lexer and let the Earley parser resolve the ambiguity. + +Another approach is to use the contextual lexer with LALR. It is less powerful than Earley, +but it can handle some ambiguity when lexing and it's much faster. +See examples/conf_lalr.py for an example of that approach. + +""" +from lark import Lark + +parser = Lark(r""" + start: _NL? section+ + section: "[" NAME "]" _NL item+ + item: NAME "=" VALUE? _NL + VALUE: /./+ + + %import common.CNAME -> NAME + %import common.NEWLINE -> _NL + %import common.WS_INLINE + %ignore WS_INLINE + """, parser="earley") + +def test(): + sample_conf = """ +[bla] + +a=Hello +this="that",4 +empty= +""" + + r = parser.parse(sample_conf) + print (r.pretty()) + +if __name__ == '__main__': + test() diff --git a/testbed/lark-parser__lark/examples/advanced/conf_lalr.py b/testbed/lark-parser__lark/examples/advanced/conf_lalr.py new file mode 100644 index 0000000000000000000000000000000000000000..5ffd1d20be761f13476c74107ad032fa5baf4576 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/conf_lalr.py @@ -0,0 +1,40 @@ +""" +LALR’s contextual lexer +======================= + +Demonstrates the power of LALR’s contextual lexer on a toy configuration language. + +The tokens NAME and VALUE match the same input. A standard lexer would arbitrarily +choose one over the other, which would lead to a (confusing) parse error. +However, due to the unambiguous structure of the grammar, Lark's LALR(1) algorithm knows +which one of them to expect at each point during the parse. +The lexer then only matches the tokens that the parser expects. +The result is a correct parse, something that is impossible with a regular lexer. + +Another approach is to discard a lexer altogether and use the Earley algorithm. +It will handle more cases than the contextual lexer, but at the cost of performance. +See examples/conf_earley.py for an example of that approach. +""" +from lark import Lark + +parser = Lark(r""" + start: _NL? section+ + section: "[" NAME "]" _NL item+ + item: NAME "=" VALUE? _NL + VALUE: /./+ + + %import common.CNAME -> NAME + %import common.NEWLINE -> _NL + %import common.WS_INLINE + %ignore WS_INLINE + """, parser="lalr") + + +sample_conf = """ +[bla] +a=Hello +this="that",4 +empty= +""" + +print(parser.parse(sample_conf).pretty()) diff --git a/testbed/lark-parser__lark/examples/advanced/custom_lexer.py b/testbed/lark-parser__lark/examples/advanced/custom_lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..05a5eb5e979d1f7e87c4249a4a8ab44ff10e20f0 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/custom_lexer.py @@ -0,0 +1,57 @@ +""" +Custom lexer +============ + +Demonstrates using a custom lexer to parse a non-textual stream of data + +You can use a custom lexer to tokenize text when the lexers offered by Lark +are too slow, or not flexible enough. + +You can also use it (as shown in this example) to tokenize streams of objects. +""" +from lark import Lark, Transformer, v_args +from lark.lexer import Lexer, Token + +class TypeLexer(Lexer): + def __init__(self, lexer_conf): + pass + + def lex(self, data): + for obj in data: + if isinstance(obj, int): + yield Token('INT', obj) + elif isinstance(obj, (type(''), type(u''))): + yield Token('STR', obj) + else: + raise TypeError(obj) + +parser = Lark(""" + start: data_item+ + data_item: STR INT* + + %declare STR INT + """, parser='lalr', lexer=TypeLexer) + + +class ParseToDict(Transformer): + @v_args(inline=True) + def data_item(self, name, *numbers): + return name.value, [n.value for n in numbers] + + start = dict + + +def test(): + data = ['alice', 1, 27, 3, 'bob', 4, 'carrie', 'dan', 8, 6] + + print(data) + + tree = parser.parse(data) + res = ParseToDict().transform(tree) + + print('-->') + print(res) # prints {'alice': [1, 27, 3], 'bob': [4], 'carrie': [], 'dan': [8, 6]} + + +if __name__ == '__main__': + test() diff --git a/testbed/lark-parser__lark/examples/advanced/error_puppet.py b/testbed/lark-parser__lark/examples/advanced/error_puppet.py new file mode 100644 index 0000000000000000000000000000000000000000..36c14c4eac75d77582ee6310fcf7183c41f118cf --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/error_puppet.py @@ -0,0 +1,37 @@ +""" +Error handling with a puppet +================================== + +This example demonstrates error handling using a parsing puppet in LALR + +When the parser encounters an UnexpectedToken exception, it creates a +parsing puppet with the current parse-state, and lets you control how +to proceed step-by-step. When you've achieved the correct parse-state, +you can resume the run by returning True. +""" + +from lark import Token + +from _json_parser import json_parser + +def ignore_errors(e): + if e.token.type == 'COMMA': + # Skip comma + return True + elif e.token.type == 'SIGNED_NUMBER': + # Try to feed a comma and retry the number + e.puppet.feed_token(Token('COMMA', ',')) + e.puppet.feed_token(e.token) + return True + + # Unhandled error. Will stop parse and raise exception + return False + + +def main(): + s = "[0 1, 2,, 3,,, 4, 5 6 ]" + res = json_parser.parse(s, on_error=ignore_errors) + print(res) # prints [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + +main() + diff --git a/testbed/lark-parser__lark/examples/advanced/error_reporting_lalr.py b/testbed/lark-parser__lark/examples/advanced/error_reporting_lalr.py new file mode 100644 index 0000000000000000000000000000000000000000..102f7b195c96e60bc186de271948811b4ba26e9c --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/error_reporting_lalr.py @@ -0,0 +1,79 @@ +""" +Example-Driven Error Reporting +============================== + +A demonstration of example-driven error reporting with the LALR parser + +""" +from lark import Lark, UnexpectedInput + +from _json_parser import json_grammar # Using the grammar from the json_parser example + +json_parser = Lark(json_grammar, parser='lalr') + +class JsonSyntaxError(SyntaxError): + def __str__(self): + context, line, column = self.args + return '%s at line %s, column %s.\n\n%s' % (self.label, line, column, context) + +class JsonMissingValue(JsonSyntaxError): + label = 'Missing Value' + +class JsonMissingOpening(JsonSyntaxError): + label = 'Missing Opening' + +class JsonMissingClosing(JsonSyntaxError): + label = 'Missing Closing' + +class JsonMissingComma(JsonSyntaxError): + label = 'Missing Comma' + +class JsonTrailingComma(JsonSyntaxError): + label = 'Trailing Comma' + + +def parse(json_text): + try: + j = json_parser.parse(json_text) + except UnexpectedInput as u: + exc_class = u.match_examples(json_parser.parse, { + JsonMissingOpening: ['{"foo": ]}', + '{"foor": }}', + '{"foo": }'], + JsonMissingClosing: ['{"foo": [}', + '{', + '{"a": 1', + '[1'], + JsonMissingComma: ['[1 2]', + '[false 1]', + '["b" 1]', + '{"a":true 1:4}', + '{"a":1 1:4}', + '{"a":"b" 1:4}'], + JsonTrailingComma: ['[,]', + '[1,]', + '[1,2,]', + '{"foo":1,}', + '{"foo":false,"bar":true,}'] + }, use_accepts=True) + if not exc_class: + raise + raise exc_class(u.get_context(json_text), u.line, u.column) + + +def test(): + try: + parse('{"example1": "value"') + except JsonMissingClosing as e: + print(e) + + try: + parse('{"example2": ] ') + except JsonMissingOpening as e: + print(e) + + +if __name__ == '__main__': + test() + + diff --git a/testbed/lark-parser__lark/examples/advanced/prioritizer.py b/testbed/lark-parser__lark/examples/advanced/prioritizer.py new file mode 100644 index 0000000000000000000000000000000000000000..f97a1d117d7388145cae10266c51d866816bab67 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/prioritizer.py @@ -0,0 +1,72 @@ +""" +Custom SPPF Prioritizer +======================= + +This example demonstrates how to subclass ``ForestVisitor`` to make a custom +SPPF node prioritizer to be used in conjunction with ``TreeForestTransformer``. + +Our prioritizer will count the number of descendants of a node that are tokens. +By negating this count, our prioritizer will prefer nodes with fewer token +descendants. Thus, we choose the more specific parse. +""" + +from lark import Lark +from lark.parsers.earley_forest import ForestVisitor, TreeForestTransformer + +class TokenPrioritizer(ForestVisitor): + + def visit_symbol_node_in(self, node): + # visit the entire forest by returning node.children + return node.children + + def visit_packed_node_in(self, node): + return node.children + + def visit_symbol_node_out(self, node): + priority = 0 + for child in node.children: + # Tokens do not have a priority attribute + # count them as -1 + priority += getattr(child, 'priority', -1) + node.priority = priority + + def visit_packed_node_out(self, node): + priority = 0 + for child in node.children: + priority += getattr(child, 'priority', -1) + node.priority = priority + + def on_cycle(self, node, path): + raise Exception("Oops, we encountered a cycle.") + +grammar = """ +start: hello " " world | hello_world +hello: "Hello" +world: "World" +hello_world: "Hello World" +""" + +parser = Lark(grammar, parser='earley', ambiguity='forest') +forest = parser.parse("Hello World") + +print("Default prioritizer:") +tree = TreeForestTransformer(resolve_ambiguity=True).transform(forest) +print(tree.pretty()) + +forest = parser.parse("Hello World") + +print("Custom prioritizer:") +tree = TreeForestTransformer(resolve_ambiguity=True, prioritizer=TokenPrioritizer()).transform(forest) +print(tree.pretty()) + +# Output: +# +# Default prioritizer: +# start +# hello Hello +# +# world World +# +# Custom prioritizer: +# start +# hello_world Hello World diff --git a/testbed/lark-parser__lark/examples/advanced/python2.lark b/testbed/lark-parser__lark/examples/advanced/python2.lark new file mode 100644 index 0000000000000000000000000000000000000000..6fbae459853b46211972529ec189283a12fcf282 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/python2.lark @@ -0,0 +1,168 @@ +// Python 2 grammar for Lark + +// NOTE: Work in progress!!! (XXX TODO) +// This grammar should parse all python 2.x code successfully, +// but the resulting parse-tree is still not well-organized. + +// Adapted from: https://docs.python.org/2/reference/grammar.html +// Adapted by: Erez Shinan + +// Start symbols for the grammar: +// single_input is a single interactive statement; +// file_input is a module or sequence of commands read from an input file; +// eval_input is the input for the eval() and input() functions. +// NB: compound_stmt in single_input is followed by extra _NEWLINE! +single_input: _NEWLINE | simple_stmt | compound_stmt _NEWLINE +?file_input: (_NEWLINE | stmt)* +eval_input: testlist _NEWLINE? + +decorator: "@" dotted_name [ "(" [arglist] ")" ] _NEWLINE +decorators: decorator+ +decorated: decorators (classdef | funcdef) +funcdef: "def" NAME "(" parameters ")" ":" suite +parameters: [paramlist] +paramlist: param ("," param)* ["," [star_params ["," kw_params] | kw_params]] + | star_params ["," kw_params] + | kw_params +star_params: "*" NAME +kw_params: "**" NAME +param: fpdef ["=" test] +fpdef: NAME | "(" fplist ")" +fplist: fpdef ("," fpdef)* [","] + +?stmt: simple_stmt | compound_stmt +?simple_stmt: small_stmt (";" small_stmt)* [";"] _NEWLINE +?small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt + | import_stmt | global_stmt | exec_stmt | assert_stmt) +expr_stmt: testlist augassign (yield_expr|testlist) -> augassign2 + | testlist ("=" (yield_expr|testlist))+ -> assign + | testlist + +augassign: ("+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "**=" | "//=") +// For normal assignments, additional restrictions enforced by the interpreter +print_stmt: "print" ( [ test ("," test)* [","] ] | ">>" test [ ("," test)+ [","] ] ) +del_stmt: "del" exprlist +pass_stmt: "pass" +?flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt +break_stmt: "break" +continue_stmt: "continue" +return_stmt: "return" [testlist] +yield_stmt: yield_expr +raise_stmt: "raise" [test ["," test ["," test]]] +import_stmt: import_name | import_from +import_name: "import" dotted_as_names +import_from: "from" ("."* dotted_name | "."+) "import" ("*" | "(" import_as_names ")" | import_as_names) +?import_as_name: NAME ["as" NAME] +?dotted_as_name: dotted_name ["as" NAME] +import_as_names: import_as_name ("," import_as_name)* [","] +dotted_as_names: dotted_as_name ("," dotted_as_name)* +dotted_name: NAME ("." NAME)* +global_stmt: "global" NAME ("," NAME)* +exec_stmt: "exec" expr ["in" test ["," test]] +assert_stmt: "assert" test ["," test] + +?compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated +if_stmt: "if" test ":" suite ("elif" test ":" suite)* ["else" ":" suite] +while_stmt: "while" test ":" suite ["else" ":" suite] +for_stmt: "for" exprlist "in" testlist ":" suite ["else" ":" suite] +try_stmt: ("try" ":" suite ((except_clause ":" suite)+ ["else" ":" suite] ["finally" ":" suite] | "finally" ":" suite)) +with_stmt: "with" with_item ("," with_item)* ":" suite +with_item: test ["as" expr] +// NB compile.c makes sure that the default except clause is last +except_clause: "except" [test [("as" | ",") test]] +suite: simple_stmt | _NEWLINE _INDENT _NEWLINE? stmt+ _DEDENT _NEWLINE? + +// Backward compatibility cruft to support: +// [ x for x in lambda: True, lambda: False if x() ] +// even while also allowing: +// lambda x: 5 if x else 2 +// (But not a mix of the two) +testlist_safe: old_test [("," old_test)+ [","]] +old_test: or_test | old_lambdef +old_lambdef: "lambda" [paramlist] ":" old_test + +?test: or_test ["if" or_test "else" test] | lambdef +?or_test: and_test ("or" and_test)* +?and_test: not_test ("and" not_test)* +?not_test: "not" not_test | comparison +?comparison: expr (comp_op expr)* +comp_op: "<"|">"|"=="|">="|"<="|"<>"|"!="|"in"|"not" "in"|"is"|"is" "not" +?expr: xor_expr ("|" xor_expr)* +?xor_expr: and_expr ("^" and_expr)* +?and_expr: shift_expr ("&" shift_expr)* +?shift_expr: arith_expr (("<<"|">>") arith_expr)* +?arith_expr: term (("+"|"-") term)* +?term: factor (("*"|"/"|"%"|"//") factor)* +?factor: ("+"|"-"|"~") factor | power +?power: molecule ["**" factor] +// _trailer: "(" [arglist] ")" | "[" subscriptlist "]" | "." NAME +?molecule: molecule "(" [arglist] ")" -> func_call + | molecule "[" [subscriptlist] "]" -> getitem + | molecule "." NAME -> getattr + | atom +?atom: "(" [yield_expr|testlist_comp] ")" -> tuple + | "[" [listmaker] "]" + | "{" [dictorsetmaker] "}" + | "`" testlist1 "`" + | "(" test ")" + | NAME | number | string+ +listmaker: test ( list_for | ("," test)* [","] ) +?testlist_comp: test ( comp_for | ("," test)+ [","] | ",") +lambdef: "lambda" [paramlist] ":" test +?subscriptlist: subscript ("," subscript)* [","] +subscript: "." "." "." | test | [test] ":" [test] [sliceop] +sliceop: ":" [test] +?exprlist: expr ("," expr)* [","] +?testlist: test ("," test)* [","] +dictorsetmaker: ( (test ":" test (comp_for | ("," test ":" test)* [","])) | (test (comp_for | ("," test)* [","])) ) + +classdef: "class" NAME ["(" [testlist] ")"] ":" suite + +arglist: (argument ",")* (argument [","] + | star_args ["," kw_args] + | kw_args) + +star_args: "*" test +kw_args: "**" test + + +// The reason that keywords are test nodes instead of NAME is that using NAME +// results in an ambiguity. ast.c makes sure it's a NAME. +argument: test [comp_for] | test "=" test + +list_iter: list_for | list_if +list_for: "for" exprlist "in" testlist_safe [list_iter] +list_if: "if" old_test [list_iter] + +comp_iter: comp_for | comp_if +comp_for: "for" exprlist "in" or_test [comp_iter] +comp_if: "if" old_test [comp_iter] + +testlist1: test ("," test)* + +yield_expr: "yield" [testlist] + +number: DEC_NUMBER | HEX_NUMBER | OCT_NUMBER | FLOAT | IMAG_NUMBER +string: STRING | LONG_STRING +// Tokens + +COMMENT: /#[^\n]*/ +_NEWLINE: ( /\r?\n[\t ]*/ | COMMENT )+ + +STRING : /[ubf]?r?("(?!"").*?(? FLOAT +%import common.INT -> _INT +%import common.CNAME -> NAME +IMAG_NUMBER: (_INT | FLOAT) ("j"|"J") + + +%ignore /[\t \f]+/ // WS +%ignore /\\[\t \f]*\r?\n/ // LINE_CONT +%ignore COMMENT +%declare _INDENT _DEDENT + diff --git a/testbed/lark-parser__lark/examples/advanced/python3.lark b/testbed/lark-parser__lark/examples/advanced/python3.lark new file mode 100644 index 0000000000000000000000000000000000000000..78c98753dc7c4fbec4766748092786f7be7a13c1 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/python3.lark @@ -0,0 +1,187 @@ +// Python 3 grammar for Lark + +// NOTE: Work in progress!!! (XXX TODO) +// This grammar should parse all python 3.x code successfully, +// but the resulting parse-tree is still not well-organized. + +// Adapted from: https://docs.python.org/3/reference/grammar.html +// Adapted by: Erez Shinan + +// Start symbols for the grammar: +// single_input is a single interactive statement; +// file_input is a module or sequence of commands read from an input file; +// eval_input is the input for the eval() functions. +// NB: compound_stmt in single_input is followed by extra NEWLINE! +single_input: _NEWLINE | simple_stmt | compound_stmt _NEWLINE +file_input: (_NEWLINE | stmt)* +eval_input: testlist _NEWLINE* + +decorator: "@" dotted_name [ "(" [arguments] ")" ] _NEWLINE +decorators: decorator+ +decorated: decorators (classdef | funcdef | async_funcdef) + +async_funcdef: "async" funcdef +funcdef: "def" NAME "(" parameters? ")" ["->" test] ":" suite + +parameters: paramvalue ("," paramvalue)* ["," [ starparams | kwparams]] + | starparams + | kwparams +starparams: "*" typedparam? ("," paramvalue)* ["," kwparams] +kwparams: "**" typedparam + +?paramvalue: typedparam ["=" test] +?typedparam: NAME [":" test] + +varargslist: (vfpdef ["=" test] ("," vfpdef ["=" test])* ["," [ "*" [vfpdef] ("," vfpdef ["=" test])* ["," ["**" vfpdef [","]]] | "**" vfpdef [","]]] + | "*" [vfpdef] ("," vfpdef ["=" test])* ["," ["**" vfpdef [","]]] + | "**" vfpdef [","]) + +vfpdef: NAME + +?stmt: simple_stmt | compound_stmt +?simple_stmt: small_stmt (";" small_stmt)* [";"] _NEWLINE +?small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt) +?expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) + | ("=" (yield_expr|testlist_star_expr))*) +annassign: ":" test ["=" test] +?testlist_star_expr: (test|star_expr) ("," (test|star_expr))* [","] +!augassign: ("+=" | "-=" | "*=" | "@=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "**=" | "//=") +// For normal and annotated assignments, additional restrictions enforced by the interpreter +del_stmt: "del" exprlist +pass_stmt: "pass" +?flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt +break_stmt: "break" +continue_stmt: "continue" +return_stmt: "return" [testlist] +yield_stmt: yield_expr +raise_stmt: "raise" [test ["from" test]] +import_stmt: import_name | import_from +import_name: "import" dotted_as_names +// note below: the ("." | "...") is necessary because "..." is tokenized as ELLIPSIS +import_from: "from" (dots? dotted_name | dots) "import" ("*" | "(" import_as_names ")" | import_as_names) +!dots: "."+ +import_as_name: NAME ["as" NAME] +dotted_as_name: dotted_name ["as" NAME] +import_as_names: import_as_name ("," import_as_name)* [","] +dotted_as_names: dotted_as_name ("," dotted_as_name)* +dotted_name: NAME ("." NAME)* +global_stmt: "global" NAME ("," NAME)* +nonlocal_stmt: "nonlocal" NAME ("," NAME)* +assert_stmt: "assert" test ["," test] + +compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt +async_stmt: "async" (funcdef | with_stmt | for_stmt) +if_stmt: "if" test ":" suite ("elif" test ":" suite)* ["else" ":" suite] +while_stmt: "while" test ":" suite ["else" ":" suite] +for_stmt: "for" exprlist "in" testlist ":" suite ["else" ":" suite] +try_stmt: ("try" ":" suite ((except_clause ":" suite)+ ["else" ":" suite] ["finally" ":" suite] | "finally" ":" suite)) +with_stmt: "with" with_item ("," with_item)* ":" suite +with_item: test ["as" expr] +// NB compile.c makes sure that the default except clause is last +except_clause: "except" [test ["as" NAME]] +suite: simple_stmt | _NEWLINE _INDENT stmt+ _DEDENT + +?test: or_test ("if" or_test "else" test)? | lambdef +?test_nocond: or_test | lambdef_nocond +lambdef: "lambda" [varargslist] ":" test +lambdef_nocond: "lambda" [varargslist] ":" test_nocond +?or_test: and_test ("or" and_test)* +?and_test: not_test ("and" not_test)* +?not_test: "not" not_test -> not + | comparison +?comparison: expr (_comp_op expr)* +star_expr: "*" expr +?expr: xor_expr ("|" xor_expr)* +?xor_expr: and_expr ("^" and_expr)* +?and_expr: shift_expr ("&" shift_expr)* +?shift_expr: arith_expr (_shift_op arith_expr)* +?arith_expr: term (_add_op term)* +?term: factor (_mul_op factor)* +?factor: _factor_op factor | power + +!_factor_op: "+"|"-"|"~" +!_add_op: "+"|"-" +!_shift_op: "<<"|">>" +!_mul_op: "*"|"@"|"/"|"%"|"//" +// <> isn't actually a valid comparison operator in Python. It's here for the +// sake of a __future__ import described in PEP 401 (which really works :-) +!_comp_op: "<"|">"|"=="|">="|"<="|"<>"|"!="|"in"|"not" "in"|"is"|"is" "not" + +?power: await_expr ("**" factor)? +?await_expr: AWAIT? atom_expr +AWAIT: "await" + +?atom_expr: atom_expr "(" [arguments] ")" -> funccall + | atom_expr "[" subscriptlist "]" -> getitem + | atom_expr "." NAME -> getattr + | atom + +?atom: "(" [yield_expr|testlist_comp] ")" -> tuple + | "[" [testlist_comp] "]" -> list + | "{" [dictorsetmaker] "}" -> dict + | NAME -> var + | number | string+ + | "(" test ")" + | "..." -> ellipsis + | "None" -> const_none + | "True" -> const_true + | "False" -> const_false + +?testlist_comp: (test|star_expr) [comp_for | ("," (test|star_expr))+ [","] | ","] +subscriptlist: subscript ("," subscript)* [","] +subscript: test | [test] ":" [test] [sliceop] +sliceop: ":" [test] +exprlist: (expr|star_expr) ("," (expr|star_expr))* [","] +testlist: test ("," test)* [","] +dictorsetmaker: ( ((test ":" test | "**" expr) (comp_for | ("," (test ":" test | "**" expr))* [","])) | ((test | star_expr) (comp_for | ("," (test | star_expr))* [","])) ) + +classdef: "class" NAME ["(" [arguments] ")"] ":" suite + +arguments: argvalue ("," argvalue)* ("," [ starargs | kwargs])? + | starargs + | kwargs + | test comp_for + +starargs: "*" test ("," "*" test)* ("," argvalue)* ["," kwargs] +kwargs: "**" test + +?argvalue: test ("=" test)? + + + +comp_iter: comp_for | comp_if | async_for +async_for: "async" "for" exprlist "in" or_test [comp_iter] +comp_for: "for" exprlist "in" or_test [comp_iter] +comp_if: "if" test_nocond [comp_iter] + +// not used in grammar, but may appear in "node" passed from Parser to Compiler +encoding_decl: NAME + +yield_expr: "yield" [yield_arg] +yield_arg: "from" test | testlist + + +number: DEC_NUMBER | HEX_NUMBER | BIN_NUMBER | OCT_NUMBER | FLOAT_NUMBER | IMAG_NUMBER +string: STRING | LONG_STRING +// Tokens + +NAME: /[a-zA-Z_]\w*/ +COMMENT: /#[^\n]*/ +_NEWLINE: ( /\r?\n[\t ]*/ | COMMENT )+ + + +STRING : /[ubf]?r?("(?!"").*?(? STRING + %import common.SIGNED_NUMBER -> NUMBER + %import common.WS + %ignore WS + ''' + + self.lark = Lark(grammar, parser=None, lexer='standard') + # All tokens: print([t.name for t in self.lark.parser.lexer.tokens]) + + def defaultPaper(self, style): + return QColor(39, 40, 34) + + def language(self): + return "Json" + + def description(self, style): + return {v: k for k, v in self.token_styles.items()}.get(style, "") + + def styleText(self, start, end): + self.startStyling(start) + text = self.parent().text()[start:end] + last_pos = 0 + + try: + for token in self.lark.lex(text): + ws_len = token.pos_in_stream - last_pos + if ws_len: + self.setStyling(ws_len, 0) # whitespace + + token_len = len(bytearray(token, "utf-8")) + self.setStyling( + token_len, self.token_styles.get(token.type, 0)) + + last_pos = token.pos_in_stream + token_len + except Exception as e: + print(e) + + +class EditorAll(QsciScintilla): + + def __init__(self, parent=None): + super().__init__(parent) + + # Set font defaults + font = QFont() + font.setFamily('Consolas') + font.setFixedPitch(True) + font.setPointSize(8) + font.setBold(True) + self.setFont(font) + + # Set margin defaults + fontmetrics = QFontMetrics(font) + self.setMarginsFont(font) + self.setMarginWidth(0, fontmetrics.width("000") + 6) + self.setMarginLineNumbers(0, True) + self.setMarginsForegroundColor(QColor(128, 128, 128)) + self.setMarginsBackgroundColor(QColor(39, 40, 34)) + self.setMarginType(1, self.SymbolMargin) + self.setMarginWidth(1, 12) + + # Set indentation defaults + self.setIndentationsUseTabs(False) + self.setIndentationWidth(4) + self.setBackspaceUnindents(True) + self.setIndentationGuides(True) + + # self.setFolding(QsciScintilla.CircledFoldStyle) + + # Set caret defaults + self.setCaretForegroundColor(QColor(247, 247, 241)) + self.setCaretWidth(2) + + # Set selection color defaults + self.setSelectionBackgroundColor(QColor(61, 61, 52)) + self.resetSelectionForegroundColor() + + # Set multiselection defaults + self.SendScintilla(QsciScintilla.SCI_SETMULTIPLESELECTION, True) + self.SendScintilla(QsciScintilla.SCI_SETMULTIPASTE, 1) + self.SendScintilla( + QsciScintilla.SCI_SETADDITIONALSELECTIONTYPING, True) + + lexer = LexerJson(self) + self.setLexer(lexer) + + +EXAMPLE_TEXT = textwrap.dedent("""\ + { + "_id": "5b05ffcbcf8e597939b3f5ca", + "about": "Excepteur consequat commodo esse voluptate aute aliquip ad sint deserunt commodo eiusmod irure. Sint aliquip sit magna duis eu est culpa aliqua excepteur ut tempor nulla. Aliqua ex pariatur id labore sit. Quis sit ex aliqua veniam exercitation laboris anim adipisicing. Lorem nisi reprehenderit ullamco labore qui sit ut aliqua tempor consequat pariatur proident.", + "address": "665 Malbone Street, Thornport, Louisiana, 243", + "age": 23, + "balance": "$3,216.91", + "company": "BULLJUICE", + "email": "elisekelley@bulljuice.com", + "eyeColor": "brown", + "gender": "female", + "guid": "d3a6d865-0f64-4042-8a78-4f53de9b0707", + "index": 0, + "isActive": false, + "isActive2": true, + "latitude": -18.660714, + "longitude": -85.378048, + "name": "Elise Kelley", + "phone": "+1 (808) 543-3966", + "picture": "http://placehold.it/32x32", + "registered": "2017-09-30T03:47:40 -02:00", + "tags": [ + "et", + "nostrud", + "in", + "fugiat", + "incididunt", + "labore", + "nostrud" + ] + }\ + """) + +def main(): + app = QApplication(sys.argv) + ex = EditorAll() + ex.setWindowTitle(__file__) + ex.setText(EXAMPLE_TEXT) + ex.resize(800, 600) + ex.show() + sys.exit(app.exec_()) + + +if __name__ == "__main__": + main() diff --git a/testbed/lark-parser__lark/examples/advanced/reconstruct_json.py b/testbed/lark-parser__lark/examples/advanced/reconstruct_json.py new file mode 100644 index 0000000000000000000000000000000000000000..201bc32dfc462ec60e07e526143a9db38c878d42 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/reconstruct_json.py @@ -0,0 +1,50 @@ +""" +Reconstruct a JSON +================== + +Demonstrates the experimental text-reconstruction feature + +The Reconstructor takes a parse tree (already filtered from punctuation, of course), +and reconstructs it into correct text, that can be parsed correctly. +It can be useful for creating "hooks" to alter data before handing it to other parsers. You can also use it to generate samples from scratch. +""" + +import json + +from lark import Lark +from lark.reconstruct import Reconstructor + +from _json_parser import json_grammar + +test_json = ''' + { + "empty_object" : {}, + "empty_array" : [], + "booleans" : { "YES" : true, "NO" : false }, + "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ], + "strings" : [ "This", [ "And" , "That", "And a \\"b" ] ], + "nothing" : null + } +''' + +def test_earley(): + + json_parser = Lark(json_grammar, maybe_placeholders=False) + tree = json_parser.parse(test_json) + + new_json = Reconstructor(json_parser).reconstruct(tree) + print (new_json) + print (json.loads(new_json) == json.loads(test_json)) + + +def test_lalr(): + + json_parser = Lark(json_grammar, parser='lalr', maybe_placeholders=False) + tree = json_parser.parse(test_json) + + new_json = Reconstructor(json_parser).reconstruct(tree) + print (new_json) + print (json.loads(new_json) == json.loads(test_json)) + +test_earley() +test_lalr() diff --git a/testbed/lark-parser__lark/examples/advanced/template_lark.lark b/testbed/lark-parser__lark/examples/advanced/template_lark.lark new file mode 100644 index 0000000000000000000000000000000000000000..296407fee6d116a0195c674c7b9fae558460dc74 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/template_lark.lark @@ -0,0 +1,56 @@ +start: (_item | _NL)* + +_item: rule + | token + | statement + +_rule_or_token: RULE + | TOKEN +rule: RULE rule_params priority? ":" expansions{_rule_or_token} _NL +token: TOKEN priority? ":" expansions{TOKEN} _NL + +rule_params: ["{" RULE ("," RULE)* "}"] + +priority: "." NUMBER + +statement: "%ignore" expansions{TOKEN} _NL -> ignore + | "%import" import_path{_rule_or_token} ["->" _rule_or_token] _NL -> import + | "%import" import_path{_rule_or_token} name_list{_rule_or_token} _NL -> multi_import + | "%declare" TOKEN+ -> declare + +!import_path{name}: "."? name ("." name)* +name_list{name}: "(" name ("," name)* ")" + +?expansions{name}: alias{name} (_VBAR alias{name})* + +?alias{name}: expansion{name} ["->" RULE] + +?expansion{name}: expr{name}* + +?expr{name}: atom{name} [OP | "~" NUMBER [".." NUMBER]] + +?atom{name}: "(" expansions{name} ")" + | "[" expansions{name} "]" -> maybe + | value{name} + +?value{name}: STRING ".." STRING -> literal_range + | name + | (REGEXP | STRING) -> literal + | name "{" value{name} ("," value{name})* "}" -> template_usage + +_VBAR: _NL? "|" +OP: /[+*]|[?](?![a-z])/ +RULE: /!?[_?]?[a-z][_a-z0-9]*/ +TOKEN: /_?[A-Z][_A-Z0-9]*/ +STRING: _STRING "i"? +REGEXP: /\/(?!\/)(\\\/|\\\\|[^\/\n])*?\/[imslux]*/ +_NL: /(\r?\n)+\s*/ + +%import common.ESCAPED_STRING -> _STRING +%import common.INT -> NUMBER +%import common.WS_INLINE + +COMMENT: /\s*/ "//" /[^\n]/* + +%ignore WS_INLINE +%ignore COMMENT diff --git a/testbed/lark-parser__lark/examples/advanced/templates.py b/testbed/lark-parser__lark/examples/advanced/templates.py new file mode 100644 index 0000000000000000000000000000000000000000..ac59b7a9d7b8847dcee0c9115d1de8ed1c5e2de6 --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/templates.py @@ -0,0 +1,29 @@ +""" +Templates +========= + +This example shows how to use Lark's templates to achieve cleaner grammars + +""" +from lark import Lark + +grammar = r""" +start: list | dict + +list: "[" _seperated{atom, ","} "]" +dict: "{" _seperated{key_value, ","} "}" +key_value: atom ":" atom + +_seperated{x, sep}: x (sep x)* // Define a sequence of 'x sep x sep x ...' + +atom: NUMBER | ESCAPED_STRING + +%import common (NUMBER, ESCAPED_STRING, WS) +%ignore WS +""" + + +parser = Lark(grammar) + +print(parser.parse('[1, "a", 2]')) +print(parser.parse('{"a": 2, "b": 6}')) \ No newline at end of file diff --git a/testbed/lark-parser__lark/examples/advanced/tree_forest_transformer.py b/testbed/lark-parser__lark/examples/advanced/tree_forest_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9a2cd1d59ced49ab2e3f1c6f2ca7d98004129c --- /dev/null +++ b/testbed/lark-parser__lark/examples/advanced/tree_forest_transformer.py @@ -0,0 +1,58 @@ +""" +Transform a Forest +================== + +This example demonstrates how to subclass ``TreeForestTransformer`` to +directly transform a SPPF. +""" + +from lark import Lark +from lark.parsers.earley_forest import TreeForestTransformer, handles_ambiguity, Discard + +class CustomTransformer(TreeForestTransformer): + + @handles_ambiguity + def sentence(self, trees): + return next(tree for tree in trees if tree.data == 'simple') + + def simple(self, children): + children.append('.') + return self.tree_class('simple', children) + + def adj(self, children): + raise Discard() + + def __default_token__(self, token): + return token.capitalize() + +grammar = """ + sentence: noun verb noun -> simple + | noun verb "like" noun -> comparative + + noun: adj? NOUN + verb: VERB + adj: ADJ + + NOUN: "flies" | "bananas" | "fruit" + VERB: "like" | "flies" + ADJ: "fruit" + + %import common.WS + %ignore WS +""" + +parser = Lark(grammar, start='sentence', ambiguity='forest') +sentence = 'fruit flies like bananas' +forest = parser.parse(sentence) + +tree = CustomTransformer(resolve_ambiguity=False).transform(forest) +print(tree.pretty()) + +# Output: +# +# simple +# noun Flies +# verb Like +# noun Bananas +# . +# diff --git a/testbed/lark-parser__lark/examples/calc.py b/testbed/lark-parser__lark/examples/calc.py new file mode 100644 index 0000000000000000000000000000000000000000..9e9aa78fd7511ecc1e45c5c158feb76a00a65159 --- /dev/null +++ b/testbed/lark-parser__lark/examples/calc.py @@ -0,0 +1,82 @@ +""" +Basic calculator +================ + +A simple example of a REPL calculator + +This example shows how to write a basic calculator with variables. +""" +from lark import Lark, Transformer, v_args + + +try: + input = raw_input # For Python2 compatibility +except NameError: + pass + + +calc_grammar = """ + ?start: sum + | NAME "=" sum -> assign_var + + ?sum: product + | sum "+" product -> add + | sum "-" product -> sub + + ?product: atom + | product "*" atom -> mul + | product "/" atom -> div + + ?atom: NUMBER -> number + | "-" atom -> neg + | NAME -> var + | "(" sum ")" + + %import common.CNAME -> NAME + %import common.NUMBER + %import common.WS_INLINE + + %ignore WS_INLINE +""" + + +@v_args(inline=True) # Affects the signatures of the methods +class CalculateTree(Transformer): + from operator import add, sub, mul, truediv as div, neg + number = float + + def __init__(self): + self.vars = {} + + def assign_var(self, name, value): + self.vars[name] = value + return value + + def var(self, name): + try: + return self.vars[name] + except KeyError: + raise Exception("Variable not found: %s" % name) + + +calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree()) +calc = calc_parser.parse + + +def main(): + while True: + try: + s = input('> ') + except EOFError: + break + print(calc(s)) + + +def test(): + print(calc("a = 1+2")) + print(calc("1+a*-3")) + + +if __name__ == '__main__': + # test() + main() diff --git a/testbed/lark-parser__lark/examples/fruitflies.py b/testbed/lark-parser__lark/examples/fruitflies.py new file mode 100644 index 0000000000000000000000000000000000000000..aca0b1b07e98e58dc7f774b48bee48e616d9b59d --- /dev/null +++ b/testbed/lark-parser__lark/examples/fruitflies.py @@ -0,0 +1,58 @@ +""" +Handling Ambiguity +================== + +A demonstration of ambiguity + +This example shows how to use get explicit ambiguity from Lark's Earley parser. + +""" +import sys +from lark import Lark, tree + +grammar = """ + sentence: noun verb noun -> simple + | noun verb "like" noun -> comparative + + noun: adj? NOUN + verb: VERB + adj: ADJ + + NOUN: "flies" | "bananas" | "fruit" + VERB: "like" | "flies" + ADJ: "fruit" + + %import common.WS + %ignore WS +""" + +parser = Lark(grammar, start='sentence', ambiguity='explicit') + +sentence = 'fruit flies like bananas' + +def make_png(filename): + tree.pydot__tree_to_png( parser.parse(sentence), filename) + +def make_dot(filename): + tree.pydot__tree_to_dot( parser.parse(sentence), filename) + +if __name__ == '__main__': + print(parser.parse(sentence).pretty()) + # make_png(sys.argv[1]) + # make_dot(sys.argv[1]) + +# Output: +# +# _ambig +# comparative +# noun fruit +# verb flies +# noun bananas +# simple +# noun +# fruit +# flies +# verb like +# noun bananas +# +# (or view a nicer version at "./fruitflies.png") diff --git a/testbed/lark-parser__lark/examples/indented_tree.py b/testbed/lark-parser__lark/examples/indented_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..6cdaf3743d823379f3b9b06040fe38c59b51d08d --- /dev/null +++ b/testbed/lark-parser__lark/examples/indented_tree.py @@ -0,0 +1,55 @@ +""" +Parsing Indentation +=================== + +A demonstration of parsing indentation (“whitespace significant” language) +and the usage of the Indenter class. + +Since indentation is context-sensitive, a postlex stage is introduced to +manufacture INDENT/DEDENT tokens. + +It is crucial for the indenter that the NL_type matches +the spaces (and tabs) after the newline. +""" +from lark import Lark +from lark.indenter import Indenter + +tree_grammar = r""" + ?start: _NL* tree + + tree: NAME _NL [_INDENT tree+ _DEDENT] + + %import common.CNAME -> NAME + %import common.WS_INLINE + %declare _INDENT _DEDENT + %ignore WS_INLINE + + _NL: /(\r?\n[\t ]*)+/ +""" + +class TreeIndenter(Indenter): + NL_type = '_NL' + OPEN_PAREN_types = [] + CLOSE_PAREN_types = [] + INDENT_type = '_INDENT' + DEDENT_type = '_DEDENT' + tab_len = 8 + +parser = Lark(tree_grammar, parser='lalr', postlex=TreeIndenter()) + +test_tree = """ +a + b + c + d + e + f + g +""" + +def test(): + print(parser.parse(test_tree).pretty()) + +if __name__ == '__main__': + test() + diff --git a/testbed/lark-parser__lark/examples/json_parser.py b/testbed/lark-parser__lark/examples/json_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c3573f3f98181942081625f9f834c73aa970419d --- /dev/null +++ b/testbed/lark-parser__lark/examples/json_parser.py @@ -0,0 +1,91 @@ +""" +Simple JSON Parser +================== + +The code is short and clear, and outperforms every other parser (that's written in Python). +For an explanation, check out the JSON parser tutorial at /docs/json_tutorial.md +""" +import sys + +from lark import Lark, Transformer, v_args + +json_grammar = r""" + ?start: value + + ?value: object + | array + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + + array : "[" [value ("," value)*] "]" + object : "{" [pair ("," pair)*] "}" + pair : string ":" value + + string : ESCAPED_STRING + + %import common.ESCAPED_STRING + %import common.SIGNED_NUMBER + %import common.WS + + %ignore WS +""" + + +class TreeToJson(Transformer): + @v_args(inline=True) + def string(self, s): + return s[1:-1].replace('\\"', '"') + + array = list + pair = tuple + object = dict + number = v_args(inline=True)(float) + + null = lambda self, _: None + true = lambda self, _: True + false = lambda self, _: False + + +### Create the JSON parser with Lark, using the Earley algorithm +# json_parser = Lark(json_grammar, parser='earley', lexer='standard') +# def parse(x): +# return TreeToJson().transform(json_parser.parse(x)) + +### Create the JSON parser with Lark, using the LALR algorithm +json_parser = Lark(json_grammar, parser='lalr', + # Using the standard lexer isn't required, and isn't usually recommended. + # But, it's good enough for JSON, and it's slightly faster. + lexer='standard', + # Disabling propagate_positions and placeholders slightly improves speed + propagate_positions=False, + maybe_placeholders=False, + # Using an internal transformer is faster and more memory efficient + transformer=TreeToJson()) +parse = json_parser.parse + + +def test(): + test_json = ''' + { + "empty_object" : {}, + "empty_array" : [], + "booleans" : { "YES" : true, "NO" : false }, + "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ], + "strings" : [ "This", [ "And" , "That", "And a \\"b" ] ], + "nothing" : null + } + ''' + + j = parse(test_json) + print(j) + import json + assert j == json.loads(test_json) + + +if __name__ == '__main__': + # test() + with open(sys.argv[1]) as f: + print(parse(f.read())) diff --git a/testbed/lark-parser__lark/examples/lark.lark b/testbed/lark-parser__lark/examples/lark.lark new file mode 100644 index 0000000000000000000000000000000000000000..474b8198c2222c648e65a72f1f85ef16d161f3d1 --- /dev/null +++ b/testbed/lark-parser__lark/examples/lark.lark @@ -0,0 +1,58 @@ +start: (_item? _NL)* _item? + +_item: rule + | token + | statement + +rule: RULE rule_params priority? ":" expansions +token: TOKEN token_params priority? ":" expansions + +rule_params: ["{" RULE ("," RULE)* "}"] +token_params: ["{" TOKEN ("," TOKEN)* "}"] + +priority: "." NUMBER + +statement: "%ignore" expansions -> ignore + | "%import" import_path ["->" name] -> import + | "%import" import_path name_list -> multi_import + | "%declare" name+ -> declare + +!import_path: "."? name ("." name)* +name_list: "(" name ("," name)* ")" + +?expansions: alias (_VBAR alias)* + +?alias: expansion ["->" RULE] + +?expansion: expr* + +?expr: atom [OP | "~" NUMBER [".." NUMBER]] + +?atom: "(" expansions ")" + | "[" expansions "]" -> maybe + | value + +?value: STRING ".." STRING -> literal_range + | name + | (REGEXP | STRING) -> literal + | name "{" value ("," value)* "}" -> template_usage + +name: RULE + | TOKEN + +_VBAR: _NL? "|" +OP: /[+*]|[?](?![a-z])/ +RULE: /!?[_?]?[a-z][_a-z0-9]*/ +TOKEN: /_?[A-Z][_A-Z0-9]*/ +STRING: _STRING "i"? +REGEXP: /\/(?!\/)(\\\/|\\\\|[^\/\n])*?\/[imslux]*/ +_NL: /(\r?\n)+\s*/ + +%import common.ESCAPED_STRING -> _STRING +%import common.SIGNED_INT -> NUMBER +%import common.WS_INLINE + +COMMENT: /\s*/ "//" /[^\n]/* + +%ignore WS_INLINE +%ignore COMMENT diff --git a/testbed/lark-parser__lark/examples/lark_grammar.py b/testbed/lark-parser__lark/examples/lark_grammar.py new file mode 100644 index 0000000000000000000000000000000000000000..f2185eec3743551b5458d218f2a28315183f19de --- /dev/null +++ b/testbed/lark-parser__lark/examples/lark_grammar.py @@ -0,0 +1,33 @@ +""" +Lark Grammar +============ + +A reference implementation of the Lark grammar (using LALR(1)) +""" +import lark +from pathlib import Path + +parser = lark.Lark.open('lark.lark', rel_to=__file__, parser="lalr") + +examples_path = Path(__file__).parent +lark_path = Path(lark.__file__).parent + +grammar_files = [ + examples_path / 'lark.lark', + examples_path / 'advanced/python2.lark', + examples_path / 'advanced/python3.lark', + examples_path / 'relative-imports/multiples.lark', + examples_path / 'relative-imports/multiple2.lark', + examples_path / 'relative-imports/multiple3.lark', + examples_path / 'tests/no_newline_at_end.lark', + examples_path / 'tests/negative_priority.lark', + lark_path / 'grammars/common.lark', +] + +def test(): + for grammar_file in grammar_files: + tree = parser.parse(open(grammar_file).read()) + print("All grammars parsed successfully") + +if __name__ == '__main__': + test() diff --git a/testbed/lark-parser__lark/examples/relative-imports/multiple2.lark b/testbed/lark-parser__lark/examples/relative-imports/multiple2.lark new file mode 100644 index 0000000000000000000000000000000000000000..a65077cd48cc1245c2fababeaf82127ad37d58b2 --- /dev/null +++ b/testbed/lark-parser__lark/examples/relative-imports/multiple2.lark @@ -0,0 +1 @@ +start: ("0" | "1")* "0" diff --git a/testbed/lark-parser__lark/examples/relative-imports/multiple3.lark b/testbed/lark-parser__lark/examples/relative-imports/multiple3.lark new file mode 100644 index 0000000000000000000000000000000000000000..6a67bce77b7b55b87276cdb0fa1062f97806ad04 --- /dev/null +++ b/testbed/lark-parser__lark/examples/relative-imports/multiple3.lark @@ -0,0 +1,5 @@ +start: mod0mod0+ + +mod0mod0: "0" | "1" mod1mod0 +mod1mod0: "1" | "0" mod2mod1 mod1mod0 +mod2mod1: "0" | "1" mod2mod1 diff --git a/testbed/lark-parser__lark/examples/relative-imports/multiples.lark b/testbed/lark-parser__lark/examples/relative-imports/multiples.lark new file mode 100644 index 0000000000000000000000000000000000000000..35b5d17ec005155525837ac9902d4fd4006ddf8c --- /dev/null +++ b/testbed/lark-parser__lark/examples/relative-imports/multiples.lark @@ -0,0 +1,5 @@ +start: "2:" multiple2 + | "3:" multiple3 + +%import .multiple2.start -> multiple2 +%import .multiple3.start -> multiple3 diff --git a/testbed/lark-parser__lark/examples/relative-imports/multiples.py b/testbed/lark-parser__lark/examples/relative-imports/multiples.py new file mode 100644 index 0000000000000000000000000000000000000000..b57d4464f6a5afee8c85d054c20a3a5c15f858c3 --- /dev/null +++ b/testbed/lark-parser__lark/examples/relative-imports/multiples.py @@ -0,0 +1,28 @@ +# +# This example demonstrates relative imports with rule rewrite +# see multiples.lark +# + +# +# if b is a number written in binary, and m is either 2 or 3, +# the grammar aims to recognise m:b iif b is a multiple of m +# +# for example, 3:1001 is recognised +# because 9 (0b1001) is a multiple of 3 +# + +from lark import Lark, UnexpectedInput + +parser = Lark.open('multiples.lark', parser='lalr') + +def is_in_grammar(data): + try: + parser.parse(data) + except UnexpectedInput: + return False + return True + +for n_dec in range(100): + n_bin = bin(n_dec)[2:] + assert is_in_grammar('2:{}'.format(n_bin)) == (n_dec % 2 == 0) + assert is_in_grammar('3:{}'.format(n_bin)) == (n_dec % 3 == 0) diff --git a/testbed/lark-parser__lark/examples/standalone/create_standalone.sh b/testbed/lark-parser__lark/examples/standalone/create_standalone.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8da6b0d0886971f6f7c4904cca31ad7c16ae9ca --- /dev/null +++ b/testbed/lark-parser__lark/examples/standalone/create_standalone.sh @@ -0,0 +1,2 @@ +#!/bin/sh +PYTHONPATH=../.. python -m lark.tools.standalone json.lark > json_parser.py diff --git a/testbed/lark-parser__lark/examples/standalone/json.lark b/testbed/lark-parser__lark/examples/standalone/json.lark new file mode 100644 index 0000000000000000000000000000000000000000..243a2308d3616a10b20ac4a3848617bf37dffe3e --- /dev/null +++ b/testbed/lark-parser__lark/examples/standalone/json.lark @@ -0,0 +1,21 @@ +?start: value + +?value: object + | array + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + +array : "[" [value ("," value)*] "]" +object : "{" [pair ("," pair)*] "}" +pair : string ":" value + +string : ESCAPED_STRING + +%import common.ESCAPED_STRING +%import common.SIGNED_NUMBER +%import common.WS + +%ignore WS diff --git a/testbed/lark-parser__lark/examples/standalone/json_parser.py b/testbed/lark-parser__lark/examples/standalone/json_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..d20cb4b83fdd2bed8438403e81f5925a2a088cd3 --- /dev/null +++ b/testbed/lark-parser__lark/examples/standalone/json_parser.py @@ -0,0 +1,2356 @@ +# The file was automatically generated by Lark v0.9.0 +__version__ = "0.9.0" + +# +# +# Lark Stand-alone Generator Tool +# ---------------------------------- +# Generates a stand-alone LALR(1) parser with a standard lexer +# +# Git: https://github.com/erezsh/lark +# Author: Erez Shinan (erezshin@gmail.com) +# +# +# >>> LICENSE +# +# This tool and its generated code use a separate license from Lark, +# and are subject to the terms of the Mozilla Public License, v. 2.0. +# If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# If you wish to purchase a commercial license for this tool and its +# generated code, you may contact me via email or otherwise. +# +# If MPL2 is incompatible with your free or open-source project, +# contact me and we'll work it out. +# +# + +import os +from io import open + + + +class LarkError(Exception): + pass + +class GrammarError(LarkError): + pass + +class ParseError(LarkError): + pass + +class LexError(LarkError): + pass + +class UnexpectedEOF(ParseError): + def __init__(self, expected): + self.expected = expected + + message = ("Unexpected end-of-input. Expected one of: \n\t* %s\n" % '\n\t* '.join(x.name for x in self.expected)) + super(UnexpectedEOF, self).__init__(message) + + +class UnexpectedInput(LarkError): + #-- + pos_in_stream = None + + def get_context(self, text, span=40): + #-- + pos = self.pos_in_stream + start = max(pos - span, 0) + end = pos + span + if not isinstance(text, bytes): + before = text[start:pos].rsplit('\n', 1)[-1] + after = text[pos:end].split('\n', 1)[0] + return before + after + '\n' + ' ' * len(before) + '^\n' + else: + before = text[start:pos].rsplit(b'\n', 1)[-1] + after = text[pos:end].split(b'\n', 1)[0] + return (before + after + b'\n' + b' ' * len(before) + b'^\n').decode("ascii", "backslashreplace") + + def match_examples(self, parse_fn, examples, token_type_match_fallback=False, use_accepts=False): + #-- + assert self.state is not None, "Not supported for this exception" + + if isinstance(examples, dict): + examples = examples.items() + + candidate = (None, False) + for i, (label, example) in enumerate(examples): + assert not isinstance(example, STRING_TYPE) + + for j, malformed in enumerate(example): + try: + parse_fn(malformed) + except UnexpectedInput as ut: + if ut.state == self.state: + if use_accepts and ut.accepts != self.accepts: + logger.debug("Different accepts with same state[%d]: %s != %s at example [%s][%s]" % + (self.state, self.accepts, ut.accepts, i, j)) + continue + try: + if ut.token == self.token: ## + + logger.debug("Exact Match at example [%s][%s]" % (i, j)) + return label + + if token_type_match_fallback: + ## + + if (ut.token.type == self.token.type) and not candidate[-1]: + logger.debug("Token Type Fallback at example [%s][%s]" % (i, j)) + candidate = label, True + + except AttributeError: + pass + if not candidate[0]: + logger.debug("Same State match at example [%s][%s]" % (i, j)) + candidate = label, False + + return candidate[0] + + +class UnexpectedCharacters(LexError, UnexpectedInput): + def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None): + self.line = line + self.column = column + self.pos_in_stream = lex_pos + self.state = state + + self.allowed = allowed + self.considered_tokens = considered_tokens + + if isinstance(seq, bytes): + _s = seq[lex_pos:lex_pos+1].decode("ascii", "backslashreplace") + else: + _s = seq[lex_pos] + + message = "No terminal defined for '%s' at line %d col %d" % (_s, line, column) + message += '\n\n' + self.get_context(seq) + if allowed: + message += '\nExpecting: %s\n' % allowed + if token_history: + message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in token_history) + + super(UnexpectedCharacters, self).__init__(message) + + +class UnexpectedToken(ParseError, UnexpectedInput): + #-- + def __init__(self, token, expected, considered_rules=None, state=None, puppet=None): + self.line = getattr(token, 'line', '?') + self.column = getattr(token, 'column', '?') + self.pos_in_stream = getattr(token, 'pos_in_stream', None) + self.state = state + + self.token = token + self.expected = expected ## + + self.considered_rules = considered_rules + self.puppet = puppet + + ## + + ## + + self.accepts = puppet and puppet.accepts() + + message = ("Unexpected token %r at line %s, column %s.\n" + "Expected one of: \n\t* %s\n" + % (token, self.line, self.column, '\n\t* '.join(self.accepts or self.expected))) + + super(UnexpectedToken, self).__init__(message) + + +class VisitError(LarkError): + #-- + def __init__(self, rule, obj, orig_exc): + self.obj = obj + self.orig_exc = orig_exc + + message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc) + super(VisitError, self).__init__(message) + +import logging +logger = logging.getLogger("lark") +logger.addHandler(logging.StreamHandler()) +## + +## + +logger.setLevel(logging.CRITICAL) + + +def classify(seq, key=None, value=None): + d = {} + for item in seq: + k = key(item) if (key is not None) else item + v = value(item) if (value is not None) else item + if k in d: + d[k].append(v) + else: + d[k] = [v] + return d + + +def _deserialize(data, namespace, memo): + if isinstance(data, dict): + if '__type__' in data: ## + + class_ = namespace[data['__type__']] + return class_.deserialize(data, memo) + elif '@' in data: + return memo[data['@']] + return {key:_deserialize(value, namespace, memo) for key, value in data.items()} + elif isinstance(data, list): + return [_deserialize(value, namespace, memo) for value in data] + return data + + +class Serialize(object): + def memo_serialize(self, types_to_memoize): + memo = SerializeMemoizer(types_to_memoize) + return self.serialize(memo), memo.serialize() + + def serialize(self, memo=None): + if memo and memo.in_types(self): + return {'@': memo.memoized.get(self)} + + fields = getattr(self, '__serialize_fields__') + res = {f: _serialize(getattr(self, f), memo) for f in fields} + res['__type__'] = type(self).__name__ + postprocess = getattr(self, '_serialize', None) + if postprocess: + postprocess(res, memo) + return res + + @classmethod + def deserialize(cls, data, memo): + namespace = getattr(cls, '__serialize_namespace__', {}) + namespace = {c.__name__:c for c in namespace} + + fields = getattr(cls, '__serialize_fields__') + + if '@' in data: + return memo[data['@']] + + inst = cls.__new__(cls) + for f in fields: + try: + setattr(inst, f, _deserialize(data[f], namespace, memo)) + except KeyError as e: + raise KeyError("Cannot find key for class", cls, e) + postprocess = getattr(inst, '_deserialize', None) + if postprocess: + postprocess() + return inst + + +class SerializeMemoizer(Serialize): + __serialize_fields__ = 'memoized', + + def __init__(self, types_to_memoize): + self.types_to_memoize = tuple(types_to_memoize) + self.memoized = Enumerator() + + def in_types(self, value): + return isinstance(value, self.types_to_memoize) + + def serialize(self): + return _serialize(self.memoized.reversed(), None) + + @classmethod + def deserialize(cls, data, namespace, memo): + return _deserialize(data, namespace, memo) + + + +try: + STRING_TYPE = basestring +except NameError: ## + + STRING_TYPE = str + + +import types +from functools import wraps, partial +from contextlib import contextmanager + +Str = type(u'') +try: + classtype = types.ClassType ## + +except AttributeError: + classtype = type ## + + +def smart_decorator(f, create_decorator): + if isinstance(f, types.FunctionType): + return wraps(f)(create_decorator(f, True)) + + elif isinstance(f, (classtype, type, types.BuiltinFunctionType)): + return wraps(f)(create_decorator(f, False)) + + elif isinstance(f, types.MethodType): + return wraps(f)(create_decorator(f.__func__, True)) + + elif isinstance(f, partial): + ## + + return wraps(f.func)(create_decorator(lambda *args, **kw: f(*args[1:], **kw), True)) + + else: + return create_decorator(f.__func__.__call__, True) + +try: + import regex +except ImportError: + regex = None + +import sys, re +Py36 = (sys.version_info[:2] >= (3, 6)) + +import sre_parse +import sre_constants +categ_pattern = re.compile(r'\\p{[A-Za-z_]+}') +def get_regexp_width(expr): + if regex: + ## + + ## + + ## + + regexp_final = re.sub(categ_pattern, 'A', expr) + else: + if re.search(categ_pattern, expr): + raise ImportError('`regex` module must be installed in order to use Unicode categories.', expr) + regexp_final = expr + try: + return [int(x) for x in sre_parse.parse(regexp_final).getwidth()] + except sre_constants.error: + raise ValueError(expr) + + +from collections import OrderedDict + + +class Meta: + def __init__(self): + self.empty = True + + +class Tree(object): + #-- + def __init__(self, data, children, meta=None): + self.data = data + self.children = children + self._meta = meta + + @property + def meta(self): + if self._meta is None: + self._meta = Meta() + return self._meta + + def __repr__(self): + return 'Tree(%s, %s)' % (self.data, self.children) + + def _pretty_label(self): + return self.data + + def _pretty(self, level, indent_str): + if len(self.children) == 1 and not isinstance(self.children[0], Tree): + return [ indent_str*level, self._pretty_label(), '\t', '%s' % (self.children[0],), '\n'] + + l = [ indent_str*level, self._pretty_label(), '\n' ] + for n in self.children: + if isinstance(n, Tree): + l += n._pretty(level+1, indent_str) + else: + l += [ indent_str*(level+1), '%s' % (n,), '\n' ] + + return l + + def pretty(self, indent_str=' '): + #-- + return ''.join(self._pretty(0, indent_str)) + + def __eq__(self, other): + try: + return self.data == other.data and self.children == other.children + except AttributeError: + return False + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash((self.data, tuple(self.children))) + + def iter_subtrees(self): + #-- + queue = [self] + subtrees = OrderedDict() + for subtree in queue: + subtrees[id(subtree)] = subtree + queue += [c for c in reversed(subtree.children) + if isinstance(c, Tree) and id(c) not in subtrees] + + del queue + return reversed(list(subtrees.values())) + + def find_pred(self, pred): + #-- + return filter(pred, self.iter_subtrees()) + + def find_data(self, data): + #-- + return self.find_pred(lambda t: t.data == data) + + +from inspect import getmembers, getmro + +class Discard(Exception): + #-- + pass + +## + + +class _Decoratable: + #-- + + @classmethod + def _apply_decorator(cls, decorator, **kwargs): + mro = getmro(cls) + assert mro[0] is cls + libmembers = {name for _cls in mro[1:] for name, _ in getmembers(_cls)} + for name, value in getmembers(cls): + + ## + + if name.startswith('_') or (name in libmembers and name not in cls.__dict__): + continue + if not callable(value): + continue + + ## + + if hasattr(cls.__dict__[name], 'vargs_applied') or hasattr(value, 'vargs_applied'): + continue + + static = isinstance(cls.__dict__[name], (staticmethod, classmethod)) + setattr(cls, name, decorator(value, static=static, **kwargs)) + return cls + + def __class_getitem__(cls, _): + return cls + + +class Transformer(_Decoratable): + #-- + __visit_tokens__ = True ## + + + def __init__(self, visit_tokens=True): + self.__visit_tokens__ = visit_tokens + + def _call_userfunc(self, tree, new_children=None): + ## + + children = new_children if new_children is not None else tree.children + try: + f = getattr(self, tree.data) + except AttributeError: + return self.__default__(tree.data, children, tree.meta) + else: + try: + wrapper = getattr(f, 'visit_wrapper', None) + if wrapper is not None: + return f.visit_wrapper(f, tree.data, children, tree.meta) + else: + return f(children) + except (GrammarError, Discard): + raise + except Exception as e: + raise VisitError(tree.data, tree, e) + + def _call_userfunc_token(self, token): + try: + f = getattr(self, token.type) + except AttributeError: + return self.__default_token__(token) + else: + try: + return f(token) + except (GrammarError, Discard): + raise + except Exception as e: + raise VisitError(token.type, token, e) + + + def _transform_children(self, children): + for c in children: + try: + if isinstance(c, Tree): + yield self._transform_tree(c) + elif self.__visit_tokens__ and isinstance(c, Token): + yield self._call_userfunc_token(c) + else: + yield c + except Discard: + pass + + def _transform_tree(self, tree): + children = list(self._transform_children(tree.children)) + return self._call_userfunc(tree, children) + + def transform(self, tree): + return self._transform_tree(tree) + + def __mul__(self, other): + return TransformerChain(self, other) + + def __default__(self, data, children, meta): + #-- + return Tree(data, children, meta) + + def __default_token__(self, token): + #-- + return token + + + +class InlineTransformer(Transformer): ## + + def _call_userfunc(self, tree, new_children=None): + ## + + children = new_children if new_children is not None else tree.children + try: + f = getattr(self, tree.data) + except AttributeError: + return self.__default__(tree.data, children, tree.meta) + else: + return f(*children) + + +class TransformerChain(object): + def __init__(self, *transformers): + self.transformers = transformers + + def transform(self, tree): + for t in self.transformers: + tree = t.transform(tree) + return tree + + def __mul__(self, other): + return TransformerChain(*self.transformers + (other,)) + + +class Transformer_InPlace(Transformer): + #-- + def _transform_tree(self, tree): ## + + return self._call_userfunc(tree) + + def transform(self, tree): + for subtree in tree.iter_subtrees(): + subtree.children = list(self._transform_children(subtree.children)) + + return self._transform_tree(tree) + + +class Transformer_NonRecursive(Transformer): + #-- + + def transform(self, tree): + ## + + rev_postfix = [] + q = [tree] + while q: + t = q.pop() + rev_postfix.append( t ) + if isinstance(t, Tree): + q += t.children + + ## + + stack = [] + for x in reversed(rev_postfix): + if isinstance(x, Tree): + size = len(x.children) + if size: + args = stack[-size:] + del stack[-size:] + else: + args = [] + stack.append(self._call_userfunc(x, args)) + else: + stack.append(x) + + t ,= stack ## + + return t + + + +class Transformer_InPlaceRecursive(Transformer): + #-- + def _transform_tree(self, tree): + tree.children = list(self._transform_children(tree.children)) + return self._call_userfunc(tree) + + + +## + + +class VisitorBase: + def _call_userfunc(self, tree): + return getattr(self, tree.data, self.__default__)(tree) + + def __default__(self, tree): + #-- + return tree + + def __class_getitem__(cls, _): + return cls + + +class Visitor(VisitorBase): + #-- + + def visit(self, tree): + for subtree in tree.iter_subtrees(): + self._call_userfunc(subtree) + return tree + + def visit_topdown(self,tree): + for subtree in tree.iter_subtrees_topdown(): + self._call_userfunc(subtree) + return tree + + +class Visitor_Recursive(VisitorBase): + #-- + + def visit(self, tree): + for child in tree.children: + if isinstance(child, Tree): + self.visit(child) + + self._call_userfunc(tree) + return tree + + def visit_topdown(self,tree): + self._call_userfunc(tree) + + for child in tree.children: + if isinstance(child, Tree): + self.visit_topdown(child) + + return tree + + + +def visit_children_decor(func): + #-- + @wraps(func) + def inner(cls, tree): + values = cls.visit_children(tree) + return func(cls, values) + return inner + + +class Interpreter(_Decoratable): + #-- + + def visit(self, tree): + f = getattr(self, tree.data) + wrapper = getattr(f, 'visit_wrapper', None) + if wrapper is not None: + return f.visit_wrapper(f, tree.data, tree.children, tree.meta) + else: + return f(tree) + + def visit_children(self, tree): + return [self.visit(child) if isinstance(child, Tree) else child + for child in tree.children] + + def __getattr__(self, name): + return self.__default__ + + def __default__(self, tree): + return self.visit_children(tree) + + + + +## + + +def _apply_decorator(obj, decorator, **kwargs): + try: + _apply = obj._apply_decorator + except AttributeError: + return decorator(obj, **kwargs) + else: + return _apply(decorator, **kwargs) + + + +def _inline_args__func(func): + @wraps(func) + def create_decorator(_f, with_self): + if with_self: + def f(self, children): + return _f(self, *children) + else: + def f(self, children): + return _f(*children) + return f + + return smart_decorator(func, create_decorator) + + +def inline_args(obj): ## + + return _apply_decorator(obj, _inline_args__func) + + + +def _visitor_args_func_dec(func, visit_wrapper=None, static=False): + def create_decorator(_f, with_self): + if with_self: + def f(self, *args, **kwargs): + return _f(self, *args, **kwargs) + else: + def f(self, *args, **kwargs): + return _f(*args, **kwargs) + return f + + if static: + f = wraps(func)(create_decorator(func, False)) + else: + f = smart_decorator(func, create_decorator) + f.vargs_applied = True + f.visit_wrapper = visit_wrapper + return f + + +def _vargs_inline(f, data, children, meta): + return f(*children) +def _vargs_meta_inline(f, data, children, meta): + return f(meta, *children) +def _vargs_meta(f, data, children, meta): + return f(children, meta) ## + +def _vargs_tree(f, data, children, meta): + return f(Tree(data, children, meta)) + + +def v_args(inline=False, meta=False, tree=False, wrapper=None): + #-- + if tree and (meta or inline): + raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.") + + func = None + if meta: + if inline: + func = _vargs_meta_inline + else: + func = _vargs_meta + elif inline: + func = _vargs_inline + elif tree: + func = _vargs_tree + + if wrapper is not None: + if func is not None: + raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.") + func = wrapper + + def _visitor_args_dec(obj): + return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func) + return _visitor_args_dec + + + +class Indenter: + def __init__(self): + self.paren_level = None + self.indent_level = None + assert self.tab_len > 0 + + def handle_NL(self, token): + if self.paren_level > 0: + return + + yield token + + indent_str = token.rsplit('\n', 1)[1] ## + + indent = indent_str.count(' ') + indent_str.count('\t') * self.tab_len + + if indent > self.indent_level[-1]: + self.indent_level.append(indent) + yield Token.new_borrow_pos(self.INDENT_type, indent_str, token) + else: + while indent < self.indent_level[-1]: + self.indent_level.pop() + yield Token.new_borrow_pos(self.DEDENT_type, indent_str, token) + + assert indent == self.indent_level[-1], '%s != %s' % (indent, self.indent_level[-1]) + + def _process(self, stream): + for token in stream: + if token.type == self.NL_type: + for t in self.handle_NL(token): + yield t + else: + yield token + + if token.type in self.OPEN_PAREN_types: + self.paren_level += 1 + elif token.type in self.CLOSE_PAREN_types: + self.paren_level -= 1 + assert self.paren_level >= 0 + + while len(self.indent_level) > 1: + self.indent_level.pop() + yield Token(self.DEDENT_type, '') + + assert self.indent_level == [0], self.indent_level + + def process(self, stream): + self.paren_level = 0 + self.indent_level = [0] + return self._process(stream) + + ## + + @property + def always_accept(self): + return (self.NL_type,) + + + +class Symbol(Serialize): + __slots__ = ('name',) + + is_term = NotImplemented + + def __init__(self, name): + self.name = name + + def __eq__(self, other): + assert isinstance(other, Symbol), other + return self.is_term == other.is_term and self.name == other.name + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(self.name) + + def __repr__(self): + return '%s(%r)' % (type(self).__name__, self.name) + + fullrepr = property(__repr__) + + +class Terminal(Symbol): + __serialize_fields__ = 'name', 'filter_out' + + is_term = True + + def __init__(self, name, filter_out=False): + self.name = name + self.filter_out = filter_out + + @property + def fullrepr(self): + return '%s(%r, %r)' % (type(self).__name__, self.name, self.filter_out) + + + +class NonTerminal(Symbol): + __serialize_fields__ = 'name', + + is_term = False + + + +class RuleOptions(Serialize): + __serialize_fields__ = 'keep_all_tokens', 'expand1', 'priority', 'template_source', 'empty_indices' + + def __init__(self, keep_all_tokens=False, expand1=False, priority=None, template_source=None, empty_indices=()): + self.keep_all_tokens = keep_all_tokens + self.expand1 = expand1 + self.priority = priority + self.template_source = template_source + self.empty_indices = empty_indices + + def __repr__(self): + return 'RuleOptions(%r, %r, %r, %r)' % ( + self.keep_all_tokens, + self.expand1, + self.priority, + self.template_source + ) + + +class Rule(Serialize): + #-- + __slots__ = ('origin', 'expansion', 'alias', 'options', 'order', '_hash') + + __serialize_fields__ = 'origin', 'expansion', 'order', 'alias', 'options' + __serialize_namespace__ = Terminal, NonTerminal, RuleOptions + + def __init__(self, origin, expansion, order=0, alias=None, options=None): + self.origin = origin + self.expansion = expansion + self.alias = alias + self.order = order + self.options = options or RuleOptions() + self._hash = hash((self.origin, tuple(self.expansion))) + + def _deserialize(self): + self._hash = hash((self.origin, tuple(self.expansion))) + + def __str__(self): + return '<%s : %s>' % (self.origin.name, ' '.join(x.name for x in self.expansion)) + + def __repr__(self): + return 'Rule(%r, %r, %r, %r)' % (self.origin, self.expansion, self.alias, self.options) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + if not isinstance(other, Rule): + return False + return self.origin == other.origin and self.expansion == other.expansion + + + + +from copy import copy + +class Pattern(Serialize): + + def __init__(self, value, flags=()): + self.value = value + self.flags = frozenset(flags) + + def __repr__(self): + return repr(self.to_regexp()) + + ## + + def __hash__(self): + return hash((type(self), self.value, self.flags)) + def __eq__(self, other): + return type(self) == type(other) and self.value == other.value and self.flags == other.flags + + def to_regexp(self): + raise NotImplementedError() + + if Py36: + ## + + def _get_flags(self, value): + for f in self.flags: + value = ('(?%s:%s)' % (f, value)) + return value + + else: + def _get_flags(self, value): + for f in self.flags: + value = ('(?%s)' % f) + value + return value + + +class PatternStr(Pattern): + __serialize_fields__ = 'value', 'flags' + + type = "str" + + def to_regexp(self): + return self._get_flags(re.escape(self.value)) + + @property + def min_width(self): + return len(self.value) + max_width = min_width + +class PatternRE(Pattern): + __serialize_fields__ = 'value', 'flags', '_width' + + type = "re" + + def to_regexp(self): + return self._get_flags(self.value) + + _width = None + def _get_width(self): + if self._width is None: + self._width = get_regexp_width(self.to_regexp()) + return self._width + + @property + def min_width(self): + return self._get_width()[0] + @property + def max_width(self): + return self._get_width()[1] + + +class TerminalDef(Serialize): + __serialize_fields__ = 'name', 'pattern', 'priority' + __serialize_namespace__ = PatternStr, PatternRE + + def __init__(self, name, pattern, priority=1): + assert isinstance(pattern, Pattern), pattern + self.name = name + self.pattern = pattern + self.priority = priority + + def __repr__(self): + return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern) + + +class Token(Str): + #-- + __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column', 'end_pos') + + def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None, end_line=None, end_column=None, end_pos=None): + try: + self = super(Token, cls).__new__(cls, value) + except UnicodeDecodeError: + value = value.decode('latin1') + self = super(Token, cls).__new__(cls, value) + + self.type = type_ + self.pos_in_stream = pos_in_stream + self.value = value + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.end_pos = end_pos + return self + + def update(self, type_=None, value=None): + return Token.new_borrow_pos( + type_ if type_ is not None else self.type, + value if value is not None else self.value, + self + ) + + @classmethod + def new_borrow_pos(cls, type_, value, borrow_t): + return cls(type_, value, borrow_t.pos_in_stream, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column, borrow_t.end_pos) + + def __reduce__(self): + return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, )) + + def __repr__(self): + return 'Token(%s, %r)' % (self.type, self.value) + + def __deepcopy__(self, memo): + return Token(self.type, self.value, self.pos_in_stream, self.line, self.column) + + def __eq__(self, other): + if isinstance(other, Token) and self.type != other.type: + return False + + return Str.__eq__(self, other) + + __hash__ = Str.__hash__ + + +class LineCounter: + def __init__(self, newline_char): + self.newline_char = newline_char + self.char_pos = 0 + self.line = 1 + self.column = 1 + self.line_start_pos = 0 + + def feed(self, token, test_newline=True): + #-- + if test_newline: + newlines = token.count(self.newline_char) + if newlines: + self.line += newlines + self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1 + + self.char_pos += len(token) + self.column = self.char_pos - self.line_start_pos + 1 + +class _Lex: + #-- + def __init__(self, lexer, state=None): + self.lexer = lexer + self.state = state + + def lex(self, stream, newline_types, ignore_types): + newline_types = frozenset(newline_types) + ignore_types = frozenset(ignore_types) + line_ctr = LineCounter('\n' if not self.lexer.use_bytes else b'\n') + last_token = None + + while line_ctr.char_pos < len(stream): + lexer = self.lexer + res = lexer.match(stream, line_ctr.char_pos) + if not res: + allowed = {v for m, tfi in lexer.mres for v in tfi.values()} - ignore_types + if not allowed: + allowed = {""} + raise UnexpectedCharacters(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column, allowed=allowed, state=self.state, token_history=last_token and [last_token]) + + value, type_ = res + + if type_ not in ignore_types: + t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column) + line_ctr.feed(value, type_ in newline_types) + t.end_line = line_ctr.line + t.end_column = line_ctr.column + t.end_pos = line_ctr.char_pos + if t.type in lexer.callback: + t = lexer.callback[t.type](t) + if not isinstance(t, Token): + raise ValueError("Callbacks must return a token (returned %r)" % t) + yield t + last_token = t + else: + if type_ in lexer.callback: + t2 = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column) + lexer.callback[type_](t2) + line_ctr.feed(value, type_ in newline_types) + + + + +class UnlessCallback: + def __init__(self, mres): + self.mres = mres + + def __call__(self, t): + for mre, type_from_index in self.mres: + m = mre.match(t.value) + if m: + t.type = type_from_index[m.lastindex] + break + return t + +class CallChain: + def __init__(self, callback1, callback2, cond): + self.callback1 = callback1 + self.callback2 = callback2 + self.cond = cond + + def __call__(self, t): + t2 = self.callback1(t) + return self.callback2(t) if self.cond(t2) else t2 + + + + + +def _create_unless(terminals, g_regex_flags, re_, use_bytes): + tokens_by_type = classify(terminals, lambda t: type(t.pattern)) + assert len(tokens_by_type) <= 2, tokens_by_type.keys() + embedded_strs = set() + callback = {} + for retok in tokens_by_type.get(PatternRE, []): + unless = [] ## + + for strtok in tokens_by_type.get(PatternStr, []): + if strtok.priority > retok.priority: + continue + s = strtok.pattern.value + m = re_.match(retok.pattern.to_regexp(), s, g_regex_flags) + if m and m.group(0) == s: + unless.append(strtok) + if strtok.pattern.flags <= retok.pattern.flags: + embedded_strs.add(strtok) + if unless: + callback[retok.name] = UnlessCallback(build_mres(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes)) + + terminals = [t for t in terminals if t not in embedded_strs] + return terminals, callback + + +def _build_mres(terminals, max_size, g_regex_flags, match_whole, re_, use_bytes): + ## + + ## + + ## + + postfix = '$' if match_whole else '' + mres = [] + while terminals: + pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size]) + if use_bytes: + pattern = pattern.encode('latin-1') + try: + mre = re_.compile(pattern, g_regex_flags) + except AssertionError: ## + + return _build_mres(terminals, max_size//2, g_regex_flags, match_whole, re_, use_bytes) + + ## + + mres.append((mre, {i:n for n,i in mre.groupindex.items()} )) + terminals = terminals[max_size:] + return mres + +def build_mres(terminals, g_regex_flags, re_, use_bytes, match_whole=False): + return _build_mres(terminals, len(terminals), g_regex_flags, match_whole, re_, use_bytes) + +def _regexp_has_newline(r): + #-- + return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r) + +class Lexer(object): + #-- + lex = NotImplemented + + +class TraditionalLexer(Lexer): + + def __init__(self, conf): + terminals = list(conf.tokens) + assert all(isinstance(t, TerminalDef) for t in terminals), terminals + + self.re = conf.re_module + + if not conf.skip_validation: + ## + + for t in terminals: + try: + self.re.compile(t.pattern.to_regexp(), conf.g_regex_flags) + except self.re.error: + raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern)) + + if t.pattern.min_width == 0: + raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern)) + + assert set(conf.ignore) <= {t.name for t in terminals} + + ## + + self.newline_types = [t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp())] + self.ignore_types = list(conf.ignore) + + terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name)) + self.terminals = terminals + self.user_callbacks = conf.callbacks + self.g_regex_flags = conf.g_regex_flags + self.use_bytes = conf.use_bytes + + self._mres = None + ## + + + def _build(self): + terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, re_=self.re, use_bytes=self.use_bytes) + assert all(self.callback.values()) + + for type_, f in self.user_callbacks.items(): + if type_ in self.callback: + ## + + self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_) + else: + self.callback[type_] = f + + self._mres = build_mres(terminals, self.g_regex_flags, self.re, self.use_bytes) + + @property + def mres(self): + if self._mres is None: + self._build() + return self._mres + + def match(self, stream, pos): + for mre, type_from_index in self.mres: + m = mre.match(stream, pos) + if m: + return m.group(0), type_from_index[m.lastindex] + + def lex(self, stream): + return _Lex(self).lex(stream, self.newline_types, self.ignore_types) + + + + +class ContextualLexer(Lexer): + + def __init__(self, conf, states, always_accept=()): + terminals = list(conf.tokens) + tokens_by_name = {} + for t in terminals: + assert t.name not in tokens_by_name, t + tokens_by_name[t.name] = t + + trad_conf = copy(conf) + trad_conf.tokens = terminals + + lexer_by_tokens = {} + self.lexers = {} + for state, accepts in states.items(): + key = frozenset(accepts) + try: + lexer = lexer_by_tokens[key] + except KeyError: + accepts = set(accepts) | set(conf.ignore) | set(always_accept) + state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name] + lexer_conf = copy(trad_conf) + lexer_conf.tokens = state_tokens + lexer = TraditionalLexer(lexer_conf) + lexer_by_tokens[key] = lexer + + self.lexers[state] = lexer + + assert trad_conf.tokens is terminals + self.root_lexer = TraditionalLexer(trad_conf) + + def lex(self, stream, get_parser_state): + parser_state = get_parser_state() + l = _Lex(self.lexers[parser_state], parser_state) + try: + for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types): + yield x + parser_state = get_parser_state() + l.lexer = self.lexers[parser_state] + l.state = parser_state ## + + except UnexpectedCharacters as e: + ## + + ## + + ## + + root_match = self.root_lexer.match(stream, e.pos_in_stream) + if not root_match: + raise + + value, type_ = root_match + t = Token(type_, value, e.pos_in_stream, e.line, e.column) + raise UnexpectedToken(t, e.allowed, state=e.state) + + + +class LexerConf(Serialize): + __serialize_fields__ = 'tokens', 'ignore', 'g_regex_flags', 'use_bytes' + __serialize_namespace__ = TerminalDef, + + def __init__(self, tokens, re_module, ignore=(), postlex=None, callbacks=None, g_regex_flags=0, skip_validation=False, use_bytes=False): + self.tokens = tokens ## + + self.ignore = ignore + self.postlex = postlex + self.callbacks = callbacks or {} + self.g_regex_flags = g_regex_flags + self.re_module = re_module + self.skip_validation = skip_validation + self.use_bytes = use_bytes + + +from functools import partial, wraps +from itertools import repeat, product + + +class ExpandSingleChild: + def __init__(self, node_builder): + self.node_builder = node_builder + + def __call__(self, children): + if len(children) == 1: + return children[0] + else: + return self.node_builder(children) + +class PropagatePositions: + def __init__(self, node_builder): + self.node_builder = node_builder + + def __call__(self, children): + res = self.node_builder(children) + + ## + + if isinstance(res, Tree): + res_meta = res.meta + for c in children: + if isinstance(c, Tree): + child_meta = c.meta + if not child_meta.empty: + res_meta.line = child_meta.line + res_meta.column = child_meta.column + res_meta.start_pos = child_meta.start_pos + res_meta.empty = False + break + elif isinstance(c, Token): + res_meta.line = c.line + res_meta.column = c.column + res_meta.start_pos = c.pos_in_stream + res_meta.empty = False + break + + for c in reversed(children): + if isinstance(c, Tree): + child_meta = c.meta + if not child_meta.empty: + res_meta.end_line = child_meta.end_line + res_meta.end_column = child_meta.end_column + res_meta.end_pos = child_meta.end_pos + res_meta.empty = False + break + elif isinstance(c, Token): + res_meta.end_line = c.end_line + res_meta.end_column = c.end_column + res_meta.end_pos = c.end_pos + res_meta.empty = False + break + + return res + + +class ChildFilter: + def __init__(self, to_include, append_none, node_builder): + self.node_builder = node_builder + self.to_include = to_include + self.append_none = append_none + + def __call__(self, children): + filtered = [] + + for i, to_expand, add_none in self.to_include: + if add_none: + filtered += [None] * add_none + if to_expand: + filtered += children[i].children + else: + filtered.append(children[i]) + + if self.append_none: + filtered += [None] * self.append_none + + return self.node_builder(filtered) + +class ChildFilterLALR(ChildFilter): + #-- + + def __call__(self, children): + filtered = [] + for i, to_expand, add_none in self.to_include: + if add_none: + filtered += [None] * add_none + if to_expand: + if filtered: + filtered += children[i].children + else: ## + + filtered = children[i].children + else: + filtered.append(children[i]) + + if self.append_none: + filtered += [None] * self.append_none + + return self.node_builder(filtered) + +class ChildFilterLALR_NoPlaceholders(ChildFilter): + #-- + def __init__(self, to_include, node_builder): + self.node_builder = node_builder + self.to_include = to_include + + def __call__(self, children): + filtered = [] + for i, to_expand in self.to_include: + if to_expand: + if filtered: + filtered += children[i].children + else: ## + + filtered = children[i].children + else: + filtered.append(children[i]) + return self.node_builder(filtered) + +def _should_expand(sym): + return not sym.is_term and sym.name.startswith('_') + +def maybe_create_child_filter(expansion, keep_all_tokens, ambiguous, _empty_indices): + ## + + if _empty_indices: + assert _empty_indices.count(False) == len(expansion) + s = ''.join(str(int(b)) for b in _empty_indices) + empty_indices = [len(ones) for ones in s.split('0')] + assert len(empty_indices) == len(expansion)+1, (empty_indices, len(expansion)) + else: + empty_indices = [0] * (len(expansion)+1) + + to_include = [] + nones_to_add = 0 + for i, sym in enumerate(expansion): + nones_to_add += empty_indices[i] + if keep_all_tokens or not (sym.is_term and sym.filter_out): + to_include.append((i, _should_expand(sym), nones_to_add)) + nones_to_add = 0 + + nones_to_add += empty_indices[len(expansion)] + + if _empty_indices or len(to_include) < len(expansion) or any(to_expand for i, to_expand,_ in to_include): + if _empty_indices or ambiguous: + return partial(ChildFilter if ambiguous else ChildFilterLALR, to_include, nones_to_add) + else: + ## + + return partial(ChildFilterLALR_NoPlaceholders, [(i, x) for i,x,_ in to_include]) + +class AmbiguousExpander: + #-- + def __init__(self, to_expand, tree_class, node_builder): + self.node_builder = node_builder + self.tree_class = tree_class + self.to_expand = to_expand + + def __call__(self, children): + def _is_ambig_tree(child): + return hasattr(child, 'data') and child.data == '_ambig' + + ## + + ## + + ## + + ## + + ambiguous = [] + for i, child in enumerate(children): + if _is_ambig_tree(child): + if i in self.to_expand: + ambiguous.append(i) + + to_expand = [j for j, grandchild in enumerate(child.children) if _is_ambig_tree(grandchild)] + child.expand_kids_by_index(*to_expand) + + if not ambiguous: + return self.node_builder(children) + + expand = [ iter(child.children) if i in ambiguous else repeat(child) for i, child in enumerate(children) ] + return self.tree_class('_ambig', [self.node_builder(list(f[0])) for f in product(zip(*expand))]) + +def maybe_create_ambiguous_expander(tree_class, expansion, keep_all_tokens): + to_expand = [i for i, sym in enumerate(expansion) + if keep_all_tokens or ((not (sym.is_term and sym.filter_out)) and _should_expand(sym))] + if to_expand: + return partial(AmbiguousExpander, to_expand, tree_class) + +def ptb_inline_args(func): + @wraps(func) + def f(children): + return func(*children) + return f + +def inplace_transformer(func): + @wraps(func) + def f(children): + ## + + tree = Tree(func.__name__, children) + return func(tree) + return f + +def apply_visit_wrapper(func, name, wrapper): + if wrapper is _vargs_meta or wrapper is _vargs_meta_inline: + raise NotImplementedError("Meta args not supported for internal transformer") + @wraps(func) + def f(children): + return wrapper(func, name, children, None) + return f + + +class ParseTreeBuilder: + def __init__(self, rules, tree_class, propagate_positions=False, keep_all_tokens=False, ambiguous=False, maybe_placeholders=False): + self.tree_class = tree_class + self.propagate_positions = propagate_positions + self.always_keep_all_tokens = keep_all_tokens + self.ambiguous = ambiguous + self.maybe_placeholders = maybe_placeholders + + self.rule_builders = list(self._init_builders(rules)) + + def _init_builders(self, rules): + for rule in rules: + options = rule.options + keep_all_tokens = self.always_keep_all_tokens or options.keep_all_tokens + expand_single_child = options.expand1 + + wrapper_chain = list(filter(None, [ + (expand_single_child and not rule.alias) and ExpandSingleChild, + maybe_create_child_filter(rule.expansion, keep_all_tokens, self.ambiguous, options.empty_indices if self.maybe_placeholders else None), + self.propagate_positions and PropagatePositions, + self.ambiguous and maybe_create_ambiguous_expander(self.tree_class, rule.expansion, keep_all_tokens), + ])) + + yield rule, wrapper_chain + + + def create_callback(self, transformer=None): + callbacks = {} + + for rule, wrapper_chain in self.rule_builders: + + user_callback_name = rule.alias or rule.options.template_source or rule.origin.name + try: + f = getattr(transformer, user_callback_name) + ## + + wrapper = getattr(f, 'visit_wrapper', None) + if wrapper is not None: + f = apply_visit_wrapper(f, user_callback_name, wrapper) + else: + if isinstance(transformer, InlineTransformer): + f = ptb_inline_args(f) + elif isinstance(transformer, Transformer_InPlace): + f = inplace_transformer(f) + except AttributeError: + f = partial(self.tree_class, user_callback_name) + + for w in wrapper_chain: + f = w(f) + + if rule in callbacks: + raise GrammarError("Rule '%s' already exists" % (rule,)) + + callbacks[rule] = f + + return callbacks + + + +class LALR_Parser(object): + def __init__(self, parser_conf, debug=False): + assert all(r.options.priority is None for r in parser_conf.rules), "LALR doesn't yet support prioritization" + analysis = LALR_Analyzer(parser_conf, debug=debug) + analysis.compute_lalr() + callbacks = parser_conf.callbacks + + self._parse_table = analysis.parse_table + self.parser_conf = parser_conf + self.parser = _Parser(analysis.parse_table, callbacks, debug) + + @classmethod + def deserialize(cls, data, memo, callbacks): + inst = cls.__new__(cls) + inst._parse_table = IntParseTable.deserialize(data, memo) + inst.parser = _Parser(inst._parse_table, callbacks) + return inst + + def serialize(self, memo): + return self._parse_table.serialize(memo) + + def parse(self, *args): + return self.parser.parse(*args) + + +class _Parser: + def __init__(self, parse_table, callbacks, debug=False): + self.parse_table = parse_table + self.callbacks = callbacks + self.debug = debug + + def parse(self, seq, start, set_state=None, value_stack=None, state_stack=None): + token = None + stream = iter(seq) + states = self.parse_table.states + start_state = self.parse_table.start_states[start] + end_state = self.parse_table.end_states[start] + + state_stack = state_stack or [start_state] + value_stack = value_stack or [] + + if set_state: set_state(start_state) + + def get_action(token): + state = state_stack[-1] + try: + return states[state][token.type] + except KeyError: + expected = {s for s in states[state].keys() if s.isupper()} + try: + puppet = ParserPuppet(self, state_stack, value_stack, start, stream, set_state) + except NameError: ## + + puppet = None + raise UnexpectedToken(token, expected, state=state, puppet=puppet) + + def reduce(rule): + size = len(rule.expansion) + if size: + s = value_stack[-size:] + del state_stack[-size:] + del value_stack[-size:] + else: + s = [] + + value = self.callbacks[rule](s) + + _action, new_state = states[state_stack[-1]][rule.origin.name] + assert _action is Shift + state_stack.append(new_state) + value_stack.append(value) + + ## + + try: + for token in stream: + while True: + action, arg = get_action(token) + assert arg != end_state + + if action is Shift: + state_stack.append(arg) + value_stack.append(token) + if set_state: set_state(arg) + break ## + + else: + reduce(arg) + except Exception as e: + if self.debug: + print("") + print("STATE STACK DUMP") + print("----------------") + for i, s in enumerate(state_stack): + print('%d)' % i , s) + print("") + + raise + + token = Token.new_borrow_pos('$END', '', token) if token else Token('$END', '', 0, 1, 1) + while True: + _action, arg = get_action(token) + assert(_action is Reduce) + reduce(arg) + if state_stack[-1] == end_state: + return value_stack[-1] + + + +class Action: + def __init__(self, name): + self.name = name + def __str__(self): + return self.name + def __repr__(self): + return str(self) + +Shift = Action('Shift') +Reduce = Action('Reduce') + + +class ParseTable: + def __init__(self, states, start_states, end_states): + self.states = states + self.start_states = start_states + self.end_states = end_states + + def serialize(self, memo): + tokens = Enumerator() + rules = Enumerator() + + states = { + state: {tokens.get(token): ((1, arg.serialize(memo)) if action is Reduce else (0, arg)) + for token, (action, arg) in actions.items()} + for state, actions in self.states.items() + } + + return { + 'tokens': tokens.reversed(), + 'states': states, + 'start_states': self.start_states, + 'end_states': self.end_states, + } + + @classmethod + def deserialize(cls, data, memo): + tokens = data['tokens'] + states = { + state: {tokens[token]: ((Reduce, Rule.deserialize(arg, memo)) if action==1 else (Shift, arg)) + for token, (action, arg) in actions.items()} + for state, actions in data['states'].items() + } + return cls(states, data['start_states'], data['end_states']) + + +class IntParseTable(ParseTable): + + @classmethod + def from_ParseTable(cls, parse_table): + enum = list(parse_table.states) + state_to_idx = {s:i for i,s in enumerate(enum)} + int_states = {} + + for s, la in parse_table.states.items(): + la = {k:(v[0], state_to_idx[v[1]]) if v[0] is Shift else v + for k,v in la.items()} + int_states[ state_to_idx[s] ] = la + + + start_states = {start:state_to_idx[s] for start, s in parse_table.start_states.items()} + end_states = {start:state_to_idx[s] for start, s in parse_table.end_states.items()} + return cls(int_states, start_states, end_states) + + + +def get_frontend(parser, lexer): + if parser=='lalr': + if lexer is None: + raise ValueError('The LALR parser requires use of a lexer') + elif lexer == 'standard': + return LALR_TraditionalLexer + elif lexer == 'contextual': + return LALR_ContextualLexer + elif issubclass(lexer, Lexer): + class LALR_CustomLexerWrapper(LALR_CustomLexer): + def __init__(self, lexer_conf, parser_conf, options=None): + super(LALR_CustomLexerWrapper, self).__init__( + lexer, lexer_conf, parser_conf, options=options) + def init_lexer(self): + self.lexer = lexer(self.lexer_conf) + + return LALR_CustomLexerWrapper + else: + raise ValueError('Unknown lexer: %s' % lexer) + elif parser=='earley': + if lexer=='standard': + return Earley + elif lexer=='dynamic': + return XEarley + elif lexer=='dynamic_complete': + return XEarley_CompleteLex + elif lexer=='contextual': + raise ValueError('The Earley parser does not support the contextual parser') + else: + raise ValueError('Unknown lexer: %s' % lexer) + elif parser == 'cyk': + if lexer == 'standard': + return CYK + else: + raise ValueError('CYK parser requires using standard parser.') + else: + raise ValueError('Unknown parser: %s' % parser) + + +class _ParserFrontend(Serialize): + def _parse(self, input, start, *args): + if start is None: + start = self.start + if len(start) > 1: + raise ValueError("Lark initialized with more than 1 possible start rule. Must specify which start rule to parse", start) + start ,= start + return self.parser.parse(input, start, *args) + + +def _get_lexer_callbacks(transformer, terminals): + result = {} + for terminal in terminals: + callback = getattr(transformer, terminal.name, None) + if callback is not None: + result[terminal.name] = callback + return result + + +class WithLexer(_ParserFrontend): + lexer = None + parser = None + lexer_conf = None + start = None + + __serialize_fields__ = 'parser', 'lexer_conf', 'start' + __serialize_namespace__ = LexerConf, + + def __init__(self, lexer_conf, parser_conf, options=None): + self.lexer_conf = lexer_conf + self.start = parser_conf.start + self.postlex = lexer_conf.postlex + + @classmethod + def deserialize(cls, data, memo, callbacks, postlex, transformer, re_module): + inst = super(WithLexer, cls).deserialize(data, memo) + + inst.postlex = postlex + inst.parser = LALR_Parser.deserialize(inst.parser, memo, callbacks) + + terminals = [item for item in memo.values() if isinstance(item, TerminalDef)] + inst.lexer_conf.callbacks = _get_lexer_callbacks(transformer, terminals) + inst.lexer_conf.re_module = re_module + inst.lexer_conf.skip_validation=True + inst.init_lexer() + + return inst + + def _serialize(self, data, memo): + data['parser'] = data['parser'].serialize(memo) + + def lex(self, *args): + stream = self.lexer.lex(*args) + return self.postlex.process(stream) if self.postlex else stream + + def parse(self, text, start=None): + token_stream = self.lex(text) + return self._parse(token_stream, start) + + def init_traditional_lexer(self): + self.lexer = TraditionalLexer(self.lexer_conf) + +class LALR_WithLexer(WithLexer): + def __init__(self, lexer_conf, parser_conf, options=None): + debug = options.debug if options else False + self.parser = LALR_Parser(parser_conf, debug=debug) + WithLexer.__init__(self, lexer_conf, parser_conf, options) + + self.init_lexer() + + def init_lexer(self, **kw): + raise NotImplementedError() + +class LALR_TraditionalLexer(LALR_WithLexer): + def init_lexer(self): + self.init_traditional_lexer() + +class LALR_ContextualLexer(LALR_WithLexer): + def init_lexer(self): + states = {idx:list(t.keys()) for idx, t in self.parser._parse_table.states.items()} + always_accept = self.postlex.always_accept if self.postlex else () + self.lexer = ContextualLexer(self.lexer_conf, states, always_accept=always_accept) + + + def parse(self, text, start=None): + parser_state = [None] + def set_parser_state(s): + parser_state[0] = s + + token_stream = self.lex(text, lambda: parser_state[0]) + return self._parse(token_stream, start, set_parser_state) + + +class LarkOptions(Serialize): + #-- + OPTIONS_DOC = """ + **=== General ===** + + start + The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start") + debug + Display debug information, such as warnings (default: False) + transformer + Applies the transformer to every parse tree (equivlent to applying it after the parse, but faster) + propagate_positions + Propagates (line, column, end_line, end_column) attributes into all tree branches. + maybe_placeholders + When True, the ``[]`` operator returns ``None`` when not matched. + + When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all. + (default= ``False``. Recommended to set to ``True``) + regex + When True, uses the ``regex`` module instead of the stdlib ``re``. + cache + Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now. + + - When ``False``, does nothing (default) + - When ``True``, caches to a temporary file in the local directory + - When given a string, caches to the path pointed by the string + + g_regex_flags + Flags that are applied to all terminals (both regex and strings) + keep_all_tokens + Prevent the tree builder from automagically removing "punctuation" tokens (default: False) + + **=== Algorithm ===** + + parser + Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley"). + (there is also a "cyk" option for legacy) + lexer + Decides whether or not to use a lexer stage + + - "auto" (default): Choose for me based on the parser + - "standard": Use a standard lexer + - "contextual": Stronger lexer (only works with parser="lalr") + - "dynamic": Flexible and powerful (only with parser="earley") + - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible. + ambiguity + Decides how to handle ambiguity in the parse. Only relevant if parser="earley" + + - "resolve" - The parser will automatically choose the simplest derivation + (it chooses consistently: greedy for tokens, non-greedy for rules) + - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest). + + **=== Misc. / Domain Specific ===** + + postlex + Lexer post-processing (Default: None) Only works with the standard and contextual lexers. + priority + How priorities should be evaluated - auto, none, normal, invert (Default: auto) + lexer_callbacks + Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution. + use_bytes + Accept an input of type ``bytes`` instead of ``str`` (Python 3 only). + edit_terminals + A callback for editing the terminals before parse. + """ + if __doc__: + __doc__ += OPTIONS_DOC + + _defaults = { + 'debug': False, + 'keep_all_tokens': False, + 'tree_class': None, + 'cache': False, + 'postlex': None, + 'parser': 'earley', + 'lexer': 'auto', + 'transformer': None, + 'start': 'start', + 'priority': 'auto', + 'ambiguity': 'auto', + 'regex': False, + 'propagate_positions': False, + 'lexer_callbacks': {}, + 'maybe_placeholders': False, + 'edit_terminals': None, + 'g_regex_flags': 0, + 'use_bytes': False, + } + + def __init__(self, options_dict): + o = dict(options_dict) + + options = {} + for name, default in self._defaults.items(): + if name in o: + value = o.pop(name) + if isinstance(default, bool) and name not in ('cache', 'use_bytes'): + value = bool(value) + else: + value = default + + options[name] = value + + if isinstance(options['start'], STRING_TYPE): + options['start'] = [options['start']] + + self.__dict__['options'] = options + + assert self.parser in ('earley', 'lalr', 'cyk', None) + + if self.parser == 'earley' and self.transformer: + raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.' + 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)') + + if o: + raise ValueError("Unknown options: %s" % o.keys()) + + def __getattr__(self, name): + try: + return self.options[name] + except KeyError as e: + raise AttributeError(e) + + def __setattr__(self, name, value): + assert name in self.options + self.options[name] = value + + def serialize(self, memo): + return self.options + + @classmethod + def deserialize(cls, data, memo): + return cls(data) + + +class Lark(Serialize): + #-- + def __init__(self, grammar, **options): + self.options = LarkOptions(options) + + ## + + use_regex = self.options.regex + if use_regex: + if regex: + re_module = regex + else: + raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.') + else: + re_module = re + + ## + + try: + self.source = grammar.name + except AttributeError: + self.source = '' + + ## + + try: + read = grammar.read + except AttributeError: + pass + else: + grammar = read() + + assert isinstance(grammar, STRING_TYPE) + self.grammar_source = grammar + if self.options.use_bytes: + if not isascii(grammar): + raise ValueError("Grammar must be ascii only, when use_bytes=True") + if sys.version_info[0] == 2 and self.options.use_bytes != 'force': + raise NotImplementedError("`use_bytes=True` may have issues on python2." + "Use `use_bytes='force'` to use it at your own risk.") + + cache_fn = None + if self.options.cache: + if self.options.parser != 'lalr': + raise NotImplementedError("cache only works with parser='lalr' for now") + if isinstance(self.options.cache, STRING_TYPE): + cache_fn = self.options.cache + else: + if self.options.cache is not True: + raise ValueError("cache argument must be bool or str") + unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals') + from . import __version__ + options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable) + s = grammar + options_str + __version__ + md5 = hashlib.md5(s.encode()).hexdigest() + cache_fn = '.lark_cache_%s.tmp' % md5 + + if FS.exists(cache_fn): + logger.debug('Loading grammar from cache: %s', cache_fn) + with FS.open(cache_fn, 'rb') as f: + self._load(f, self.options.transformer, self.options.postlex) + return + + if self.options.lexer == 'auto': + if self.options.parser == 'lalr': + self.options.lexer = 'contextual' + elif self.options.parser == 'earley': + self.options.lexer = 'dynamic' + elif self.options.parser == 'cyk': + self.options.lexer = 'standard' + else: + assert False, self.options.parser + lexer = self.options.lexer + assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer) + + if self.options.ambiguity == 'auto': + if self.options.parser == 'earley': + self.options.ambiguity = 'resolve' + else: + disambig_parsers = ['earley', 'cyk'] + assert self.options.parser in disambig_parsers, ( + 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers) + + if self.options.priority == 'auto': + if self.options.parser in ('earley', 'cyk', ): + self.options.priority = 'normal' + elif self.options.parser in ('lalr', ): + self.options.priority = None + elif self.options.priority in ('invert', 'normal'): + assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time" + + assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority) + assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"' + assert self.options.ambiguity in ('resolve', 'explicit', 'auto', ) + + ## + + self.grammar = load_grammar(grammar, self.source, re_module) + + ## + + self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start) + + if self.options.edit_terminals: + for t in self.terminals: + self.options.edit_terminals(t) + + self._terminals_dict = {t.name: t for t in self.terminals} + + ## + + ## + + if self.options.priority == 'invert': + for rule in self.rules: + if rule.options.priority is not None: + rule.options.priority = -rule.options.priority + ## + + ## + + ## + + elif self.options.priority == None: + for rule in self.rules: + if rule.options.priority is not None: + rule.options.priority = None + + ## + + lexer_callbacks = (_get_lexer_callbacks(self.options.transformer, self.terminals) + if self.options.transformer + else {}) + lexer_callbacks.update(self.options.lexer_callbacks) + + self.lexer_conf = LexerConf(self.terminals, re_module, self.ignore_tokens, self.options.postlex, lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes) + + if self.options.parser: + self.parser = self._build_parser() + elif lexer: + self.lexer = self._build_lexer() + + if cache_fn: + logger.debug('Saving grammar to cache: %s', cache_fn) + with FS.open(cache_fn, 'wb') as f: + self.save(f) + + ## + + __doc__ += "\nOptions:\n" + LarkOptions.OPTIONS_DOC + + __serialize_fields__ = 'parser', 'rules', 'options' + + def _build_lexer(self): + return TraditionalLexer(self.lexer_conf) + + def _prepare_callbacks(self): + self.parser_class = get_frontend(self.options.parser, self.options.lexer) + self._parse_tree_builder = ParseTreeBuilder(self.rules, self.options.tree_class or Tree, self.options.propagate_positions, self.options.keep_all_tokens, self.options.parser!='lalr' and self.options.ambiguity=='explicit', self.options.maybe_placeholders) + self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer) + + def _build_parser(self): + self._prepare_callbacks() + parser_conf = ParserConf(self.rules, self._callbacks, self.options.start) + return self.parser_class(self.lexer_conf, parser_conf, options=self.options) + + def save(self, f): + #-- + data, m = self.memo_serialize([TerminalDef, Rule]) + pickle.dump({'data': data, 'memo': m}, f) + + @classmethod + def load(cls, f): + #-- + inst = cls.__new__(cls) + return inst._load(f) + + def _load(self, f, transformer=None, postlex=None): + if isinstance(f, dict): + d = f + else: + d = pickle.load(f) + memo = d['memo'] + data = d['data'] + + assert memo + memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {}) + options = dict(data['options']) + if transformer is not None: + options['transformer'] = transformer + if postlex is not None: + options['postlex'] = postlex + self.options = LarkOptions.deserialize(options, memo) + re_module = regex if self.options.regex else re + self.rules = [Rule.deserialize(r, memo) for r in data['rules']] + self.source = '' + self._prepare_callbacks() + self.parser = self.parser_class.deserialize( + data['parser'], + memo, + self._callbacks, + self.options.postlex, + self.options.transformer, + re_module + ) + return self + + @classmethod + def _load_from_dict(cls, data, memo, transformer=None, postlex=None): + inst = cls.__new__(cls) + return inst._load({'data': data, 'memo': memo}, transformer, postlex) + + @classmethod + def open(cls, grammar_filename, rel_to=None, **options): + #-- + if rel_to: + basepath = os.path.dirname(rel_to) + grammar_filename = os.path.join(basepath, grammar_filename) + with open(grammar_filename, encoding='utf8') as f: + return cls(f, **options) + + def __repr__(self): + return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer) + + + def lex(self, text): + #-- + if not hasattr(self, 'lexer'): + self.lexer = self._build_lexer() + stream = self.lexer.lex(text) + if self.options.postlex: + return self.options.postlex.process(stream) + return stream + + def get_terminal(self, name): + #-- + return self._terminals_dict[name] + + def parse(self, text, start=None, on_error=None): + #-- + + try: + return self.parser.parse(text, start=start) + except UnexpectedToken as e: + if on_error is None: + raise + + while True: + if not on_error(e): + raise e + try: + return e.puppet.resume_parse() + except UnexpectedToken as e2: + e = e2 + + + +DATA = ( +{'parser': {'parser': {'tokens': {0: 'RBRACE', 1: 'COMMA', 2: 'RSQB', 3: '$END', 4: '__object_star_1', 5: 'COLON', 6: 'LBRACE', 7: 'value', 8: 'string', 9: 'object', 10: 'TRUE', 11: 'SIGNED_NUMBER', 12: 'LSQB', 13: 'NULL', 14: 'FALSE', 15: 'array', 16: 'ESCAPED_STRING', 17: '__array_star_0', 18: 'pair', 19: 'start'}, 'states': {0: {0: (1, {'@': 12}), 1: (1, {'@': 12})}, 1: {1: (1, {'@': 13}), 2: (1, {'@': 13}), 0: (1, {'@': 13}), 3: (1, {'@': 13})}, 2: {1: (1, {'@': 14}), 2: (1, {'@': 14}), 0: (1, {'@': 14}), 3: (1, {'@': 14})}, 3: {0: (0, 25), 1: (0, 32)}, 4: {4: (0, 3), 1: (0, 27), 0: (0, 33)}, 5: {0: (1, {'@': 15}), 1: (1, {'@': 15})}, 6: {}, 7: {1: (0, 23), 2: (0, 2)}, 8: {1: (1, {'@': 16}), 2: (1, {'@': 16})}, 9: {1: (1, {'@': 17}), 2: (1, {'@': 17}), 5: (1, {'@': 17}), 0: (1, {'@': 17}), 3: (1, {'@': 17})}, 10: {1: (1, {'@': 18}), 2: (1, {'@': 18}), 0: (1, {'@': 18}), 3: (1, {'@': 18})}, 11: {1: (1, {'@': 19}), 2: (1, {'@': 19}), 0: (1, {'@': 19}), 3: (1, {'@': 19})}, 12: {1: (1, {'@': 20}), 2: (1, {'@': 20}), 0: (1, {'@': 20}), 3: (1, {'@': 20})}, 13: {5: (0, 22)}, 14: {6: (0, 21), 7: (0, 29), 8: (0, 12), 9: (0, 1), 10: (0, 16), 11: (0, 11), 12: (0, 26), 13: (0, 30), 14: (0, 15), 15: (0, 10), 16: (0, 9)}, 15: {1: (1, {'@': 21}), 2: (1, {'@': 21}), 0: (1, {'@': 21}), 3: (1, {'@': 21})}, 16: {1: (1, {'@': 22}), 2: (1, {'@': 22}), 0: (1, {'@': 22}), 3: (1, {'@': 22})}, 17: {1: (1, {'@': 23}), 2: (1, {'@': 23}), 0: (1, {'@': 23}), 3: (1, {'@': 23})}, 18: {2: (0, 24), 1: (0, 14), 17: (0, 7)}, 19: {1: (1, {'@': 24}), 2: (1, {'@': 24}), 0: (1, {'@': 24}), 3: (1, {'@': 24})}, 20: {0: (1, {'@': 25}), 1: (1, {'@': 25})}, 21: {8: (0, 13), 18: (0, 4), 16: (0, 9), 0: (0, 19)}, 22: {6: (0, 21), 8: (0, 12), 9: (0, 1), 10: (0, 16), 11: (0, 11), 12: (0, 26), 13: (0, 30), 14: (0, 15), 15: (0, 10), 7: (0, 20), 16: (0, 9)}, 23: {6: (0, 21), 7: (0, 8), 9: (0, 1), 8: (0, 12), 10: (0, 16), 11: (0, 11), 12: (0, 26), 13: (0, 30), 14: (0, 15), 15: (0, 10), 16: (0, 9)}, 24: {1: (1, {'@': 26}), 2: (1, {'@': 26}), 0: (1, {'@': 26}), 3: (1, {'@': 26})}, 25: {1: (1, {'@': 27}), 2: (1, {'@': 27}), 0: (1, {'@': 27}), 3: (1, {'@': 27})}, 26: {6: (0, 21), 10: (0, 16), 12: (0, 26), 13: (0, 30), 14: (0, 15), 7: (0, 18), 8: (0, 12), 16: (0, 9), 9: (0, 1), 11: (0, 11), 15: (0, 10), 2: (0, 17)}, 27: {8: (0, 13), 18: (0, 0), 16: (0, 9)}, 28: {6: (0, 21), 10: (0, 16), 12: (0, 26), 13: (0, 30), 8: (0, 12), 16: (0, 9), 19: (0, 6), 9: (0, 1), 11: (0, 11), 7: (0, 31), 15: (0, 10), 14: (0, 15)}, 29: {1: (1, {'@': 28}), 2: (1, {'@': 28})}, 30: {1: (1, {'@': 29}), 2: (1, {'@': 29}), 0: (1, {'@': 29}), 3: (1, {'@': 29})}, 31: {3: (1, {'@': 30})}, 32: {18: (0, 5), 8: (0, 13), 16: (0, 9)}, 33: {1: (1, {'@': 31}), 2: (1, {'@': 31}), 0: (1, {'@': 31}), 3: (1, {'@': 31})}}, 'start_states': {'start': 28}, 'end_states': {'start': 6}}, 'lexer_conf': {'tokens': [{'@': 0}, {'@': 1}, {'@': 2}, {'@': 3}, {'@': 4}, {'@': 5}, {'@': 6}, {'@': 7}, {'@': 8}, {'@': 9}, {'@': 10}, {'@': 11}], 'ignore': ['WS'], 'g_regex_flags': 0, 'use_bytes': False, '__type__': 'LexerConf'}, 'start': ['start'], '__type__': 'LALR_ContextualLexer'}, 'rules': [{'@': 30}, {'@': 13}, {'@': 18}, {'@': 20}, {'@': 19}, {'@': 22}, {'@': 21}, {'@': 29}, {'@': 14}, {'@': 26}, {'@': 23}, {'@': 27}, {'@': 31}, {'@': 24}, {'@': 25}, {'@': 17}, {'@': 28}, {'@': 16}, {'@': 12}, {'@': 15}], 'options': {'debug': False, 'keep_all_tokens': False, 'tree_class': None, 'cache': False, 'postlex': None, 'parser': 'lalr', 'lexer': 'contextual', 'transformer': None, 'start': ['start'], 'priority': None, 'ambiguity': 'auto', 'regex': False, 'propagate_positions': False, 'lexer_callbacks': {}, 'maybe_placeholders': False, 'edit_terminals': None, 'g_regex_flags': 0, 'use_bytes': False}, '__type__': 'Lark'} +) +MEMO = ( +{0: {'name': 'ESCAPED_STRING', 'pattern': {'value': '\\".*?(? movement + | "c" COLOR [COLOR] -> change_color + | "fill" code_block -> fill + | "repeat" NUMBER code_block -> repeat + + code_block: "{" instruction+ "}" + + MOVEMENT: "f"|"b"|"l"|"r" + COLOR: LETTER+ + + %import common.LETTER + %import common.INT -> NUMBER + %import common.WS + %ignore WS +""" + +parser = Lark(turtle_grammar) + +def run_instruction(t): + if t.data == 'change_color': + turtle.color(*t.children) # We just pass the color names as-is + + elif t.data == 'movement': + name, number = t.children + { 'f': turtle.fd, + 'b': turtle.bk, + 'l': turtle.lt, + 'r': turtle.rt, }[name](int(number)) + + elif t.data == 'repeat': + count, block = t.children + for i in range(int(count)): + run_instruction(block) + + elif t.data == 'fill': + turtle.begin_fill() + run_instruction(t.children[0]) + turtle.end_fill() + + elif t.data == 'code_block': + for cmd in t.children: + run_instruction(cmd) + else: + raise SyntaxError('Unknown instruction: %s' % t.data) + + +def run_turtle(program): + parse_tree = parser.parse(program) + for inst in parse_tree.children: + run_instruction(inst) + +def main(): + while True: + code = input('> ') + try: + run_turtle(code) + except Exception as e: + print(e) + +def test(): + text = """ + c red yellow + fill { repeat 36 { + f200 l170 + }} + """ + run_turtle(text) + +if __name__ == '__main__': + # test() + main() diff --git a/testbed/lark-parser__lark/lark-stubs/exceptions.pyi b/testbed/lark-parser__lark/lark-stubs/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..587d60ad0ddc91d524a379cb1d431bc6640483e3 --- /dev/null +++ b/testbed/lark-parser__lark/lark-stubs/exceptions.pyi @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- + +from typing import Dict, Iterable, Callable, Union, TypeVar, Tuple, Any, List, Set +from .tree import Tree +from .lexer import Token +from .parsers.lalr_puppet import ParserPuppet + +class LarkError(Exception): + pass + + +class GrammarError(LarkError): + pass + + +class ParseError(LarkError): + pass + + +class LexError(LarkError): + pass + + +T = TypeVar('T') + +class UnexpectedEOF(ParseError): + expected: List[Token] + +class UnexpectedInput(LarkError): + line: int + column: int + pos_in_stream: int + state: Any + + def get_context(self, text: str, span: int = ...): + ... + + def match_examples( + self, + parse_fn: Callable[[str], Tree], + examples: Union[Dict[T, Iterable[str]], Iterable[Tuple[T, Iterable[str]]]], + token_type_match_fallback: bool = False, + use_accepts: bool = False, + ) -> T: + ... + + +class UnexpectedToken(ParseError, UnexpectedInput): + expected: Set[str] + considered_rules: Set[str] + puppet: ParserPuppet + accepts: Set[str] + +class UnexpectedCharacters(LexError, UnexpectedInput): + allowed: Set[str] + considered_tokens: Set[Any] + + +class VisitError(LarkError): + obj: Union[Tree, Token] + orig_exc: Exception diff --git a/testbed/lark-parser__lark/lark-stubs/reconstruct.pyi b/testbed/lark-parser__lark/lark-stubs/reconstruct.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2220c46a79cd3bc8cb0726fea6db6107f567bc80 --- /dev/null +++ b/testbed/lark-parser__lark/lark-stubs/reconstruct.pyi @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +from typing import List, Dict, Union +from .lark import Lark +from .tree import Tree +from .visitors import Transformer_InPlace +from .lexer import TerminalDef + + +class WriteTokensTransformer(Transformer_InPlace): + + def __init__(self, tokens: Dict[str, TerminalDef], term_subs): + ... + + +class MatchTree(Tree): + pass + + +class MakeMatchTree: + name: str + expansion: List[TerminalDef] + + def __init__(self, name: str, expansion: List[TerminalDef]): + ... + + def __call__(self, args: List[Union[str, Tree]]): + ... + + +class Reconstructor: + + def __init__(self, parser: Lark, term_subs: Dict[str, str] = ...): + ... + + def reconstruct(self, tree: Tree) -> str: + ... diff --git a/testbed/lark-parser__lark/lark-stubs/tree.pyi b/testbed/lark-parser__lark/lark-stubs/tree.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a24ab3519b503cc11c108f2e2f3a078aae708345 --- /dev/null +++ b/testbed/lark-parser__lark/lark-stubs/tree.pyi @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- + +from typing import List, Callable, Iterator, Union, Optional, Literal +from .lexer import TerminalDef + +class Meta: + empty: bool + line: int + column: int + start_pos: int + end_line: int + end_column: int + end_pos: int + orig_expansion: List[TerminalDef] + match_tree: bool + + +class Tree: + data: str + children: List[Union[str, Tree]] + meta: Meta + + def __init__( + self, + data: str, + children: List[Union[str, Tree]], + meta: Optional[Meta] = None + ): + ... + + def pretty(self, indent_str: str = ...) -> str: + ... + + def find_pred(self, pred: Callable[[Tree], bool]) -> Iterator[Tree]: + ... + + def find_data(self, data: str) -> Iterator[Tree]: + ... + + def expand_kids_by_index(self, *indices: int) -> None: + ... + + def scan_values(self, pred: Callable[[Union[str, Tree]], bool]): + ... + + def iter_subtrees(self) -> Iterator[Tree]: + ... + + def iter_subtrees_topdown(self) -> Iterator[Tree]: + ... + + def copy(self) -> Tree: + ... + + def set(self, data: str, children: List[Union[str, Tree]]) -> None: + ... + + def __hash__(self) -> int: + ... + + +class SlottedTree(Tree): + pass + + +def pydot__tree_to_png( + tree: Tree, + filename: str, + rankdir: Literal["TB", "LR", "BT", "RL"] = ..., + **kwargs +) -> None: + ... diff --git a/testbed/lark-parser__lark/lark-stubs/visitors.pyi b/testbed/lark-parser__lark/lark-stubs/visitors.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2aafd2ed3fb456ac55c388fe600807c96135e40b --- /dev/null +++ b/testbed/lark-parser__lark/lark-stubs/visitors.pyi @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- + +from typing import TypeVar, Tuple, List, Callable, Generic, Type +from abc import ABC +from .tree import Tree + +_T = TypeVar('_T') +_R = TypeVar('_R') +_FUNC = Callable[..., _T] + + +class Transformer(ABC, Generic[_T]): + + def __init__(self, visit_tokens: bool = True): + ... + + def transform(self, tree: Tree) -> _T: + ... + + def __mul__(self, other: Transformer[_T]) -> TransformerChain[_T]: + ... + + +class TransformerChain(Generic[_T]): + transformers: Tuple[Transformer[_T], ...] + + def __init__(self, *transformers: Transformer[_T]): + ... + + def transform(self, tree: Tree) -> _T: + ... + + def __mul__(self, other: Transformer[_T]) -> TransformerChain[_T]: + ... + + +class Transformer_InPlace(Transformer): + pass + + +class VisitorBase: + pass + + +class Visitor(VisitorBase, ABC, Generic[_T]): + + def visit(self, tree: Tree) -> Tree: + ... + + def visit_topdown(self, tree: Tree) -> Tree: + ... + + +class Visitor_Recursive(VisitorBase): + + def visit(self, tree: Tree) -> Tree: + ... + + def visit_topdown(self, tree: Tree) -> Tree: + ... + + +class Interpreter(ABC, Generic[_T]): + + def visit(self, tree: Tree) -> _T: + ... + + def visit_children(self, tree: Tree) -> List[_T]: + ... + + +_InterMethod = Callable[[Type[Interpreter], _T], _R] + + +def v_args( + inline: bool = False, + meta: bool = False, + tree: bool = False +) -> Callable[[_FUNC], _FUNC]: + ... + + +def visit_children_decor(func: _InterMethod) -> _InterMethod: + ... + + +class Discard(Exception): + pass + + +# Deprecated +class InlineTransformer: + pass + + +# Deprecated +def inline_args(obj: _FUNC) -> _FUNC: + ... diff --git a/testbed/lark-parser__lark/lark/__init__.py b/testbed/lark-parser__lark/lark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0ba4d2b983683af9ca4faef7c64f9273d88790 --- /dev/null +++ b/testbed/lark-parser__lark/lark/__init__.py @@ -0,0 +1,10 @@ +from .utils import logger +from .tree import Tree +from .visitors import Transformer, Visitor, v_args, Discard +from .visitors import InlineTransformer, inline_args # XXX Deprecated +from .exceptions import (ParseError, LexError, GrammarError, UnexpectedToken, + UnexpectedInput, UnexpectedCharacters, LarkError) +from .lexer import Token +from .lark import Lark + +__version__ = "0.10.1" diff --git a/testbed/lark-parser__lark/lark/__pyinstaller/__init__.py b/testbed/lark-parser__lark/lark/__pyinstaller/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa02fc9233c5711d590f24683eb1e8a724241766 --- /dev/null +++ b/testbed/lark-parser__lark/lark/__pyinstaller/__init__.py @@ -0,0 +1,6 @@ +# For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html + +import os + +def get_hook_dirs(): + return [os.path.dirname(__file__)] \ No newline at end of file diff --git a/testbed/lark-parser__lark/lark/__pyinstaller/hook-lark.py b/testbed/lark-parser__lark/lark/__pyinstaller/hook-lark.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3d8e3d16090a57aba10da2eaec4ddb268fe7d1 --- /dev/null +++ b/testbed/lark-parser__lark/lark/__pyinstaller/hook-lark.py @@ -0,0 +1,14 @@ +#----------------------------------------------------------------------------- +# Copyright (c) 2017-2020, PyInstaller Development Team. +# +# Distributed under the terms of the GNU General Public License (version 2 +# or later) with exception for distributing the bootloader. +# +# The full license is in the file COPYING.txt, distributed with this software. +# +# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) +#----------------------------------------------------------------------------- + +from PyInstaller.utils.hooks import collect_data_files + +datas = collect_data_files('lark') diff --git a/testbed/lark-parser__lark/lark/common.py b/testbed/lark-parser__lark/lark/common.py new file mode 100644 index 0000000000000000000000000000000000000000..714399a797218932fa6abc34a58dc05a03283021 --- /dev/null +++ b/testbed/lark-parser__lark/lark/common.py @@ -0,0 +1,29 @@ +from .utils import Serialize +from .lexer import TerminalDef + +###{standalone + +class LexerConf(Serialize): + __serialize_fields__ = 'tokens', 'ignore', 'g_regex_flags', 'use_bytes' + __serialize_namespace__ = TerminalDef, + + def __init__(self, tokens, re_module, ignore=(), postlex=None, callbacks=None, g_regex_flags=0, skip_validation=False, use_bytes=False): + self.tokens = tokens # TODO should be terminals + self.ignore = ignore + self.postlex = postlex + self.callbacks = callbacks or {} + self.g_regex_flags = g_regex_flags + self.re_module = re_module + self.skip_validation = skip_validation + self.use_bytes = use_bytes + +###} + +class ParserConf: + def __init__(self, rules, callbacks, start): + assert isinstance(start, list) + self.rules = rules + self.callbacks = callbacks + self.start = start + + diff --git a/testbed/lark-parser__lark/lark/exceptions.py b/testbed/lark-parser__lark/lark/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..62883983addf7432d082c61bac246115efd4bc56 --- /dev/null +++ b/testbed/lark-parser__lark/lark/exceptions.py @@ -0,0 +1,181 @@ +from .utils import STRING_TYPE, logger + +###{standalone + + +class LarkError(Exception): + pass + +class GrammarError(LarkError): + pass + +class ParseError(LarkError): + pass + +class LexError(LarkError): + pass + +class UnexpectedEOF(ParseError): + def __init__(self, expected): + self.expected = expected + + message = ("Unexpected end-of-input. Expected one of: \n\t* %s\n" % '\n\t* '.join(x.name for x in self.expected)) + super(UnexpectedEOF, self).__init__(message) + + +class UnexpectedInput(LarkError): + """UnexpectedInput Error. + + Used as a base class for the following exceptions: + + - ``UnexpectedToken``: The parser recieved an unexpected token + - ``UnexpectedCharacters``: The lexer encountered an unexpected string + + After catching one of these exceptions, you may call the following helper methods to create a nicer error message. + """ + pos_in_stream = None + + def get_context(self, text, span=40): + """Returns a pretty string pinpointing the error in the text, + with span amount of context characters around it. + + Note: + The parser doesn't hold a copy of the text it has to parse, + so you have to provide it again + """ + pos = self.pos_in_stream + start = max(pos - span, 0) + end = pos + span + if not isinstance(text, bytes): + before = text[start:pos].rsplit('\n', 1)[-1] + after = text[pos:end].split('\n', 1)[0] + return before + after + '\n' + ' ' * len(before.expandtabs()) + '^\n' + else: + before = text[start:pos].rsplit(b'\n', 1)[-1] + after = text[pos:end].split(b'\n', 1)[0] + return (before + after + b'\n' + b' ' * len(before.expandtabs()) + b'^\n').decode("ascii", "backslashreplace") + + def match_examples(self, parse_fn, examples, token_type_match_fallback=False, use_accepts=False): + """Allows you to detect what's wrong in the input text by matching + against example errors. + + Given a parser instance and a dictionary mapping some label with + some malformed syntax examples, it'll return the label for the + example that bests matches the current error. The function will + iterate the dictionary until it finds a matching error, and + return the corresponding value. + + For an example usage, see `examples/error_reporting_lalr.py` + + Parameters: + parse_fn: parse function (usually ``lark_instance.parse``) + examples: dictionary of ``{'example_string': value}``. + use_accepts: Recommended to call this with ``use_accepts=True``. + The default is ``False`` for backwards compatibility. + """ + assert self.state is not None, "Not supported for this exception" + + if isinstance(examples, dict): + examples = examples.items() + + candidate = (None, False) + for i, (label, example) in enumerate(examples): + assert not isinstance(example, STRING_TYPE) + + for j, malformed in enumerate(example): + try: + parse_fn(malformed) + except UnexpectedInput as ut: + if ut.state == self.state: + if use_accepts and ut.accepts != self.accepts: + logger.debug("Different accepts with same state[%d]: %s != %s at example [%s][%s]" % + (self.state, self.accepts, ut.accepts, i, j)) + continue + try: + if ut.token == self.token: # Try exact match first + logger.debug("Exact Match at example [%s][%s]" % (i, j)) + return label + + if token_type_match_fallback: + # Fallback to token types match + if (ut.token.type == self.token.type) and not candidate[-1]: + logger.debug("Token Type Fallback at example [%s][%s]" % (i, j)) + candidate = label, True + + except AttributeError: + pass + if not candidate[0]: + logger.debug("Same State match at example [%s][%s]" % (i, j)) + candidate = label, False + + return candidate[0] + + +class UnexpectedCharacters(LexError, UnexpectedInput): + def __init__(self, seq, lex_pos, line, column, allowed=None, considered_tokens=None, state=None, token_history=None): + self.line = line + self.column = column + self.pos_in_stream = lex_pos + self.state = state + + self.allowed = allowed + self.considered_tokens = considered_tokens + + if isinstance(seq, bytes): + _s = seq[lex_pos:lex_pos+1].decode("ascii", "backslashreplace") + else: + _s = seq[lex_pos] + + message = "No terminal defined for '%s' at line %d col %d" % (_s, line, column) + message += '\n\n' + self.get_context(seq) + if allowed: + message += '\nExpecting: %s\n' % allowed + if token_history: + message += '\nPrevious tokens: %s\n' % ', '.join(repr(t) for t in token_history) + + super(UnexpectedCharacters, self).__init__(message) + + +class UnexpectedToken(ParseError, UnexpectedInput): + """When the parser throws UnexpectedToken, it instanciates a puppet + with its internal state. Users can then interactively set the puppet to + the desired puppet state, and resume regular parsing. + + see: :ref:`ParserPuppet`. + """ + def __init__(self, token, expected, considered_rules=None, state=None, puppet=None): + self.line = getattr(token, 'line', '?') + self.column = getattr(token, 'column', '?') + self.pos_in_stream = getattr(token, 'pos_in_stream', None) + self.state = state + + self.token = token + self.expected = expected # XXX deprecate? `accepts` is better + self.considered_rules = considered_rules + self.puppet = puppet + + # TODO Only calculate `accepts()` when we need to display it to the user + # This will improve performance when doing automatic error handling + self.accepts = puppet and puppet.accepts() + + message = ("Unexpected token %r at line %s, column %s.\n" + "Expected one of: \n\t* %s\n" + % (token, self.line, self.column, '\n\t* '.join(self.accepts or self.expected))) + + super(UnexpectedToken, self).__init__(message) + + +class VisitError(LarkError): + """VisitError is raised when visitors are interrupted by an exception + + It provides the following attributes for inspection: + - obj: the tree node or token it was processing when the exception was raised + - orig_exc: the exception that cause it to fail + """ + def __init__(self, rule, obj, orig_exc): + self.obj = obj + self.orig_exc = orig_exc + + message = 'Error trying to process rule "%s":\n\n%s' % (rule, orig_exc) + super(VisitError, self).__init__(message) +###} diff --git a/testbed/lark-parser__lark/lark/grammar.py b/testbed/lark-parser__lark/lark/grammar.py new file mode 100644 index 0000000000000000000000000000000000000000..bb8435138f57293b02b78e075a41c22c41f1f9bd --- /dev/null +++ b/testbed/lark-parser__lark/lark/grammar.py @@ -0,0 +1,108 @@ +from .utils import Serialize + +###{standalone + +class Symbol(Serialize): + __slots__ = ('name',) + + is_term = NotImplemented + + def __init__(self, name): + self.name = name + + def __eq__(self, other): + assert isinstance(other, Symbol), other + return self.is_term == other.is_term and self.name == other.name + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(self.name) + + def __repr__(self): + return '%s(%r)' % (type(self).__name__, self.name) + + fullrepr = property(__repr__) + + +class Terminal(Symbol): + __serialize_fields__ = 'name', 'filter_out' + + is_term = True + + def __init__(self, name, filter_out=False): + self.name = name + self.filter_out = filter_out + + @property + def fullrepr(self): + return '%s(%r, %r)' % (type(self).__name__, self.name, self.filter_out) + + + +class NonTerminal(Symbol): + __serialize_fields__ = 'name', + + is_term = False + + + +class RuleOptions(Serialize): + __serialize_fields__ = 'keep_all_tokens', 'expand1', 'priority', 'template_source', 'empty_indices' + + def __init__(self, keep_all_tokens=False, expand1=False, priority=None, template_source=None, empty_indices=()): + self.keep_all_tokens = keep_all_tokens + self.expand1 = expand1 + self.priority = priority + self.template_source = template_source + self.empty_indices = empty_indices + + def __repr__(self): + return 'RuleOptions(%r, %r, %r, %r)' % ( + self.keep_all_tokens, + self.expand1, + self.priority, + self.template_source + ) + + +class Rule(Serialize): + """ + origin : a symbol + expansion : a list of symbols + order : index of this expansion amongst all rules of the same name + """ + __slots__ = ('origin', 'expansion', 'alias', 'options', 'order', '_hash') + + __serialize_fields__ = 'origin', 'expansion', 'order', 'alias', 'options' + __serialize_namespace__ = Terminal, NonTerminal, RuleOptions + + def __init__(self, origin, expansion, order=0, alias=None, options=None): + self.origin = origin + self.expansion = expansion + self.alias = alias + self.order = order + self.options = options or RuleOptions() + self._hash = hash((self.origin, tuple(self.expansion))) + + def _deserialize(self): + self._hash = hash((self.origin, tuple(self.expansion))) + + def __str__(self): + return '<%s : %s>' % (self.origin.name, ' '.join(x.name for x in self.expansion)) + + def __repr__(self): + return 'Rule(%r, %r, %r, %r)' % (self.origin, self.expansion, self.alias, self.options) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + if not isinstance(other, Rule): + return False + return self.origin == other.origin and self.expansion == other.expansion + + + +###} diff --git a/testbed/lark-parser__lark/lark/grammars/common.lark b/testbed/lark-parser__lark/lark/grammars/common.lark new file mode 100644 index 0000000000000000000000000000000000000000..a675ca410a4489477bf9398e12d0ade3f9a884f1 --- /dev/null +++ b/testbed/lark-parser__lark/lark/grammars/common.lark @@ -0,0 +1,50 @@ +// +// Numbers +// + +DIGIT: "0".."9" +HEXDIGIT: "a".."f"|"A".."F"|DIGIT + +INT: DIGIT+ +SIGNED_INT: ["+"|"-"] INT +DECIMAL: INT "." INT? | "." INT + +// float = /-?\d+(\.\d+)?([eE][+-]?\d+)?/ +_EXP: ("e"|"E") SIGNED_INT +FLOAT: INT _EXP | DECIMAL _EXP? +SIGNED_FLOAT: ["+"|"-"] FLOAT + +NUMBER: FLOAT | INT +SIGNED_NUMBER: ["+"|"-"] NUMBER + +// +// Strings +// +_STRING_INNER: /.*?/ +_STRING_ESC_INNER: _STRING_INNER /(? 0 + + def handle_NL(self, token): + if self.paren_level > 0: + return + + yield token + + indent_str = token.rsplit('\n', 1)[1] # Tabs and spaces + indent = indent_str.count(' ') + indent_str.count('\t') * self.tab_len + + if indent > self.indent_level[-1]: + self.indent_level.append(indent) + yield Token.new_borrow_pos(self.INDENT_type, indent_str, token) + else: + while indent < self.indent_level[-1]: + self.indent_level.pop() + yield Token.new_borrow_pos(self.DEDENT_type, indent_str, token) + + assert indent == self.indent_level[-1], '%s != %s' % (indent, self.indent_level[-1]) + + def _process(self, stream): + for token in stream: + if token.type == self.NL_type: + for t in self.handle_NL(token): + yield t + else: + yield token + + if token.type in self.OPEN_PAREN_types: + self.paren_level += 1 + elif token.type in self.CLOSE_PAREN_types: + self.paren_level -= 1 + assert self.paren_level >= 0 + + while len(self.indent_level) > 1: + self.indent_level.pop() + yield Token(self.DEDENT_type, '') + + assert self.indent_level == [0], self.indent_level + + def process(self, stream): + self.paren_level = 0 + self.indent_level = [0] + return self._process(stream) + + # XXX Hack for ContextualLexer. Maybe there's a more elegant solution? + @property + def always_accept(self): + return (self.NL_type,) + +###} diff --git a/testbed/lark-parser__lark/lark/lark.py b/testbed/lark-parser__lark/lark/lark.py new file mode 100644 index 0000000000000000000000000000000000000000..770b82136b2ba12d1a1aae55d05d95cbcb588221 --- /dev/null +++ b/testbed/lark-parser__lark/lark/lark.py @@ -0,0 +1,471 @@ +from __future__ import absolute_import + +import sys, os, pickle, hashlib +from io import open + + +from .utils import STRING_TYPE, Serialize, SerializeMemoizer, FS, isascii, logger +from .load_grammar import load_grammar +from .tree import Tree +from .common import LexerConf, ParserConf + +from .lexer import Lexer, TraditionalLexer, TerminalDef, UnexpectedToken +from .parse_tree_builder import ParseTreeBuilder +from .parser_frontends import get_frontend, _get_lexer_callbacks +from .grammar import Rule + +import re +try: + import regex +except ImportError: + regex = None + +###{standalone + +class LarkOptions(Serialize): + """Specifies the options for Lark + + """ + OPTIONS_DOC = """ + **=== General Options ===** + + start + The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start") + debug + Display debug information, such as warnings (default: False) + transformer + Applies the transformer to every parse tree (equivlent to applying it after the parse, but faster) + propagate_positions + Propagates (line, column, end_line, end_column) attributes into all tree branches. + maybe_placeholders + When True, the ``[]`` operator returns ``None`` when not matched. + + When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all. + (default= ``False``. Recommended to set to ``True``) + cache + Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now. + + - When ``False``, does nothing (default) + - When ``True``, caches to a temporary file in the local directory + - When given a string, caches to the path pointed by the string + regex + When True, uses the ``regex`` module instead of the stdlib ``re``. + g_regex_flags + Flags that are applied to all terminals (both regex and strings) + keep_all_tokens + Prevent the tree builder from automagically removing "punctuation" tokens (default: False) + tree_class + Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``. + + **=== Algorithm Options ===** + + parser + Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley"). + (there is also a "cyk" option for legacy) + lexer + Decides whether or not to use a lexer stage + + - "auto" (default): Choose for me based on the parser + - "standard": Use a standard lexer + - "contextual": Stronger lexer (only works with parser="lalr") + - "dynamic": Flexible and powerful (only with parser="earley") + - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible. + ambiguity + Decides how to handle ambiguity in the parse. Only relevant if parser="earley" + + - "resolve": The parser will automatically choose the simplest derivation + (it chooses consistently: greedy for tokens, non-greedy for rules) + - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest). + - "forest": The parser will return the root of the shared packed parse forest. + + **=== Misc. / Domain Specific Options ===** + + postlex + Lexer post-processing (Default: None) Only works with the standard and contextual lexers. + priority + How priorities should be evaluated - auto, none, normal, invert (Default: auto) + lexer_callbacks + Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution. + use_bytes + Accept an input of type ``bytes`` instead of ``str`` (Python 3 only). + edit_terminals + A callback for editing the terminals before parse. + + **=== End Options ===** + """ + if __doc__: + __doc__ += OPTIONS_DOC + + _defaults = { + 'debug': False, + 'keep_all_tokens': False, + 'tree_class': None, + 'cache': False, + 'postlex': None, + 'parser': 'earley', + 'lexer': 'auto', + 'transformer': None, + 'start': 'start', + 'priority': 'auto', + 'ambiguity': 'auto', + 'regex': False, + 'propagate_positions': False, + 'lexer_callbacks': {}, + 'maybe_placeholders': False, + 'edit_terminals': None, + 'g_regex_flags': 0, + 'use_bytes': False, + } + + def __init__(self, options_dict): + o = dict(options_dict) + + options = {} + for name, default in self._defaults.items(): + if name in o: + value = o.pop(name) + if isinstance(default, bool) and name not in ('cache', 'use_bytes'): + value = bool(value) + else: + value = default + + options[name] = value + + if isinstance(options['start'], STRING_TYPE): + options['start'] = [options['start']] + + self.__dict__['options'] = options + + assert self.parser in ('earley', 'lalr', 'cyk', None) + + if self.parser == 'earley' and self.transformer: + raise ValueError('Cannot specify an embedded transformer when using the Earley algorithm.' + 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)') + + if o: + raise ValueError("Unknown options: %s" % o.keys()) + + def __getattr__(self, name): + try: + return self.options[name] + except KeyError as e: + raise AttributeError(e) + + def __setattr__(self, name, value): + assert name in self.options + self.options[name] = value + + def serialize(self, memo): + return self.options + + @classmethod + def deserialize(cls, data, memo): + return cls(data) + + +_LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'use_bytes', 'debug', 'g_regex_flags', + 'regex', 'propagate_positions', 'keep_all_tokens', 'tree_class'} + + +class Lark(Serialize): + """Main interface for the library. + + It's mostly a thin wrapper for the many different parsers, and for the tree constructor. + + Parameters: + grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax) + options: a dictionary controlling various aspects of Lark. + + Example: + >>> Lark(r'''start: "foo" ''') + Lark(...) + """ + def __init__(self, grammar, **options): + self.options = LarkOptions(options) + + # Set regex or re module + use_regex = self.options.regex + if use_regex: + if regex: + re_module = regex + else: + raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.') + else: + re_module = re + + # Some, but not all file-like objects have a 'name' attribute + try: + self.source = grammar.name + except AttributeError: + self.source = '' + + # Drain file-like objects to get their contents + try: + read = grammar.read + except AttributeError: + pass + else: + grammar = read() + + assert isinstance(grammar, STRING_TYPE) + self.grammar_source = grammar + if self.options.use_bytes: + if not isascii(grammar): + raise ValueError("Grammar must be ascii only, when use_bytes=True") + if sys.version_info[0] == 2 and self.options.use_bytes != 'force': + raise NotImplementedError("`use_bytes=True` may have issues on python2." + "Use `use_bytes='force'` to use it at your own risk.") + + cache_fn = None + if self.options.cache: + if self.options.parser != 'lalr': + raise NotImplementedError("cache only works with parser='lalr' for now") + if isinstance(self.options.cache, STRING_TYPE): + cache_fn = self.options.cache + else: + if self.options.cache is not True: + raise ValueError("cache argument must be bool or str") + unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals') + from . import __version__ + options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable) + s = grammar + options_str + __version__ + md5 = hashlib.md5(s.encode()).hexdigest() + cache_fn = '.lark_cache_%s.tmp' % md5 + + if FS.exists(cache_fn): + logger.debug('Loading grammar from cache: %s', cache_fn) + # Remove options that aren't relevant for loading from cache + for name in (set(options) - _LOAD_ALLOWED_OPTIONS): + del options[name] + with FS.open(cache_fn, 'rb') as f: + self._load(f, **options) + return + + if self.options.lexer == 'auto': + if self.options.parser == 'lalr': + self.options.lexer = 'contextual' + elif self.options.parser == 'earley': + self.options.lexer = 'dynamic' + elif self.options.parser == 'cyk': + self.options.lexer = 'standard' + else: + assert False, self.options.parser + lexer = self.options.lexer + assert lexer in ('standard', 'contextual', 'dynamic', 'dynamic_complete') or issubclass(lexer, Lexer) + + if self.options.ambiguity == 'auto': + if self.options.parser == 'earley': + self.options.ambiguity = 'resolve' + else: + disambig_parsers = ['earley', 'cyk'] + assert self.options.parser in disambig_parsers, ( + 'Only %s supports disambiguation right now') % ', '.join(disambig_parsers) + + if self.options.priority == 'auto': + if self.options.parser in ('earley', 'cyk', ): + self.options.priority = 'normal' + elif self.options.parser in ('lalr', ): + self.options.priority = None + elif self.options.priority in ('invert', 'normal'): + assert self.options.parser in ('earley', 'cyk'), "priorities are not supported for LALR at this time" + + assert self.options.priority in ('auto', None, 'normal', 'invert'), 'invalid priority option specified: {}. options are auto, none, normal, invert.'.format(self.options.priority) + assert self.options.ambiguity not in ('resolve__antiscore_sum', ), 'resolve__antiscore_sum has been replaced with the option priority="invert"' + assert self.options.ambiguity in ('resolve', 'explicit', 'forest', 'auto', ) + + # Parse the grammar file and compose the grammars (TODO) + self.grammar = load_grammar(grammar, self.source, re_module, self.options.keep_all_tokens) + + if self.options.postlex is not None: + terminals_to_keep = set(self.options.postlex.always_accept) + else: + terminals_to_keep = set() + + # Compile the EBNF grammar into BNF + self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep) + + if self.options.edit_terminals: + for t in self.terminals: + self.options.edit_terminals(t) + + self._terminals_dict = {t.name: t for t in self.terminals} + + # If the user asked to invert the priorities, negate them all here. + # This replaces the old 'resolve__antiscore_sum' option. + if self.options.priority == 'invert': + for rule in self.rules: + if rule.options.priority is not None: + rule.options.priority = -rule.options.priority + # Else, if the user asked to disable priorities, strip them from the + # rules. This allows the Earley parsers to skip an extra forest walk + # for improved performance, if you don't need them (or didn't specify any). + elif self.options.priority == None: + for rule in self.rules: + if rule.options.priority is not None: + rule.options.priority = None + + # TODO Deprecate lexer_callbacks? + lexer_callbacks = (_get_lexer_callbacks(self.options.transformer, self.terminals) + if self.options.transformer + else {}) + lexer_callbacks.update(self.options.lexer_callbacks) + + self.lexer_conf = LexerConf(self.terminals, re_module, self.ignore_tokens, self.options.postlex, lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes) + + if self.options.parser: + self.parser = self._build_parser() + elif lexer: + self.lexer = self._build_lexer() + + if cache_fn: + logger.debug('Saving grammar to cache: %s', cache_fn) + with FS.open(cache_fn, 'wb') as f: + self.save(f) + + if __doc__: + __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC + + __serialize_fields__ = 'parser', 'rules', 'options' + + def _build_lexer(self): + return TraditionalLexer(self.lexer_conf) + + def _prepare_callbacks(self): + self.parser_class = get_frontend(self.options.parser, self.options.lexer) + self._callbacks = None + # we don't need these callbacks if we aren't building a tree + if self.options.ambiguity != 'forest': + self._parse_tree_builder = ParseTreeBuilder( + self.rules, + self.options.tree_class or Tree, + self.options.propagate_positions, + self.options.parser!='lalr' and self.options.ambiguity=='explicit', + self.options.maybe_placeholders + ) + self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer) + + def _build_parser(self): + self._prepare_callbacks() + parser_conf = ParserConf(self.rules, self._callbacks, self.options.start) + return self.parser_class(self.lexer_conf, parser_conf, options=self.options) + + def save(self, f): + """Saves the instance into the given file object + + Useful for caching and multiprocessing. + """ + data, m = self.memo_serialize([TerminalDef, Rule]) + pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL) + + @classmethod + def load(cls, f): + """Loads an instance from the given file object + + Useful for caching and multiprocessing. + """ + inst = cls.__new__(cls) + return inst._load(f) + + def _load(self, f, **kwargs): + if isinstance(f, dict): + d = f + else: + d = pickle.load(f) + memo = d['memo'] + data = d['data'] + + assert memo + memo = SerializeMemoizer.deserialize(memo, {'Rule': Rule, 'TerminalDef': TerminalDef}, {}) + options = dict(data['options']) + if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults): + raise ValueError("Some options are not allowed when loading a Parser: {}" + .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS)) + options.update(kwargs) + self.options = LarkOptions.deserialize(options, memo) + self.rules = [Rule.deserialize(r, memo) for r in data['rules']] + self.source = '' + self._prepare_callbacks() + self.parser = self.parser_class.deserialize( + data['parser'], + memo, + self._callbacks, + self.options, # Not all, but multiple attributes are used + ) + self.terminals = self.parser.lexer_conf.tokens + self._terminals_dict = {t.name: t for t in self.terminals} + return self + + @classmethod + def _load_from_dict(cls, data, memo, **kwargs): + inst = cls.__new__(cls) + return inst._load({'data': data, 'memo': memo}, **kwargs) + + @classmethod + def open(cls, grammar_filename, rel_to=None, **options): + """Create an instance of Lark with the grammar given by its filename + + If ``rel_to`` is provided, the function will find the grammar filename in relation to it. + + Example: + + >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr") + Lark(...) + + """ + if rel_to: + basepath = os.path.dirname(rel_to) + grammar_filename = os.path.join(basepath, grammar_filename) + with open(grammar_filename, encoding='utf8') as f: + return cls(f, **options) + + def __repr__(self): + return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source, self.options.parser, self.options.lexer) + + + def lex(self, text): + "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'" + if not hasattr(self, 'lexer'): + self.lexer = self._build_lexer() + stream = self.lexer.lex(text) + if self.options.postlex: + return self.options.postlex.process(stream) + return stream + + def get_terminal(self, name): + "Get information about a terminal" + return self._terminals_dict[name] + + def parse(self, text, start=None, on_error=None): + """Parse the given text, according to the options provided. + + Parameters: + text (str): Text to be parsed. + start (str, optional): Required if Lark was given multiple possible start symbols (using the start option). + on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing. + LALR only. See examples/error_puppet.py for an example of how to use on_error. + + Returns: + If a transformer is supplied to ``__init__``, returns whatever is the + result of the transformation. Otherwise, returns a Tree instance. + + """ + + try: + return self.parser.parse(text, start=start) + except UnexpectedToken as e: + if on_error is None: + raise + + while True: + if not on_error(e): + raise e + try: + return e.puppet.resume_parse() + except UnexpectedToken as e2: + if e.token.type == e2.token.type == '$END' and e.puppet == e2.puppet: + # Prevent infinite loop + raise e2 + e = e2 + + +###} diff --git a/testbed/lark-parser__lark/lark/lexer.py b/testbed/lark-parser__lark/lark/lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc9e4b1158bb5a64f15f60b7914b06b55a40d0e --- /dev/null +++ b/testbed/lark-parser__lark/lark/lexer.py @@ -0,0 +1,433 @@ +## Lexer Implementation + +import re + +from .utils import Str, classify, get_regexp_width, Py36, Serialize +from .exceptions import UnexpectedCharacters, LexError, UnexpectedToken + +###{standalone +from copy import copy + +class Pattern(Serialize): + + def __init__(self, value, flags=()): + self.value = value + self.flags = frozenset(flags) + + def __repr__(self): + return repr(self.to_regexp()) + + # Pattern Hashing assumes all subclasses have a different priority! + def __hash__(self): + return hash((type(self), self.value, self.flags)) + def __eq__(self, other): + return type(self) == type(other) and self.value == other.value and self.flags == other.flags + + def to_regexp(self): + raise NotImplementedError() + + if Py36: + # Python 3.6 changed syntax for flags in regular expression + def _get_flags(self, value): + for f in self.flags: + value = ('(?%s:%s)' % (f, value)) + return value + + else: + def _get_flags(self, value): + for f in self.flags: + value = ('(?%s)' % f) + value + return value + + +class PatternStr(Pattern): + __serialize_fields__ = 'value', 'flags' + + type = "str" + + def to_regexp(self): + return self._get_flags(re.escape(self.value)) + + @property + def min_width(self): + return len(self.value) + max_width = min_width + +class PatternRE(Pattern): + __serialize_fields__ = 'value', 'flags', '_width' + + type = "re" + + def to_regexp(self): + return self._get_flags(self.value) + + _width = None + def _get_width(self): + if self._width is None: + self._width = get_regexp_width(self.to_regexp()) + return self._width + + @property + def min_width(self): + return self._get_width()[0] + @property + def max_width(self): + return self._get_width()[1] + + +class TerminalDef(Serialize): + __serialize_fields__ = 'name', 'pattern', 'priority' + __serialize_namespace__ = PatternStr, PatternRE + + def __init__(self, name, pattern, priority=1): + assert isinstance(pattern, Pattern), pattern + self.name = name + self.pattern = pattern + self.priority = priority + + def __repr__(self): + return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern) + + +class Token(Str): + """A string with meta-information, that is produced by the lexer. + + When parsing text, the resulting chunks of the input that haven't been discarded, + will end up in the tree as Token instances. The Token class inherits from Python's ``str``, + so normal string comparisons and operations will work as expected. + + Attributes: + type: Name of the token (as specified in grammar) + value: Value of the token (redundant, as ``token.value == token`` will always be true) + pos_in_stream: The index of the token in the text + line: The line of the token in the text (starting with 1) + column: The column of the token in the text (starting with 1) + end_line: The line where the token ends + end_column: The next column after the end of the token. For example, + if the token is a single character with a column value of 4, + end_column will be 5. + end_pos: the index where the token ends (basically ``pos_in_stream + len(token)``) + """ + __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column', 'end_pos') + + def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None, end_line=None, end_column=None, end_pos=None): + try: + self = super(Token, cls).__new__(cls, value) + except UnicodeDecodeError: + value = value.decode('latin1') + self = super(Token, cls).__new__(cls, value) + + self.type = type_ + self.pos_in_stream = pos_in_stream + self.value = value + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.end_pos = end_pos + return self + + def update(self, type_=None, value=None): + return Token.new_borrow_pos( + type_ if type_ is not None else self.type, + value if value is not None else self.value, + self + ) + + @classmethod + def new_borrow_pos(cls, type_, value, borrow_t): + return cls(type_, value, borrow_t.pos_in_stream, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column, borrow_t.end_pos) + + def __reduce__(self): + return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, )) + + def __repr__(self): + return 'Token(%r, %r)' % (self.type, self.value) + + def __deepcopy__(self, memo): + return Token(self.type, self.value, self.pos_in_stream, self.line, self.column) + + def __eq__(self, other): + if isinstance(other, Token) and self.type != other.type: + return False + + return Str.__eq__(self, other) + + __hash__ = Str.__hash__ + + +class LineCounter: + def __init__(self, newline_char): + self.newline_char = newline_char + self.char_pos = 0 + self.line = 1 + self.column = 1 + self.line_start_pos = 0 + + def feed(self, token, test_newline=True): + """Consume a token and calculate the new line & column. + + As an optional optimization, set test_newline=False is token doesn't contain a newline. + """ + if test_newline: + newlines = token.count(self.newline_char) + if newlines: + self.line += newlines + self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1 + + self.char_pos += len(token) + self.column = self.char_pos - self.line_start_pos + 1 + +class _Lex: + "Built to serve both Lexer and ContextualLexer" + def __init__(self, lexer, state=None): + self.lexer = lexer + self.state = state + + def lex(self, stream, newline_types, ignore_types): + newline_types = frozenset(newline_types) + ignore_types = frozenset(ignore_types) + line_ctr = LineCounter('\n' if not self.lexer.use_bytes else b'\n') + last_token = None + + while line_ctr.char_pos < len(stream): + lexer = self.lexer + res = lexer.match(stream, line_ctr.char_pos) + if not res: + allowed = {v for m, tfi in lexer.mres for v in tfi.values()} - ignore_types + if not allowed: + allowed = {""} + raise UnexpectedCharacters(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column, allowed=allowed, state=self.state, token_history=last_token and [last_token]) + + value, type_ = res + + if type_ not in ignore_types: + t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column) + line_ctr.feed(value, type_ in newline_types) + t.end_line = line_ctr.line + t.end_column = line_ctr.column + t.end_pos = line_ctr.char_pos + if t.type in lexer.callback: + t = lexer.callback[t.type](t) + if not isinstance(t, Token): + raise ValueError("Callbacks must return a token (returned %r)" % t) + yield t + last_token = t + else: + if type_ in lexer.callback: + t2 = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column) + lexer.callback[type_](t2) + line_ctr.feed(value, type_ in newline_types) + + + + +class UnlessCallback: + def __init__(self, mres): + self.mres = mres + + def __call__(self, t): + for mre, type_from_index in self.mres: + m = mre.match(t.value) + if m: + t.type = type_from_index[m.lastindex] + break + return t + +class CallChain: + def __init__(self, callback1, callback2, cond): + self.callback1 = callback1 + self.callback2 = callback2 + self.cond = cond + + def __call__(self, t): + t2 = self.callback1(t) + return self.callback2(t) if self.cond(t2) else t2 + + + + + +def _create_unless(terminals, g_regex_flags, re_, use_bytes): + tokens_by_type = classify(terminals, lambda t: type(t.pattern)) + assert len(tokens_by_type) <= 2, tokens_by_type.keys() + embedded_strs = set() + callback = {} + for retok in tokens_by_type.get(PatternRE, []): + unless = [] # {} + for strtok in tokens_by_type.get(PatternStr, []): + if strtok.priority > retok.priority: + continue + s = strtok.pattern.value + m = re_.match(retok.pattern.to_regexp(), s, g_regex_flags) + if m and m.group(0) == s: + unless.append(strtok) + if strtok.pattern.flags <= retok.pattern.flags: + embedded_strs.add(strtok) + if unless: + callback[retok.name] = UnlessCallback(build_mres(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes)) + + terminals = [t for t in terminals if t not in embedded_strs] + return terminals, callback + + +def _build_mres(terminals, max_size, g_regex_flags, match_whole, re_, use_bytes): + # Python sets an unreasonable group limit (currently 100) in its re module + # Worse, the only way to know we reached it is by catching an AssertionError! + # This function recursively tries less and less groups until it's successful. + postfix = '$' if match_whole else '' + mres = [] + while terminals: + pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size]) + if use_bytes: + pattern = pattern.encode('latin-1') + try: + mre = re_.compile(pattern, g_regex_flags) + except AssertionError: # Yes, this is what Python provides us.. :/ + return _build_mres(terminals, max_size//2, g_regex_flags, match_whole, re_, use_bytes) + + # terms_from_name = {t.name: t for t in terminals[:max_size]} + mres.append((mre, {i:n for n,i in mre.groupindex.items()} )) + terminals = terminals[max_size:] + return mres + +def build_mres(terminals, g_regex_flags, re_, use_bytes, match_whole=False): + return _build_mres(terminals, len(terminals), g_regex_flags, match_whole, re_, use_bytes) + +def _regexp_has_newline(r): + r"""Expressions that may indicate newlines in a regexp: + - newlines (\n) + - escaped newline (\\n) + - anything but ([^...]) + - any-char (.) when the flag (?s) exists + - spaces (\s) + """ + return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r) + +class Lexer(object): + """Lexer interface + + Method Signatures: + lex(self, stream) -> Iterator[Token] + """ + lex = NotImplemented + + +class TraditionalLexer(Lexer): + + def __init__(self, conf): + terminals = list(conf.tokens) + assert all(isinstance(t, TerminalDef) for t in terminals), terminals + + self.re = conf.re_module + + if not conf.skip_validation: + # Sanitization + for t in terminals: + try: + self.re.compile(t.pattern.to_regexp(), conf.g_regex_flags) + except self.re.error: + raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern)) + + if t.pattern.min_width == 0: + raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern)) + + assert set(conf.ignore) <= {t.name for t in terminals} + + # Init + self.newline_types = [t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp())] + self.ignore_types = list(conf.ignore) + + terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name)) + self.terminals = terminals + self.user_callbacks = conf.callbacks + self.g_regex_flags = conf.g_regex_flags + self.use_bytes = conf.use_bytes + + self._mres = None + # self.build(g_regex_flags) + + def _build(self): + terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, re_=self.re, use_bytes=self.use_bytes) + assert all(self.callback.values()) + + for type_, f in self.user_callbacks.items(): + if type_ in self.callback: + # Already a callback there, probably UnlessCallback + self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_) + else: + self.callback[type_] = f + + self._mres = build_mres(terminals, self.g_regex_flags, self.re, self.use_bytes) + + @property + def mres(self): + if self._mres is None: + self._build() + return self._mres + + def match(self, stream, pos): + for mre, type_from_index in self.mres: + m = mre.match(stream, pos) + if m: + return m.group(0), type_from_index[m.lastindex] + + def lex(self, stream): + return _Lex(self).lex(stream, self.newline_types, self.ignore_types) + + + + +class ContextualLexer(Lexer): + + def __init__(self, conf, states, always_accept=()): + terminals = list(conf.tokens) + tokens_by_name = {} + for t in terminals: + assert t.name not in tokens_by_name, t + tokens_by_name[t.name] = t + + trad_conf = copy(conf) + trad_conf.tokens = terminals + + lexer_by_tokens = {} + self.lexers = {} + for state, accepts in states.items(): + key = frozenset(accepts) + try: + lexer = lexer_by_tokens[key] + except KeyError: + accepts = set(accepts) | set(conf.ignore) | set(always_accept) + state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name] + lexer_conf = copy(trad_conf) + lexer_conf.tokens = state_tokens + lexer = TraditionalLexer(lexer_conf) + lexer_by_tokens[key] = lexer + + self.lexers[state] = lexer + + assert trad_conf.tokens is terminals + self.root_lexer = TraditionalLexer(trad_conf) + + def lex(self, stream, get_parser_state): + parser_state = get_parser_state() + l = _Lex(self.lexers[parser_state], parser_state) + try: + for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types): + yield x + parser_state = get_parser_state() + l.lexer = self.lexers[parser_state] + l.state = parser_state # For debug only, no need to worry about multithreading + except UnexpectedCharacters as e: + # In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined, + # but not in the current context. + # This tests the input against the global context, to provide a nicer error. + root_match = self.root_lexer.match(stream, e.pos_in_stream) + if not root_match: + raise + + value, type_ = root_match + t = Token(type_, value, e.pos_in_stream, e.line, e.column) + raise UnexpectedToken(t, e.allowed, state=e.state) + +###} diff --git a/testbed/lark-parser__lark/lark/load_grammar.py b/testbed/lark-parser__lark/lark/load_grammar.py new file mode 100644 index 0000000000000000000000000000000000000000..d03963886e0ffd0b5703548c2fc2ae64814dfe19 --- /dev/null +++ b/testbed/lark-parser__lark/lark/load_grammar.py @@ -0,0 +1,991 @@ +"Parses and creates Grammar objects" + +import os.path +import sys +from copy import copy, deepcopy +from io import open + +from .utils import bfs, eval_escaping, Py36, logger, classify_bool +from .lexer import Token, TerminalDef, PatternStr, PatternRE + +from .parse_tree_builder import ParseTreeBuilder +from .parser_frontends import LALR_TraditionalLexer +from .common import LexerConf, ParserConf +from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol +from .utils import classify, suppress, dedup_list, Str +from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken + +from .tree import Tree, SlottedTree as ST +from .visitors import Transformer, Visitor, v_args, Transformer_InPlace, Transformer_NonRecursive +inline_args = v_args(inline=True) + +__path__ = os.path.dirname(__file__) +IMPORT_PATHS = [os.path.join(__path__, 'grammars')] + +EXT = '.lark' + +_RE_FLAGS = 'imslux' + +_EMPTY = Symbol('__empty__') + +_TERMINAL_NAMES = { + '.' : 'DOT', + ',' : 'COMMA', + ':' : 'COLON', + ';' : 'SEMICOLON', + '+' : 'PLUS', + '-' : 'MINUS', + '*' : 'STAR', + '/' : 'SLASH', + '\\' : 'BACKSLASH', + '|' : 'VBAR', + '?' : 'QMARK', + '!' : 'BANG', + '@' : 'AT', + '#' : 'HASH', + '$' : 'DOLLAR', + '%' : 'PERCENT', + '^' : 'CIRCUMFLEX', + '&' : 'AMPERSAND', + '_' : 'UNDERSCORE', + '<' : 'LESSTHAN', + '>' : 'MORETHAN', + '=' : 'EQUAL', + '"' : 'DBLQUOTE', + '\'' : 'QUOTE', + '`' : 'BACKQUOTE', + '~' : 'TILDE', + '(' : 'LPAR', + ')' : 'RPAR', + '{' : 'LBRACE', + '}' : 'RBRACE', + '[' : 'LSQB', + ']' : 'RSQB', + '\n' : 'NEWLINE', + '\r\n' : 'CRLF', + '\t' : 'TAB', + ' ' : 'SPACE', +} + +# Grammar Parser +TERMINALS = { + '_LPAR': r'\(', + '_RPAR': r'\)', + '_LBRA': r'\[', + '_RBRA': r'\]', + '_LBRACE': r'\{', + '_RBRACE': r'\}', + 'OP': '[+*]|[?](?![a-z])', + '_COLON': ':', + '_COMMA': ',', + '_OR': r'\|', + '_DOT': r'\.(?!\.)', + '_DOTDOT': r'\.\.', + 'TILDE': '~', + 'RULE': '!?[_?]?[a-z][_a-z0-9]*', + 'TERMINAL': '_?[A-Z][_A-Z0-9]*', + 'STRING': r'"(\\"|\\\\|[^"\n])*?"i?', + 'REGEXP': r'/(?!/)(\\/|\\\\|[^/])*?/[%s]*' % _RE_FLAGS, + '_NL': r'(\r?\n)+\s*', + 'WS': r'[ \t]+', + 'COMMENT': r'\s*//[^\n]*', + '_TO': '->', + '_IGNORE': r'%ignore', + '_DECLARE': r'%declare', + '_IMPORT': r'%import', + 'NUMBER': r'[+-]?\d+', +} + +RULES = { + 'start': ['_list'], + '_list': ['_item', '_list _item'], + '_item': ['rule', 'term', 'statement', '_NL'], + + 'rule': ['RULE template_params _COLON expansions _NL', + 'RULE template_params _DOT NUMBER _COLON expansions _NL'], + 'template_params': ['_LBRACE _template_params _RBRACE', + ''], + '_template_params': ['RULE', + '_template_params _COMMA RULE'], + 'expansions': ['alias', + 'expansions _OR alias', + 'expansions _NL _OR alias'], + + '?alias': ['expansion _TO RULE', 'expansion'], + 'expansion': ['_expansion'], + + '_expansion': ['', '_expansion expr'], + + '?expr': ['atom', + 'atom OP', + 'atom TILDE NUMBER', + 'atom TILDE NUMBER _DOTDOT NUMBER', + ], + + '?atom': ['_LPAR expansions _RPAR', + 'maybe', + 'value'], + + 'value': ['terminal', + 'nonterminal', + 'literal', + 'range', + 'template_usage'], + + 'terminal': ['TERMINAL'], + 'nonterminal': ['RULE'], + + '?name': ['RULE', 'TERMINAL'], + + 'maybe': ['_LBRA expansions _RBRA'], + 'range': ['STRING _DOTDOT STRING'], + + 'template_usage': ['RULE _LBRACE _template_args _RBRACE'], + '_template_args': ['value', + '_template_args _COMMA value'], + + 'term': ['TERMINAL _COLON expansions _NL', + 'TERMINAL _DOT NUMBER _COLON expansions _NL'], + 'statement': ['ignore', 'import', 'declare'], + 'ignore': ['_IGNORE expansions _NL'], + 'declare': ['_DECLARE _declare_args _NL'], + 'import': ['_IMPORT _import_path _NL', + '_IMPORT _import_path _LPAR name_list _RPAR _NL', + '_IMPORT _import_path _TO name _NL'], + + '_import_path': ['import_lib', 'import_rel'], + 'import_lib': ['_import_args'], + 'import_rel': ['_DOT _import_args'], + '_import_args': ['name', '_import_args _DOT name'], + + 'name_list': ['_name_list'], + '_name_list': ['name', '_name_list _COMMA name'], + + '_declare_args': ['name', '_declare_args name'], + 'literal': ['REGEXP', 'STRING'], +} + +@inline_args +class EBNF_to_BNF(Transformer_InPlace): + def __init__(self): + self.new_rules = [] + self.rules_by_expr = {} + self.prefix = 'anon' + self.i = 0 + self.rule_options = None + + def _add_recurse_rule(self, type_, expr): + if expr in self.rules_by_expr: + return self.rules_by_expr[expr] + + new_name = '__%s_%s_%d' % (self.prefix, type_, self.i) + self.i += 1 + t = NonTerminal(new_name) + tree = ST('expansions', [ST('expansion', [expr]), ST('expansion', [t, expr])]) + self.new_rules.append((new_name, tree, self.rule_options)) + self.rules_by_expr[expr] = t + return t + + def expr(self, rule, op, *args): + if op.value == '?': + empty = ST('expansion', []) + return ST('expansions', [rule, empty]) + elif op.value == '+': + # a : b c+ d + # --> + # a : b _c d + # _c : _c c | c; + return self._add_recurse_rule('plus', rule) + elif op.value == '*': + # a : b c* d + # --> + # a : b _c? d + # _c : _c c | c; + new_name = self._add_recurse_rule('star', rule) + return ST('expansions', [new_name, ST('expansion', [])]) + elif op.value == '~': + if len(args) == 1: + mn = mx = int(args[0]) + else: + mn, mx = map(int, args) + if mx < mn or mn < 0: + raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx)) + return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx+1)]) + assert False, op + + def maybe(self, rule): + keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens + + def will_not_get_removed(sym): + if isinstance(sym, NonTerminal): + return not sym.name.startswith('_') + if isinstance(sym, Terminal): + return keep_all_tokens or not sym.filter_out + assert False + + if any(rule.scan_values(will_not_get_removed)): + empty = _EMPTY + else: + empty = ST('expansion', []) + + return ST('expansions', [rule, empty]) + + +class SimplifyRule_Visitor(Visitor): + + @staticmethod + def _flatten(tree): + while True: + to_expand = [i for i, child in enumerate(tree.children) + if isinstance(child, Tree) and child.data == tree.data] + if not to_expand: + break + tree.expand_kids_by_index(*to_expand) + + def expansion(self, tree): + # rules_list unpacking + # a : b (c|d) e + # --> + # a : b c e | b d e + # + # In AST terms: + # expansion(b, expansions(c, d), e) + # --> + # expansions( expansion(b, c, e), expansion(b, d, e) ) + + self._flatten(tree) + + for i, child in enumerate(tree.children): + if isinstance(child, Tree) and child.data == 'expansions': + tree.data = 'expansions' + tree.children = [self.visit(ST('expansion', [option if i==j else other + for j, other in enumerate(tree.children)])) + for option in dedup_list(child.children)] + self._flatten(tree) + break + + def alias(self, tree): + rule, alias_name = tree.children + if rule.data == 'expansions': + aliases = [] + for child in tree.children[0].children: + aliases.append(ST('alias', [child, alias_name])) + tree.data = 'expansions' + tree.children = aliases + + def expansions(self, tree): + self._flatten(tree) + # Ensure all children are unique + if len(set(tree.children)) != len(tree.children): + tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use + + +class RuleTreeToText(Transformer): + def expansions(self, x): + return x + def expansion(self, symbols): + return symbols, None + def alias(self, x): + (expansion, _alias), alias = x + assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed + return expansion, alias.value + + +@inline_args +class CanonizeTree(Transformer_InPlace): + def tokenmods(self, *args): + if len(args) == 1: + return list(args) + tokenmods, value = args + return tokenmods + [value] + +class PrepareAnonTerminals(Transformer_InPlace): + "Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them" + + def __init__(self, terminals): + self.terminals = terminals + self.term_set = {td.name for td in self.terminals} + self.term_reverse = {td.pattern: td for td in terminals} + self.i = 0 + self.rule_options = None + + + @inline_args + def pattern(self, p): + value = p.value + if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags: + raise GrammarError(u'Conflicting flags for the same terminal: %s' % p) + + term_name = None + + if isinstance(p, PatternStr): + try: + # If already defined, use the user-defined terminal name + term_name = self.term_reverse[p].name + except KeyError: + # Try to assign an indicative anon-terminal name + try: + term_name = _TERMINAL_NAMES[value] + except KeyError: + if value.isalnum() and value[0].isalpha() and value.upper() not in self.term_set: + with suppress(UnicodeEncodeError): + value.upper().encode('ascii') # Make sure we don't have unicode in our terminal names + term_name = value.upper() + + if term_name in self.term_set: + term_name = None + + elif isinstance(p, PatternRE): + if p in self.term_reverse: # Kind of a weird placement.name + term_name = self.term_reverse[p].name + else: + assert False, p + + if term_name is None: + term_name = '__ANON_%d' % self.i + self.i += 1 + + if term_name not in self.term_set: + assert p not in self.term_reverse + self.term_set.add(term_name) + termdef = TerminalDef(term_name, p) + self.term_reverse[p] = termdef + self.terminals.append(termdef) + + filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr) + + return Terminal(term_name, filter_out=filter_out) + + +class _ReplaceSymbols(Transformer_InPlace): + " Helper for ApplyTemplates " + + def __init__(self): + self.names = {} + + def value(self, c): + if len(c) == 1 and isinstance(c[0], Token) and c[0].value in self.names: + return self.names[c[0].value] + return self.__default__('value', c, None) + + def template_usage(self, c): + if c[0] in self.names: + return self.__default__('template_usage', [self.names[c[0]].name] + c[1:], None) + return self.__default__('template_usage', c, None) + +class ApplyTemplates(Transformer_InPlace): + " Apply the templates, creating new rules that represent the used templates " + + def __init__(self, rule_defs): + self.rule_defs = rule_defs + self.replacer = _ReplaceSymbols() + self.created_templates = set() + + def template_usage(self, c): + name = c[0] + args = c[1:] + result_name = "%s{%s}" % (name, ",".join(a.name for a in args)) + if result_name not in self.created_templates: + self.created_templates.add(result_name) + (_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name) + assert len(params) == len(args), args + result_tree = deepcopy(tree) + self.replacer.names = dict(zip(params, args)) + self.replacer.transform(result_tree) + self.rule_defs.append((result_name, [], result_tree, deepcopy(options))) + return NonTerminal(result_name) + + +def _rfind(s, choices): + return max(s.rfind(c) for c in choices) + + + + +def _literal_to_pattern(literal): + v = literal.value + flag_start = _rfind(v, '/"')+1 + assert flag_start > 0 + flags = v[flag_start:] + assert all(f in _RE_FLAGS for f in flags), flags + + if literal.type == 'STRING' and '\n' in v: + raise GrammarError('You cannot put newlines in string literals') + + if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags: + raise GrammarError('You can only use newlines in regular expressions ' + 'with the `x` (verbose) flag') + + v = v[:flag_start] + assert v[0] == v[-1] and v[0] in '"/' + x = v[1:-1] + + s = eval_escaping(x) + + if literal.type == 'STRING': + s = s.replace('\\\\', '\\') + return PatternStr(s, flags) + elif literal.type == 'REGEXP': + return PatternRE(s, flags) + else: + assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]' + + +@inline_args +class PrepareLiterals(Transformer_InPlace): + def literal(self, literal): + return ST('pattern', [_literal_to_pattern(literal)]) + + def range(self, start, end): + assert start.type == end.type == 'STRING' + start = start.value[1:-1] + end = end.value[1:-1] + assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1, (start, end, len(eval_escaping(start)), len(eval_escaping(end))) + regexp = '[%s-%s]' % (start, end) + return ST('pattern', [PatternRE(regexp)]) + + +def _make_joined_pattern(regexp, flags_set): + # In Python 3.6, a new syntax for flags was introduced, that allows us to restrict the scope + # of flags to a specific regexp group. We are already using it in `lexer.Pattern._get_flags` + # However, for prior Python versions, we still need to use global flags, so we have to make sure + # that there are no flag collisions when we merge several terminals. + flags = () + if not Py36: + if len(flags_set) > 1: + raise GrammarError("Lark doesn't support joining terminals with conflicting flags in python <3.6!") + elif len(flags_set) == 1: + flags ,= flags_set + + return PatternRE(regexp, flags) + +class TerminalTreeToPattern(Transformer): + def pattern(self, ps): + p ,= ps + return p + + def expansion(self, items): + assert items + if len(items) == 1: + return items[0] + + pattern = ''.join(i.to_regexp() for i in items) + return _make_joined_pattern(pattern, {i.flags for i in items}) + + def expansions(self, exps): + if len(exps) == 1: + return exps[0] + + pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps)) + return _make_joined_pattern(pattern, {i.flags for i in exps}) + + def expr(self, args): + inner, op = args[:2] + if op == '~': + if len(args) == 3: + op = "{%d}" % int(args[2]) + else: + mn, mx = map(int, args[2:]) + if mx < mn: + raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx)) + op = "{%d,%d}" % (mn, mx) + else: + assert len(args) == 2 + return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags) + + def maybe(self, expr): + return self.expr(expr + ['?']) + + def alias(self, t): + raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)") + + def value(self, v): + return v[0] + +class PrepareSymbols(Transformer_InPlace): + def value(self, v): + v ,= v + if isinstance(v, Tree): + return v + elif v.type == 'RULE': + return NonTerminal(Str(v.value)) + elif v.type == 'TERMINAL': + return Terminal(Str(v.value), filter_out=v.startswith('_')) + assert False + +def _choice_of_rules(rules): + return ST('expansions', [ST('expansion', [Token('RULE', name)]) for name in rules]) + +def nr_deepcopy_tree(t): + "Deepcopy tree `t` without recursion" + return Transformer_NonRecursive(False).transform(t) + +class Grammar: + def __init__(self, rule_defs, term_defs, ignore): + self.term_defs = term_defs + self.rule_defs = rule_defs + self.ignore = ignore + + def compile(self, start, terminals_to_keep): + # We change the trees in-place (to support huge grammars) + # So deepcopy allows calling compile more than once. + term_defs = deepcopy(list(self.term_defs)) + rule_defs = [(n,p,nr_deepcopy_tree(t),o) for n,p,t,o in self.rule_defs] + + # =================== + # Compile Terminals + # =================== + + # Convert terminal-trees to strings/regexps + + for name, (term_tree, priority) in term_defs: + if term_tree is None: # Terminal added through %declare + continue + expansions = list(term_tree.find_data('expansion')) + if len(expansions) == 1 and not expansions[0].children: + raise GrammarError("Terminals cannot be empty (%s)" % name) + + transformer = PrepareLiterals() * TerminalTreeToPattern() + terminals = [TerminalDef(name, transformer.transform( term_tree ), priority) + for name, (term_tree, priority) in term_defs if term_tree] + + # ================= + # Compile Rules + # ================= + + # 1. Pre-process terminals + anon_tokens_transf = PrepareAnonTerminals(terminals) + transformer = PrepareLiterals() * PrepareSymbols() * anon_tokens_transf # Adds to terminals + + # 2. Inline Templates + + transformer *= ApplyTemplates(rule_defs) + + # 3. Convert EBNF to BNF (and apply step 1 & 2) + ebnf_to_bnf = EBNF_to_BNF() + rules = [] + i = 0 + while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates + name, params, rule_tree, options = rule_defs[i] + i += 1 + if len(params) != 0: # Dont transform templates + continue + rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None + ebnf_to_bnf.rule_options = rule_options + ebnf_to_bnf.prefix = name + anon_tokens_transf.rule_options = rule_options + tree = transformer.transform(rule_tree) + res = ebnf_to_bnf.transform(tree) + rules.append((name, res, options)) + rules += ebnf_to_bnf.new_rules + + assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision" + + # 4. Compile tree to Rule objects + rule_tree_to_text = RuleTreeToText() + + simplify_rule = SimplifyRule_Visitor() + compiled_rules = [] + for rule_content in rules: + name, tree, options = rule_content + simplify_rule.visit(tree) + expansions = rule_tree_to_text.transform(tree) + + for i, (expansion, alias) in enumerate(expansions): + if alias and name.startswith('_'): + raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)" % (name, alias)) + + empty_indices = [x==_EMPTY for x in expansion] + if any(empty_indices): + exp_options = copy(options) or RuleOptions() + exp_options.empty_indices = empty_indices + expansion = [x for x in expansion if x!=_EMPTY] + else: + exp_options = options + + assert all(isinstance(x, Symbol) for x in expansion), expansion + rule = Rule(NonTerminal(name), expansion, i, alias, exp_options) + compiled_rules.append(rule) + + # Remove duplicates of empty rules, throw error for non-empty duplicates + if len(set(compiled_rules)) != len(compiled_rules): + duplicates = classify(compiled_rules, lambda x: x) + for dups in duplicates.values(): + if len(dups) > 1: + if dups[0].expansion: + raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)" + % ''.join('\n * %s' % i for i in dups)) + + # Empty rule; assert all other attributes are equal + assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups) + + # Remove duplicates + compiled_rules = list(set(compiled_rules)) + + + # Filter out unused rules + while True: + c = len(compiled_rules) + used_rules = {s for r in compiled_rules + for s in r.expansion + if isinstance(s, NonTerminal) + and s != r.origin} + used_rules |= {NonTerminal(s) for s in start} + compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules) + for r in unused: + logger.debug("Unused rule: %s", r) + if len(compiled_rules) == c: + break + + # Filter out unused terminals + used_terms = {t.name for r in compiled_rules + for t in r.expansion + if isinstance(t, Terminal)} + terminals, unused = classify_bool(terminals, lambda t: t.name in used_terms or t.name in self.ignore or t.name in terminals_to_keep) + if unused: + logger.debug("Unused terminals: %s", [t.name for t in unused]) + + return terminals, compiled_rules, self.ignore + + + +_imported_grammars = {} + +def import_from_grammar_into_namespace(grammar, namespace, aliases): + """Returns all rules and terminals of grammar, prepended + with a 'namespace' prefix, except for those which are aliased. + """ + + imported_terms = dict(grammar.term_defs) + imported_rules = {n:(n,p,deepcopy(t),o) for n,p,t,o in grammar.rule_defs} + + term_defs = [] + rule_defs = [] + + def rule_dependencies(symbol): + if symbol.type != 'RULE': + return [] + try: + _, params, tree,_ = imported_rules[symbol] + except KeyError: + raise GrammarError("Missing symbol '%s' in grammar %s" % (symbol, namespace)) + return _find_used_symbols(tree) - set(params) + + + + def get_namespace_name(name, params): + if params is not None: + try: + return params[name] + except KeyError: + pass + try: + return aliases[name].value + except KeyError: + if name[0] == '_': + return '_%s__%s' % (namespace, name[1:]) + return '%s__%s' % (namespace, name) + + to_import = list(bfs(aliases, rule_dependencies)) + for symbol in to_import: + if symbol.type == 'TERMINAL': + term_defs.append([get_namespace_name(symbol, None), imported_terms[symbol]]) + else: + assert symbol.type == 'RULE' + _, params, tree, options = imported_rules[symbol] + params_map = {p: ('%s__%s' if p[0]!='_' else '_%s__%s' ) % (namespace, p) for p in params} + for t in tree.iter_subtrees(): + for i, c in enumerate(t.children): + if isinstance(c, Token) and c.type in ('RULE', 'TERMINAL'): + t.children[i] = Token(c.type, get_namespace_name(c, params_map)) + params = [params_map[p] for p in params] # We can not rely on ordered dictionaries + rule_defs.append((get_namespace_name(symbol, params_map), params, tree, options)) + + + return term_defs, rule_defs + + + +def resolve_term_references(term_defs): + # TODO Solve with transitive closure (maybe) + + term_dict = {k:t for k, (t,_p) in term_defs} + assert len(term_dict) == len(term_defs), "Same name defined twice?" + + while True: + changed = False + for name, (token_tree, _p) in term_defs: + if token_tree is None: # Terminal added through %declare + continue + for exp in token_tree.find_data('value'): + item ,= exp.children + if isinstance(item, Token): + if item.type == 'RULE': + raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name)) + if item.type == 'TERMINAL': + term_value = term_dict[item] + assert term_value is not None + exp.children[0] = term_value + changed = True + if not changed: + break + + for name, term in term_dict.items(): + if term: # Not just declared + for child in term.children: + ids = [id(x) for x in child.iter_subtrees()] + if id(term) in ids: + raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name) + + +def options_from_rule(name, params, *x): + if len(x) > 1: + priority, expansions = x + priority = int(priority) + else: + expansions ,= x + priority = None + params = [t.value for t in params.children] if params is not None else [] # For the grammar parser + + keep_all_tokens = name.startswith('!') + name = name.lstrip('!') + expand1 = name.startswith('?') + name = name.lstrip('?') + + return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority, + template_source=(name if params else None)) + + +def symbols_from_strcase(expansion): + return [Terminal(x, filter_out=x.startswith('_')) if x.isupper() else NonTerminal(x) for x in expansion] + +@inline_args +class PrepareGrammar(Transformer_InPlace): + def terminal(self, name): + return name + def nonterminal(self, name): + return name + + +def _find_used_symbols(tree): + assert tree.data == 'expansions' + return {t for x in tree.find_data('expansion') + for t in x.scan_values(lambda t: t.type in ('RULE', 'TERMINAL'))} + +class GrammarLoader: + ERRORS = [ + ('Unclosed parenthesis', ['a: (\n']), + ('Umatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']), + ('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']), + ('Illegal name for rules or terminals', ['Aa:\n']), + ('Alias expects lowercase name', ['a: -> "a"\n']), + ('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']), + ('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']), + ('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']), + ('Terminal names cannot contain dots', ['A.B\n']), + ('%import expects a name', ['%import "a"\n']), + ('%ignore expects a value', ['%ignore %import\n']), + ] + + def __init__(self, re_module, global_keep_all_tokens): + terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()] + + rules = [options_from_rule(name, None, x) for name, x in RULES.items()] + rules = [Rule(NonTerminal(r), symbols_from_strcase(x.split()), i, None, o) for r, _p, xs, o in rules for i, x in enumerate(xs)] + callback = ParseTreeBuilder(rules, ST).create_callback() + lexer_conf = LexerConf(terminals, re_module, ['WS', 'COMMENT']) + + parser_conf = ParserConf(rules, callback, ['start']) + self.parser = LALR_TraditionalLexer(lexer_conf, parser_conf) + + self.canonize_tree = CanonizeTree() + self.re_module = re_module + self.global_keep_all_tokens = global_keep_all_tokens + + def import_grammar(self, grammar_path, base_paths=[]): + if grammar_path not in _imported_grammars: + import_paths = base_paths + IMPORT_PATHS + for import_path in import_paths: + with suppress(IOError): + joined_path = os.path.join(import_path, grammar_path) + with open(joined_path, encoding='utf8') as f: + text = f.read() + grammar = self.load_grammar(text, joined_path) + _imported_grammars[grammar_path] = grammar + break + else: + open(grammar_path, encoding='utf8') # Force a file not found error + assert False + + return _imported_grammars[grammar_path] + + def load_grammar(self, grammar_text, grammar_name=''): + "Parse grammar_text, verify, and create Grammar object. Display nice messages on error." + + try: + tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') ) + except UnexpectedCharacters as e: + context = e.get_context(grammar_text) + raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" % + (e.line, e.column, grammar_name, context)) + except UnexpectedToken as e: + context = e.get_context(grammar_text) + error = e.match_examples(self.parser.parse, self.ERRORS, use_accepts=True) + if error: + raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context)) + elif 'STRING' in e.expected: + raise GrammarError("Expecting a value at line %s column %s\n\n%s" % (e.line, e.column, context)) + raise + + tree = PrepareGrammar().transform(tree) + + # Extract grammar items + defs = classify(tree.children, lambda c: c.data, lambda c: c.children) + term_defs = defs.pop('term', []) + rule_defs = defs.pop('rule', []) + statements = defs.pop('statement', []) + assert not defs + + term_defs = [td if len(td)==3 else (td[0], 1, td[1]) for td in term_defs] + term_defs = [(name.value, (t, int(p))) for name, p, t in term_defs] + rule_defs = [options_from_rule(*x) for x in rule_defs] + + # Execute statements + ignore, imports = [], {} + for (stmt,) in statements: + if stmt.data == 'ignore': + t ,= stmt.children + ignore.append(t) + elif stmt.data == 'import': + if len(stmt.children) > 1: + path_node, arg1 = stmt.children + else: + path_node ,= stmt.children + arg1 = None + + if isinstance(arg1, Tree): # Multi import + dotted_path = tuple(path_node.children) + names = arg1.children + aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names + else: # Single import + dotted_path = tuple(path_node.children[:-1]) + name = path_node.children[-1] # Get name from dotted path + aliases = {name: arg1 or name} # Aliases if exist + + if path_node.data == 'import_lib': # Import from library + base_paths = [] + else: # Relative import + if grammar_name == '': # Import relative to script file path if grammar is coded in script + try: + base_file = os.path.abspath(sys.modules['__main__'].__file__) + except AttributeError: + base_file = None + else: + base_file = grammar_name # Import relative to grammar file path if external grammar file + if base_file: + base_paths = [os.path.split(base_file)[0]] + else: + base_paths = [os.path.abspath(os.path.curdir)] + + try: + import_base_paths, import_aliases = imports[dotted_path] + assert base_paths == import_base_paths, 'Inconsistent base_paths for %s.' % '.'.join(dotted_path) + import_aliases.update(aliases) + except KeyError: + imports[dotted_path] = base_paths, aliases + + elif stmt.data == 'declare': + for t in stmt.children: + term_defs.append([t.value, (None, None)]) + else: + assert False, stmt + + # import grammars + for dotted_path, (base_paths, aliases) in imports.items(): + grammar_path = os.path.join(*dotted_path) + EXT + g = self.import_grammar(grammar_path, base_paths=base_paths) + new_td, new_rd = import_from_grammar_into_namespace(g, '__'.join(dotted_path), aliases) + + term_defs += new_td + rule_defs += new_rd + + # Verify correctness 1 + for name, _ in term_defs: + if name.startswith('__'): + raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name) + + # Handle ignore tokens + # XXX A slightly hacky solution. Recognition of %ignore TERMINAL as separate comes from the lexer's + # inability to handle duplicate terminals (two names, one value) + ignore_names = [] + for t in ignore: + if t.data=='expansions' and len(t.children) == 1: + t2 ,= t.children + if t2.data=='expansion' and len(t2.children) == 1: + item ,= t2.children + if item.data == 'value': + item ,= item.children + if isinstance(item, Token) and item.type == 'TERMINAL': + ignore_names.append(item.value) + continue + + name = '__IGNORE_%d'% len(ignore_names) + ignore_names.append(name) + term_defs.append((name, (t, 1))) + + # Verify correctness 2 + terminal_names = set() + for name, _ in term_defs: + if name in terminal_names: + raise GrammarError("Terminal '%s' defined more than once" % name) + terminal_names.add(name) + + if set(ignore_names) > terminal_names: + raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(ignore_names) - terminal_names)) + + resolve_term_references(term_defs) + + rules = rule_defs + + rule_names = {} + for name, params, _x, option in rules: + # We can't just simply not throw away the tokens later, we need option.keep_all_tokens to correctly generate maybe_placeholders + if self.global_keep_all_tokens: + option.keep_all_tokens = True + + if name.startswith('__'): + raise GrammarError('Names starting with double-underscore are reserved (Error at %s)' % name) + if name in rule_names: + raise GrammarError("Rule '%s' defined more than once" % name) + rule_names[name] = len(params) + + for name, params , expansions, _o in rules: + for i, p in enumerate(params): + if p in rule_names: + raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name)) + if p in params[:i]: + raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name)) + for temp in expansions.find_data('template_usage'): + sym = temp.children[0] + args = temp.children[1:] + if sym not in params: + if sym not in rule_names: + raise GrammarError("Template '%s' used but not defined (in rule %s)" % (sym, name)) + if len(args) != rule_names[sym]: + raise GrammarError("Wrong number of template arguments used for %s " + "(expected %s, got %s) (in rule %s)"%(sym, rule_names[sym], len(args), name)) + for sym in _find_used_symbols(expansions): + if sym.type == 'TERMINAL': + if sym not in terminal_names: + raise GrammarError("Token '%s' used but not defined (in rule %s)" % (sym, name)) + else: + if sym not in rule_names and sym not in params: + raise GrammarError("Rule '%s' used but not defined (in rule %s)" % (sym, name)) + + + return Grammar(rules, term_defs, ignore_names) + + + +def load_grammar(grammar, source, re_, global_keep_all_tokens): + return GrammarLoader(re_, global_keep_all_tokens).load_grammar(grammar, source) diff --git a/testbed/lark-parser__lark/lark/parse_tree_builder.py b/testbed/lark-parser__lark/lark/parse_tree_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c43302f930aa53e057f79f1fcea3c0c7f2317f --- /dev/null +++ b/testbed/lark-parser__lark/lark/parse_tree_builder.py @@ -0,0 +1,357 @@ +from .exceptions import GrammarError +from .lexer import Token +from .tree import Tree +from .visitors import InlineTransformer # XXX Deprecated +from .visitors import Transformer_InPlace +from .visitors import _vargs_meta, _vargs_meta_inline + +###{standalone +from functools import partial, wraps +from itertools import repeat, product + + +class ExpandSingleChild: + def __init__(self, node_builder): + self.node_builder = node_builder + + def __call__(self, children): + if len(children) == 1: + return children[0] + else: + return self.node_builder(children) + +class PropagatePositions: + def __init__(self, node_builder): + self.node_builder = node_builder + + def __call__(self, children): + res = self.node_builder(children) + + # local reference to Tree.meta reduces number of presence checks + if isinstance(res, Tree): + res_meta = res.meta + for c in children: + if isinstance(c, Tree): + child_meta = c.meta + if not child_meta.empty: + res_meta.line = child_meta.line + res_meta.column = child_meta.column + res_meta.start_pos = child_meta.start_pos + res_meta.empty = False + break + elif isinstance(c, Token): + res_meta.line = c.line + res_meta.column = c.column + res_meta.start_pos = c.pos_in_stream + res_meta.empty = False + break + + for c in reversed(children): + if isinstance(c, Tree): + child_meta = c.meta + if not child_meta.empty: + res_meta.end_line = child_meta.end_line + res_meta.end_column = child_meta.end_column + res_meta.end_pos = child_meta.end_pos + res_meta.empty = False + break + elif isinstance(c, Token): + res_meta.end_line = c.end_line + res_meta.end_column = c.end_column + res_meta.end_pos = c.end_pos + res_meta.empty = False + break + + return res + + +class ChildFilter: + def __init__(self, to_include, append_none, node_builder): + self.node_builder = node_builder + self.to_include = to_include + self.append_none = append_none + + def __call__(self, children): + filtered = [] + + for i, to_expand, add_none in self.to_include: + if add_none: + filtered += [None] * add_none + if to_expand: + filtered += children[i].children + else: + filtered.append(children[i]) + + if self.append_none: + filtered += [None] * self.append_none + + return self.node_builder(filtered) + +class ChildFilterLALR(ChildFilter): + "Optimized childfilter for LALR (assumes no duplication in parse tree, so it's safe to change it)" + + def __call__(self, children): + filtered = [] + for i, to_expand, add_none in self.to_include: + if add_none: + filtered += [None] * add_none + if to_expand: + if filtered: + filtered += children[i].children + else: # Optimize for left-recursion + filtered = children[i].children + else: + filtered.append(children[i]) + + if self.append_none: + filtered += [None] * self.append_none + + return self.node_builder(filtered) + +class ChildFilterLALR_NoPlaceholders(ChildFilter): + "Optimized childfilter for LALR (assumes no duplication in parse tree, so it's safe to change it)" + def __init__(self, to_include, node_builder): + self.node_builder = node_builder + self.to_include = to_include + + def __call__(self, children): + filtered = [] + for i, to_expand in self.to_include: + if to_expand: + if filtered: + filtered += children[i].children + else: # Optimize for left-recursion + filtered = children[i].children + else: + filtered.append(children[i]) + return self.node_builder(filtered) + +def _should_expand(sym): + return not sym.is_term and sym.name.startswith('_') + +def maybe_create_child_filter(expansion, keep_all_tokens, ambiguous, _empty_indices): + # Prepare empty_indices as: How many Nones to insert at each index? + if _empty_indices: + assert _empty_indices.count(False) == len(expansion) + s = ''.join(str(int(b)) for b in _empty_indices) + empty_indices = [len(ones) for ones in s.split('0')] + assert len(empty_indices) == len(expansion)+1, (empty_indices, len(expansion)) + else: + empty_indices = [0] * (len(expansion)+1) + + to_include = [] + nones_to_add = 0 + for i, sym in enumerate(expansion): + nones_to_add += empty_indices[i] + if keep_all_tokens or not (sym.is_term and sym.filter_out): + to_include.append((i, _should_expand(sym), nones_to_add)) + nones_to_add = 0 + + nones_to_add += empty_indices[len(expansion)] + + if _empty_indices or len(to_include) < len(expansion) or any(to_expand for i, to_expand,_ in to_include): + if _empty_indices or ambiguous: + return partial(ChildFilter if ambiguous else ChildFilterLALR, to_include, nones_to_add) + else: + # LALR without placeholders + return partial(ChildFilterLALR_NoPlaceholders, [(i, x) for i,x,_ in to_include]) + +class AmbiguousExpander: + """Deal with the case where we're expanding children ('_rule') into a parent but the children + are ambiguous. i.e. (parent->_ambig->_expand_this_rule). In this case, make the parent itself + ambiguous with as many copies as their are ambiguous children, and then copy the ambiguous children + into the right parents in the right places, essentially shifting the ambiguiuty up the tree.""" + def __init__(self, to_expand, tree_class, node_builder): + self.node_builder = node_builder + self.tree_class = tree_class + self.to_expand = to_expand + + def __call__(self, children): + def _is_ambig_tree(child): + return hasattr(child, 'data') and child.data == '_ambig' + + #### When we're repeatedly expanding ambiguities we can end up with nested ambiguities. + # All children of an _ambig node should be a derivation of that ambig node, hence + # it is safe to assume that if we see an _ambig node nested within an ambig node + # it is safe to simply expand it into the parent _ambig node as an alternative derivation. + ambiguous = [] + for i, child in enumerate(children): + if _is_ambig_tree(child): + if i in self.to_expand: + ambiguous.append(i) + + to_expand = [j for j, grandchild in enumerate(child.children) if _is_ambig_tree(grandchild)] + child.expand_kids_by_index(*to_expand) + + if not ambiguous: + return self.node_builder(children) + + expand = [ iter(child.children) if i in ambiguous else repeat(child) for i, child in enumerate(children) ] + return self.tree_class('_ambig', [self.node_builder(list(f[0])) for f in product(zip(*expand))]) + +def maybe_create_ambiguous_expander(tree_class, expansion, keep_all_tokens): + to_expand = [i for i, sym in enumerate(expansion) + if keep_all_tokens or ((not (sym.is_term and sym.filter_out)) and _should_expand(sym))] + if to_expand: + return partial(AmbiguousExpander, to_expand, tree_class) + +class AmbiguousIntermediateExpander: + """ + Propagate ambiguous intermediate nodes and their derivations up to the + current rule. + + In general, converts + + rule + _iambig + _inter + someChildren1 + ... + _inter + someChildren2 + ... + someChildren3 + ... + + to + + _ambig + rule + someChildren1 + ... + someChildren3 + ... + rule + someChildren2 + ... + someChildren3 + ... + rule + childrenFromNestedIambigs + ... + someChildren3 + ... + ... + + propagating up any nested '_iambig' nodes along the way. + """ + + def __init__(self, tree_class, node_builder): + self.node_builder = node_builder + self.tree_class = tree_class + + def __call__(self, children): + def _is_iambig_tree(child): + return hasattr(child, 'data') and child.data == '_iambig' + + def _collapse_iambig(children): + """ + Recursively flatten the derivations of the parent of an '_iambig' + node. Returns a list of '_inter' nodes guaranteed not + to contain any nested '_iambig' nodes, or None if children does + not contain an '_iambig' node. + """ + + # Due to the structure of the SPPF, + # an '_iambig' node can only appear as the first child + if children and _is_iambig_tree(children[0]): + iambig_node = children[0] + result = [] + for grandchild in iambig_node.children: + collapsed = _collapse_iambig(grandchild.children) + if collapsed: + for child in collapsed: + child.children += children[1:] + result += collapsed + else: + new_tree = self.tree_class('_inter', grandchild.children + children[1:]) + result.append(new_tree) + return result + + collapsed = _collapse_iambig(children) + if collapsed: + processed_nodes = [self.node_builder(c.children) for c in collapsed] + return self.tree_class('_ambig', processed_nodes) + + return self.node_builder(children) + +def ptb_inline_args(func): + @wraps(func) + def f(children): + return func(*children) + return f + +def inplace_transformer(func): + @wraps(func) + def f(children): + # function name in a Transformer is a rule name. + tree = Tree(func.__name__, children) + return func(tree) + return f + +def apply_visit_wrapper(func, name, wrapper): + if wrapper is _vargs_meta or wrapper is _vargs_meta_inline: + raise NotImplementedError("Meta args not supported for internal transformer") + @wraps(func) + def f(children): + return wrapper(func, name, children, None) + return f + + +class ParseTreeBuilder: + def __init__(self, rules, tree_class, propagate_positions=False, ambiguous=False, maybe_placeholders=False): + self.tree_class = tree_class + self.propagate_positions = propagate_positions + self.ambiguous = ambiguous + self.maybe_placeholders = maybe_placeholders + + self.rule_builders = list(self._init_builders(rules)) + + def _init_builders(self, rules): + for rule in rules: + options = rule.options + keep_all_tokens = options.keep_all_tokens + expand_single_child = options.expand1 + + wrapper_chain = list(filter(None, [ + (expand_single_child and not rule.alias) and ExpandSingleChild, + maybe_create_child_filter(rule.expansion, keep_all_tokens, self.ambiguous, options.empty_indices if self.maybe_placeholders else None), + self.propagate_positions and PropagatePositions, + self.ambiguous and maybe_create_ambiguous_expander(self.tree_class, rule.expansion, keep_all_tokens), + self.ambiguous and partial(AmbiguousIntermediateExpander, self.tree_class) + ])) + + yield rule, wrapper_chain + + + def create_callback(self, transformer=None): + callbacks = {} + + for rule, wrapper_chain in self.rule_builders: + + user_callback_name = rule.alias or rule.options.template_source or rule.origin.name + try: + f = getattr(transformer, user_callback_name) + # XXX InlineTransformer is deprecated! + wrapper = getattr(f, 'visit_wrapper', None) + if wrapper is not None: + f = apply_visit_wrapper(f, user_callback_name, wrapper) + else: + if isinstance(transformer, InlineTransformer): + f = ptb_inline_args(f) + elif isinstance(transformer, Transformer_InPlace): + f = inplace_transformer(f) + except AttributeError: + f = partial(self.tree_class, user_callback_name) + + for w in wrapper_chain: + f = w(f) + + if rule in callbacks: + raise GrammarError("Rule '%s' already exists" % (rule,)) + + callbacks[rule] = f + + return callbacks + +###} diff --git a/testbed/lark-parser__lark/lark/parser_frontends.py b/testbed/lark-parser__lark/lark/parser_frontends.py new file mode 100644 index 0000000000000000000000000000000000000000..926603cf689d70ed047b476282d8a00c0ccbc95f --- /dev/null +++ b/testbed/lark-parser__lark/lark/parser_frontends.py @@ -0,0 +1,255 @@ +from .utils import get_regexp_width, Serialize +from .parsers.grammar_analysis import GrammarAnalyzer +from .lexer import TraditionalLexer, ContextualLexer, Lexer, Token, TerminalDef +from .parsers import earley, xearley, cyk +from .parsers.lalr_parser import LALR_Parser +from .grammar import Rule +from .tree import Tree +from .common import LexerConf +try: + import regex +except ImportError: + regex = None +import re + +###{standalone + +def get_frontend(parser, lexer): + if parser=='lalr': + if lexer is None: + raise ValueError('The LALR parser requires use of a lexer') + elif lexer == 'standard': + return LALR_TraditionalLexer + elif lexer == 'contextual': + return LALR_ContextualLexer + elif issubclass(lexer, Lexer): + class LALR_CustomLexerWrapper(LALR_CustomLexer): + def __init__(self, lexer_conf, parser_conf, options=None): + super(LALR_CustomLexerWrapper, self).__init__( + lexer, lexer_conf, parser_conf, options=options) + def init_lexer(self): + self.lexer = lexer(self.lexer_conf) + + return LALR_CustomLexerWrapper + else: + raise ValueError('Unknown lexer: %s' % lexer) + elif parser=='earley': + if lexer=='standard': + return Earley + elif lexer=='dynamic': + return XEarley + elif lexer=='dynamic_complete': + return XEarley_CompleteLex + elif lexer=='contextual': + raise ValueError('The Earley parser does not support the contextual parser') + else: + raise ValueError('Unknown lexer: %s' % lexer) + elif parser == 'cyk': + if lexer == 'standard': + return CYK + else: + raise ValueError('CYK parser requires using standard parser.') + else: + raise ValueError('Unknown parser: %s' % parser) + + +class _ParserFrontend(Serialize): + def _parse(self, input, start, *args): + if start is None: + start = self.start + if len(start) > 1: + raise ValueError("Lark initialized with more than 1 possible start rule. Must specify which start rule to parse", start) + start ,= start + return self.parser.parse(input, start, *args) + + +def _get_lexer_callbacks(transformer, terminals): + result = {} + for terminal in terminals: + callback = getattr(transformer, terminal.name, None) + if callback is not None: + result[terminal.name] = callback + return result + + +class WithLexer(_ParserFrontend): + lexer = None + parser = None + lexer_conf = None + start = None + + __serialize_fields__ = 'parser', 'lexer_conf', 'start' + __serialize_namespace__ = LexerConf, + + def __init__(self, lexer_conf, parser_conf, options=None): + self.lexer_conf = lexer_conf + self.start = parser_conf.start + self.postlex = lexer_conf.postlex + + @classmethod + def deserialize(cls, data, memo, callbacks, options): + inst = super(WithLexer, cls).deserialize(data, memo) + + inst.postlex = options.postlex + inst.parser = LALR_Parser.deserialize(inst.parser, memo, callbacks, options.debug) + + terminals = [item for item in memo.values() if isinstance(item, TerminalDef)] + inst.lexer_conf.callbacks = _get_lexer_callbacks(options.transformer, terminals) + inst.lexer_conf.re_module = regex if options.regex else re + inst.lexer_conf.use_bytes = options.use_bytes + inst.lexer_conf.g_regex_flags = options.g_regex_flags + inst.lexer_conf.skip_validation = True + inst.init_lexer() + + return inst + + def _serialize(self, data, memo): + data['parser'] = data['parser'].serialize(memo) + + def lex(self, *args): + stream = self.lexer.lex(*args) + return self.postlex.process(stream) if self.postlex else stream + + def parse(self, text, start=None): + token_stream = self.lex(text) + return self._parse(token_stream, start) + + def init_traditional_lexer(self): + self.lexer = TraditionalLexer(self.lexer_conf) + +class LALR_WithLexer(WithLexer): + def __init__(self, lexer_conf, parser_conf, options=None): + debug = options.debug if options else False + self.parser = LALR_Parser(parser_conf, debug=debug) + WithLexer.__init__(self, lexer_conf, parser_conf, options) + + self.init_lexer() + + def init_lexer(self, **kw): + raise NotImplementedError() + +class LALR_TraditionalLexer(LALR_WithLexer): + def init_lexer(self): + self.init_traditional_lexer() + +class LALR_ContextualLexer(LALR_WithLexer): + def init_lexer(self): + states = {idx:list(t.keys()) for idx, t in self.parser._parse_table.states.items()} + always_accept = self.postlex.always_accept if self.postlex else () + self.lexer = ContextualLexer(self.lexer_conf, states, always_accept=always_accept) + + + def parse(self, text, start=None): + parser_state = [None] + def set_parser_state(s): + parser_state[0] = s + + token_stream = self.lex(text, lambda: parser_state[0]) + return self._parse(token_stream, start, set_parser_state) +###} + +class LALR_CustomLexer(LALR_WithLexer): + def __init__(self, lexer_cls, lexer_conf, parser_conf, options=None): + self.lexer = lexer_cls(lexer_conf) + debug = options.debug if options else False + self.parser = LALR_Parser(parser_conf, debug=debug) + WithLexer.__init__(self, lexer_conf, parser_conf, options) + + +def tokenize_text(text): + line = 1 + col_start_pos = 0 + for i, ch in enumerate(text): + if '\n' in ch: + line += ch.count('\n') + col_start_pos = i + ch.rindex('\n') + yield Token('CHAR', ch, line=line, column=i - col_start_pos) + +class Earley(WithLexer): + def __init__(self, lexer_conf, parser_conf, options=None): + WithLexer.__init__(self, lexer_conf, parser_conf, options) + self.init_traditional_lexer() + + resolve_ambiguity = options.ambiguity == 'resolve' + debug = options.debug if options else False + tree_class = options.tree_class or Tree if options.ambiguity != 'forest' else None + self.parser = earley.Parser(parser_conf, self.match, resolve_ambiguity=resolve_ambiguity, debug=debug, tree_class=tree_class) + + def match(self, term, token): + return term.name == token.type + + +class XEarley(_ParserFrontend): + def __init__(self, lexer_conf, parser_conf, options=None, **kw): + self.token_by_name = {t.name:t for t in lexer_conf.tokens} + self.start = parser_conf.start + + self._prepare_match(lexer_conf) + resolve_ambiguity = options.ambiguity == 'resolve' + debug = options.debug if options else False + tree_class = options.tree_class or Tree if options.ambiguity != 'forest' else None + self.parser = xearley.Parser(parser_conf, + self.match, + ignore=lexer_conf.ignore, + resolve_ambiguity=resolve_ambiguity, + debug=debug, + tree_class=tree_class, + **kw + ) + + def match(self, term, text, index=0): + return self.regexps[term.name].match(text, index) + + def _prepare_match(self, lexer_conf): + self.regexps = {} + for t in lexer_conf.tokens: + if t.priority != 1: + raise ValueError("Dynamic Earley doesn't support weights on terminals", t, t.priority) + regexp = t.pattern.to_regexp() + try: + width = get_regexp_width(regexp)[0] + except ValueError: + raise ValueError("Bad regexp in token %s: %s" % (t.name, regexp)) + else: + if width == 0: + raise ValueError("Dynamic Earley doesn't allow zero-width regexps", t) + if lexer_conf.use_bytes: + regexp = regexp.encode('utf-8') + + self.regexps[t.name] = lexer_conf.re_module.compile(regexp, lexer_conf.g_regex_flags) + + def parse(self, text, start): + return self._parse(text, start) + +class XEarley_CompleteLex(XEarley): + def __init__(self, *args, **kw): + XEarley.__init__(self, *args, complete_lex=True, **kw) + + + +class CYK(WithLexer): + + def __init__(self, lexer_conf, parser_conf, options=None): + WithLexer.__init__(self, lexer_conf, parser_conf, options) + self.init_traditional_lexer() + + self._analysis = GrammarAnalyzer(parser_conf) + self.parser = cyk.Parser(parser_conf.rules) + + self.callbacks = parser_conf.callbacks + + def parse(self, text, start): + tokens = list(self.lex(text)) + parse = self._parse(tokens, start) + parse = self._transform(parse) + return parse + + def _transform(self, tree): + subtrees = list(tree.iter_subtrees()) + for subtree in subtrees: + subtree.children = [self._apply_callback(c) if isinstance(c, Tree) else c for c in subtree.children] + + return self._apply_callback(tree) + + def _apply_callback(self, tree): + return self.callbacks[tree.rule](tree.children) diff --git a/testbed/lark-parser__lark/lark/parsers/__init__.py b/testbed/lark-parser__lark/lark/parsers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/lark-parser__lark/lark/parsers/cyk.py b/testbed/lark-parser__lark/lark/parsers/cyk.py new file mode 100644 index 0000000000000000000000000000000000000000..ff0924f2415dc5e93af4501de66246d2f5958a78 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/cyk.py @@ -0,0 +1,345 @@ +"""This module implements a CYK parser.""" + +# Author: https://github.com/ehudt (2018) +# +# Adapted by Erez + + +from collections import defaultdict +import itertools + +from ..exceptions import ParseError +from ..lexer import Token +from ..tree import Tree +from ..grammar import Terminal as T, NonTerminal as NT, Symbol + +try: + xrange +except NameError: + xrange = range + +def match(t, s): + assert isinstance(t, T) + return t.name == s.type + + +class Rule(object): + """Context-free grammar rule.""" + + def __init__(self, lhs, rhs, weight, alias): + super(Rule, self).__init__() + assert isinstance(lhs, NT), lhs + assert all(isinstance(x, NT) or isinstance(x, T) for x in rhs), rhs + self.lhs = lhs + self.rhs = rhs + self.weight = weight + self.alias = alias + + def __str__(self): + return '%s -> %s' % (str(self.lhs), ' '.join(str(x) for x in self.rhs)) + + def __repr__(self): + return str(self) + + def __hash__(self): + return hash((self.lhs, tuple(self.rhs))) + + def __eq__(self, other): + return self.lhs == other.lhs and self.rhs == other.rhs + + def __ne__(self, other): + return not (self == other) + + +class Grammar(object): + """Context-free grammar.""" + + def __init__(self, rules): + self.rules = frozenset(rules) + + def __eq__(self, other): + return self.rules == other.rules + + def __str__(self): + return '\n' + '\n'.join(sorted(repr(x) for x in self.rules)) + '\n' + + def __repr__(self): + return str(self) + + +# Parse tree data structures +class RuleNode(object): + """A node in the parse tree, which also contains the full rhs rule.""" + + def __init__(self, rule, children, weight=0): + self.rule = rule + self.children = children + self.weight = weight + + def __repr__(self): + return 'RuleNode(%s, [%s])' % (repr(self.rule.lhs), ', '.join(str(x) for x in self.children)) + + + +class Parser(object): + """Parser wrapper.""" + + def __init__(self, rules): + super(Parser, self).__init__() + self.orig_rules = {rule: rule for rule in rules} + rules = [self._to_rule(rule) for rule in rules] + self.grammar = to_cnf(Grammar(rules)) + + def _to_rule(self, lark_rule): + """Converts a lark rule, (lhs, rhs, callback, options), to a Rule.""" + assert isinstance(lark_rule.origin, NT) + assert all(isinstance(x, Symbol) for x in lark_rule.expansion) + return Rule( + lark_rule.origin, lark_rule.expansion, + weight=lark_rule.options.priority if lark_rule.options.priority else 0, + alias=lark_rule) + + def parse(self, tokenized, start): # pylint: disable=invalid-name + """Parses input, which is a list of tokens.""" + assert start + start = NT(start) + + table, trees = _parse(tokenized, self.grammar) + # Check if the parse succeeded. + if all(r.lhs != start for r in table[(0, len(tokenized) - 1)]): + raise ParseError('Parsing failed.') + parse = trees[(0, len(tokenized) - 1)][start] + return self._to_tree(revert_cnf(parse)) + + def _to_tree(self, rule_node): + """Converts a RuleNode parse tree to a lark Tree.""" + orig_rule = self.orig_rules[rule_node.rule.alias] + children = [] + for child in rule_node.children: + if isinstance(child, RuleNode): + children.append(self._to_tree(child)) + else: + assert isinstance(child.name, Token) + children.append(child.name) + t = Tree(orig_rule.origin, children) + t.rule=orig_rule + return t + + +def print_parse(node, indent=0): + if isinstance(node, RuleNode): + print(' ' * (indent * 2) + str(node.rule.lhs)) + for child in node.children: + print_parse(child, indent + 1) + else: + print(' ' * (indent * 2) + str(node.s)) + + +def _parse(s, g): + """Parses sentence 's' using CNF grammar 'g'.""" + # The CYK table. Indexed with a 2-tuple: (start pos, end pos) + table = defaultdict(set) + # Top-level structure is similar to the CYK table. Each cell is a dict from + # rule name to the best (lightest) tree for that rule. + trees = defaultdict(dict) + # Populate base case with existing terminal production rules + for i, w in enumerate(s): + for terminal, rules in g.terminal_rules.items(): + if match(terminal, w): + for rule in rules: + table[(i, i)].add(rule) + if (rule.lhs not in trees[(i, i)] or + rule.weight < trees[(i, i)][rule.lhs].weight): + trees[(i, i)][rule.lhs] = RuleNode(rule, [T(w)], weight=rule.weight) + + # Iterate over lengths of sub-sentences + for l in xrange(2, len(s) + 1): + # Iterate over sub-sentences with the given length + for i in xrange(len(s) - l + 1): + # Choose partition of the sub-sentence in [1, l) + for p in xrange(i + 1, i + l): + span1 = (i, p - 1) + span2 = (p, i + l - 1) + for r1, r2 in itertools.product(table[span1], table[span2]): + for rule in g.nonterminal_rules.get((r1.lhs, r2.lhs), []): + table[(i, i + l - 1)].add(rule) + r1_tree = trees[span1][r1.lhs] + r2_tree = trees[span2][r2.lhs] + rule_total_weight = rule.weight + r1_tree.weight + r2_tree.weight + if (rule.lhs not in trees[(i, i + l - 1)] + or rule_total_weight < trees[(i, i + l - 1)][rule.lhs].weight): + trees[(i, i + l - 1)][rule.lhs] = RuleNode(rule, [r1_tree, r2_tree], weight=rule_total_weight) + return table, trees + + +# This section implements context-free grammar converter to Chomsky normal form. +# It also implements a conversion of parse trees from its CNF to the original +# grammar. +# Overview: +# Applies the following operations in this order: +# * TERM: Eliminates non-solitary terminals from all rules +# * BIN: Eliminates rules with more than 2 symbols on their right-hand-side. +# * UNIT: Eliminates non-terminal unit rules +# +# The following grammar characteristics aren't featured: +# * Start symbol appears on RHS +# * Empty rules (epsilon rules) + + +class CnfWrapper(object): + """CNF wrapper for grammar. + + Validates that the input grammar is CNF and provides helper data structures. + """ + + def __init__(self, grammar): + super(CnfWrapper, self).__init__() + self.grammar = grammar + self.rules = grammar.rules + self.terminal_rules = defaultdict(list) + self.nonterminal_rules = defaultdict(list) + for r in self.rules: + # Validate that the grammar is CNF and populate auxiliary data structures. + assert isinstance(r.lhs, NT), r + if len(r.rhs) not in [1, 2]: + raise ParseError("CYK doesn't support empty rules") + if len(r.rhs) == 1 and isinstance(r.rhs[0], T): + self.terminal_rules[r.rhs[0]].append(r) + elif len(r.rhs) == 2 and all(isinstance(x, NT) for x in r.rhs): + self.nonterminal_rules[tuple(r.rhs)].append(r) + else: + assert False, r + + def __eq__(self, other): + return self.grammar == other.grammar + + def __repr__(self): + return repr(self.grammar) + + +class UnitSkipRule(Rule): + """A rule that records NTs that were skipped during transformation.""" + + def __init__(self, lhs, rhs, skipped_rules, weight, alias): + super(UnitSkipRule, self).__init__(lhs, rhs, weight, alias) + self.skipped_rules = skipped_rules + + def __eq__(self, other): + return isinstance(other, type(self)) and self.skipped_rules == other.skipped_rules + + __hash__ = Rule.__hash__ + + +def build_unit_skiprule(unit_rule, target_rule): + skipped_rules = [] + if isinstance(unit_rule, UnitSkipRule): + skipped_rules += unit_rule.skipped_rules + skipped_rules.append(target_rule) + if isinstance(target_rule, UnitSkipRule): + skipped_rules += target_rule.skipped_rules + return UnitSkipRule(unit_rule.lhs, target_rule.rhs, skipped_rules, + weight=unit_rule.weight + target_rule.weight, alias=unit_rule.alias) + + +def get_any_nt_unit_rule(g): + """Returns a non-terminal unit rule from 'g', or None if there is none.""" + for rule in g.rules: + if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT): + return rule + return None + + +def _remove_unit_rule(g, rule): + """Removes 'rule' from 'g' without changing the langugage produced by 'g'.""" + new_rules = [x for x in g.rules if x != rule] + refs = [x for x in g.rules if x.lhs == rule.rhs[0]] + new_rules += [build_unit_skiprule(rule, ref) for ref in refs] + return Grammar(new_rules) + + +def _split(rule): + """Splits a rule whose len(rhs) > 2 into shorter rules.""" + rule_str = str(rule.lhs) + '__' + '_'.join(str(x) for x in rule.rhs) + rule_name = '__SP_%s' % (rule_str) + '_%d' + yield Rule(rule.lhs, [rule.rhs[0], NT(rule_name % 1)], weight=rule.weight, alias=rule.alias) + for i in xrange(1, len(rule.rhs) - 2): + yield Rule(NT(rule_name % i), [rule.rhs[i], NT(rule_name % (i + 1))], weight=0, alias='Split') + yield Rule(NT(rule_name % (len(rule.rhs) - 2)), rule.rhs[-2:], weight=0, alias='Split') + + +def _term(g): + """Applies the TERM rule on 'g' (see top comment).""" + all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)} + t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t} + new_rules = [] + for rule in g.rules: + if len(rule.rhs) > 1 and any(isinstance(x, T) for x in rule.rhs): + new_rhs = [t_rules[x].lhs if isinstance(x, T) else x for x in rule.rhs] + new_rules.append(Rule(rule.lhs, new_rhs, weight=rule.weight, alias=rule.alias)) + new_rules.extend(v for k, v in t_rules.items() if k in rule.rhs) + else: + new_rules.append(rule) + return Grammar(new_rules) + + +def _bin(g): + """Applies the BIN rule to 'g' (see top comment).""" + new_rules = [] + for rule in g.rules: + if len(rule.rhs) > 2: + new_rules += _split(rule) + else: + new_rules.append(rule) + return Grammar(new_rules) + + +def _unit(g): + """Applies the UNIT rule to 'g' (see top comment).""" + nt_unit_rule = get_any_nt_unit_rule(g) + while nt_unit_rule: + g = _remove_unit_rule(g, nt_unit_rule) + nt_unit_rule = get_any_nt_unit_rule(g) + return g + + +def to_cnf(g): + """Creates a CNF grammar from a general context-free grammar 'g'.""" + g = _unit(_bin(_term(g))) + return CnfWrapper(g) + + +def unroll_unit_skiprule(lhs, orig_rhs, skipped_rules, children, weight, alias): + if not skipped_rules: + return RuleNode(Rule(lhs, orig_rhs, weight=weight, alias=alias), children, weight=weight) + else: + weight = weight - skipped_rules[0].weight + return RuleNode( + Rule(lhs, [skipped_rules[0].lhs], weight=weight, alias=alias), [ + unroll_unit_skiprule(skipped_rules[0].lhs, orig_rhs, + skipped_rules[1:], children, + skipped_rules[0].weight, skipped_rules[0].alias) + ], weight=weight) + + +def revert_cnf(node): + """Reverts a parse tree (RuleNode) to its original non-CNF form (Node).""" + if isinstance(node, T): + return node + # Reverts TERM rule. + if node.rule.lhs.name.startswith('__T_'): + return node.children[0] + else: + children = [] + for child in map(revert_cnf, node.children): + # Reverts BIN rule. + if isinstance(child, RuleNode) and child.rule.lhs.name.startswith('__SP_'): + children += child.children + else: + children.append(child) + # Reverts UNIT rule. + if isinstance(node.rule, UnitSkipRule): + return unroll_unit_skiprule(node.rule.lhs, node.rule.rhs, + node.rule.skipped_rules, children, + node.rule.weight, node.rule.alias) + else: + return RuleNode(node.rule, children) diff --git a/testbed/lark-parser__lark/lark/parsers/earley.py b/testbed/lark-parser__lark/lark/parsers/earley.py new file mode 100644 index 0000000000000000000000000000000000000000..42542c2f92f783a5843dabcb49580384691101f5 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/earley.py @@ -0,0 +1,331 @@ +"""This module implements an scanerless Earley parser. + +The core Earley algorithm used here is based on Elizabeth Scott's implementation, here: + https://www.sciencedirect.com/science/article/pii/S1571066108001497 + +That is probably the best reference for understanding the algorithm here. + +The Earley parser outputs an SPPF-tree as per that document. The SPPF tree format +is better documented here: + http://www.bramvandersanden.com/post/2014/06/shared-packed-parse-forest/ +""" + +from collections import deque + +from ..tree import Tree +from ..visitors import Transformer_InPlace, v_args +from ..exceptions import UnexpectedEOF, UnexpectedToken +from ..utils import logger +from .grammar_analysis import GrammarAnalyzer +from ..grammar import NonTerminal +from .earley_common import Item, TransitiveItem +from .earley_forest import ForestSumVisitor, SymbolNode, ForestToParseTree + +class Parser: + def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, debug=False, tree_class=Tree): + analysis = GrammarAnalyzer(parser_conf) + self.parser_conf = parser_conf + self.resolve_ambiguity = resolve_ambiguity + self.debug = debug + self.tree_class = tree_class + + self.FIRST = analysis.FIRST + self.NULLABLE = analysis.NULLABLE + self.callbacks = parser_conf.callbacks + self.predictions = {} + + ## These could be moved to the grammar analyzer. Pre-computing these is *much* faster than + # the slow 'isupper' in is_terminal. + self.TERMINALS = { sym for r in parser_conf.rules for sym in r.expansion if sym.is_term } + self.NON_TERMINALS = { sym for r in parser_conf.rules for sym in r.expansion if not sym.is_term } + + self.forest_sum_visitor = None + for rule in parser_conf.rules: + if rule.origin not in self.predictions: + self.predictions[rule.origin] = [x.rule for x in analysis.expand_rule(rule.origin)] + + ## Detect if any rules have priorities set. If the user specified priority = "none" then + # the priorities will be stripped from all rules before they reach us, allowing us to + # skip the extra tree walk. We'll also skip this if the user just didn't specify priorities + # on any rules. + if self.forest_sum_visitor is None and rule.options.priority is not None: + self.forest_sum_visitor = ForestSumVisitor + + self.term_matcher = term_matcher + + + def predict_and_complete(self, i, to_scan, columns, transitives): + """The core Earley Predictor and Completer. + + At each stage of the input, we handling any completed items (things + that matched on the last cycle) and use those to predict what should + come next in the input stream. The completions and any predicted + non-terminals are recursively processed until we reach a set of, + which can be added to the scan list for the next scanner cycle.""" + # Held Completions (H in E.Scotts paper). + node_cache = {} + held_completions = {} + + column = columns[i] + # R (items) = Ei (column.items) + items = deque(column) + while items: + item = items.pop() # remove an element, A say, from R + + ### The Earley completer + if item.is_complete: ### (item.s == string) + if item.node is None: + label = (item.s, item.start, i) + item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label)) + item.node.add_family(item.s, item.rule, item.start, None, None) + + # create_leo_transitives(item.rule.origin, item.start) + + ###R Joop Leo right recursion Completer + if item.rule.origin in transitives[item.start]: + transitive = transitives[item.start][item.s] + if transitive.previous in transitives[transitive.column]: + root_transitive = transitives[transitive.column][transitive.previous] + else: + root_transitive = transitive + + new_item = Item(transitive.rule, transitive.ptr, transitive.start) + label = (root_transitive.s, root_transitive.start, i) + new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label)) + new_item.node.add_path(root_transitive, item.node) + if new_item.expect in self.TERMINALS: + # Add (B :: aC.B, h, y) to Q + to_scan.add(new_item) + elif new_item not in column: + # Add (B :: aC.B, h, y) to Ei and R + column.add(new_item) + items.append(new_item) + ###R Regular Earley completer + else: + # Empty has 0 length. If we complete an empty symbol in a particular + # parse step, we need to be able to use that same empty symbol to complete + # any predictions that result, that themselves require empty. Avoids + # infinite recursion on empty symbols. + # held_completions is 'H' in E.Scott's paper. + is_empty_item = item.start == i + if is_empty_item: + held_completions[item.rule.origin] = item.node + + originators = [originator for originator in columns[item.start] if originator.expect is not None and originator.expect == item.s] + for originator in originators: + new_item = originator.advance() + label = (new_item.s, originator.start, i) + new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label)) + new_item.node.add_family(new_item.s, new_item.rule, i, originator.node, item.node) + if new_item.expect in self.TERMINALS: + # Add (B :: aC.B, h, y) to Q + to_scan.add(new_item) + elif new_item not in column: + # Add (B :: aC.B, h, y) to Ei and R + column.add(new_item) + items.append(new_item) + + ### The Earley predictor + elif item.expect in self.NON_TERMINALS: ### (item.s == lr0) + new_items = [] + for rule in self.predictions[item.expect]: + new_item = Item(rule, 0, i) + new_items.append(new_item) + + # Process any held completions (H). + if item.expect in held_completions: + new_item = item.advance() + label = (new_item.s, item.start, i) + new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label)) + new_item.node.add_family(new_item.s, new_item.rule, new_item.start, item.node, held_completions[item.expect]) + new_items.append(new_item) + + for new_item in new_items: + if new_item.expect in self.TERMINALS: + to_scan.add(new_item) + elif new_item not in column: + column.add(new_item) + items.append(new_item) + + def _parse(self, stream, columns, to_scan, start_symbol=None): + def is_quasi_complete(item): + if item.is_complete: + return True + + quasi = item.advance() + while not quasi.is_complete: + if quasi.expect not in self.NULLABLE: + return False + if quasi.rule.origin == start_symbol and quasi.expect == start_symbol: + return False + quasi = quasi.advance() + return True + + def create_leo_transitives(origin, start): + visited = set() + to_create = [] + trule = None + previous = None + + ### Recursively walk backwards through the Earley sets until we find the + # first transitive candidate. If this is done continuously, we shouldn't + # have to walk more than 1 hop. + while True: + if origin in transitives[start]: + previous = trule = transitives[start][origin] + break + + is_empty_rule = not self.FIRST[origin] + if is_empty_rule: + break + + candidates = [ candidate for candidate in columns[start] if candidate.expect is not None and origin == candidate.expect ] + if len(candidates) != 1: + break + originator = next(iter(candidates)) + + if originator is None or originator in visited: + break + + visited.add(originator) + if not is_quasi_complete(originator): + break + + trule = originator.advance() + if originator.start != start: + visited.clear() + + to_create.append((origin, start, originator)) + origin = originator.rule.origin + start = originator.start + + # If a suitable Transitive candidate is not found, bail. + if trule is None: + return + + #### Now walk forwards and create Transitive Items in each set we walked through; and link + # each transitive item to the next set forwards. + while to_create: + origin, start, originator = to_create.pop() + titem = None + if previous is not None: + titem = previous.next_titem = TransitiveItem(origin, trule, originator, previous.column) + else: + titem = TransitiveItem(origin, trule, originator, start) + previous = transitives[start][origin] = titem + + + + def scan(i, token, to_scan): + """The core Earley Scanner. + + This is a custom implementation of the scanner that uses the + Lark lexer to match tokens. The scan list is built by the + Earley predictor, based on the previously completed tokens. + This ensures that at each phase of the parse we have a custom + lexer context, allowing for more complex ambiguities.""" + next_to_scan = set() + next_set = set() + columns.append(next_set) + transitives.append({}) + node_cache = {} + + for item in set(to_scan): + if match(item.expect, token): + new_item = item.advance() + label = (new_item.s, new_item.start, i) + new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label)) + new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token) + + if new_item.expect in self.TERMINALS: + # add (B ::= Aai+1.B, h, y) to Q' + next_to_scan.add(new_item) + else: + # add (B ::= Aa+1.B, h, y) to Ei+1 + next_set.add(new_item) + + if not next_set and not next_to_scan: + expect = {i.expect.name for i in to_scan} + raise UnexpectedToken(token, expect, considered_rules = set(to_scan)) + + return next_to_scan + + + # Define parser functions + match = self.term_matcher + + # Cache for nodes & tokens created in a particular parse step. + transitives = [{}] + + ## The main Earley loop. + # Run the Prediction/Completion cycle for any Items in the current Earley set. + # Completions will be added to the SPPF tree, and predictions will be recursively + # processed down to terminals/empty nodes to be added to the scanner for the next + # step. + i = 0 + for token in stream: + self.predict_and_complete(i, to_scan, columns, transitives) + + to_scan = scan(i, token, to_scan) + i += 1 + + self.predict_and_complete(i, to_scan, columns, transitives) + + ## Column is now the final column in the parse. + assert i == len(columns)-1 + return to_scan + + def parse(self, stream, start): + assert start, start + start_symbol = NonTerminal(start) + + columns = [set()] + to_scan = set() # The scan buffer. 'Q' in E.Scott's paper. + + ## Predict for the start_symbol. + # Add predicted items to the first Earley set (for the predictor) if they + # result in a non-terminal, or the scanner if they result in a terminal. + for rule in self.predictions[start_symbol]: + item = Item(rule, 0, 0) + if item.expect in self.TERMINALS: + to_scan.add(item) + else: + columns[0].add(item) + + to_scan = self._parse(stream, columns, to_scan, start_symbol) + + # If the parse was successful, the start + # symbol should have been completed in the last step of the Earley cycle, and will be in + # this column. Find the item for the start_symbol, which is the root of the SPPF tree. + solutions = [n.node for n in columns[-1] if n.is_complete and n.node is not None and n.s == start_symbol and n.start == 0] + if self.debug: + from .earley_forest import ForestToPyDotVisitor + try: + debug_walker = ForestToPyDotVisitor() + except ImportError: + logger.warning("Cannot find dependency 'pydot', will not generate sppf debug image") + else: + debug_walker.visit(solutions[0], "sppf.png") + + + if not solutions: + expected_tokens = [t.expect for t in to_scan] + raise UnexpectedEOF(expected_tokens) + elif len(solutions) > 1: + assert False, 'Earley should not generate multiple start symbol items!' + + if self.tree_class is not None: + # Perform our SPPF -> AST conversion + transformer = ForestToParseTree(self.tree_class, self.callbacks, self.forest_sum_visitor and self.forest_sum_visitor(), self.resolve_ambiguity) + return transformer.transform(solutions[0]) + + # return the root of the SPPF + return solutions[0] + +class ApplyCallbacks(Transformer_InPlace): + def __init__(self, postprocess): + self.postprocess = postprocess + + @v_args(meta=True) + def drv(self, children, meta): + return self.postprocess[meta.rule](children) diff --git a/testbed/lark-parser__lark/lark/parsers/earley_common.py b/testbed/lark-parser__lark/lark/parsers/earley_common.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd614badf4ff9f93fa47f5d68153085639089e2 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/earley_common.py @@ -0,0 +1,75 @@ +"This module implements an Earley Parser" + +# The parser uses a parse-forest to keep track of derivations and ambiguations. +# When the parse ends successfully, a disambiguation stage resolves all ambiguity +# (right now ambiguity resolution is not developed beyond the needs of lark) +# Afterwards the parse tree is reduced (transformed) according to user callbacks. +# I use the no-recursion version of Transformer, because the tree might be +# deeper than Python's recursion limit (a bit absurd, but that's life) +# +# The algorithm keeps track of each state set, using a corresponding Column instance. +# Column keeps track of new items using NewsList instances. +# +# Author: Erez Shinan (2017) +# Email : erezshin@gmail.com + +from ..grammar import NonTerminal, Terminal + +class Item(object): + "An Earley Item, the atom of the algorithm." + + __slots__ = ('s', 'rule', 'ptr', 'start', 'is_complete', 'expect', 'previous', 'node', '_hash') + def __init__(self, rule, ptr, start): + self.is_complete = len(rule.expansion) == ptr + self.rule = rule # rule + self.ptr = ptr # ptr + self.start = start # j + self.node = None # w + if self.is_complete: + self.s = rule.origin + self.expect = None + self.previous = rule.expansion[ptr - 1] if ptr > 0 and len(rule.expansion) else None + else: + self.s = (rule, ptr) + self.expect = rule.expansion[ptr] + self.previous = rule.expansion[ptr - 1] if ptr > 0 and len(rule.expansion) else None + self._hash = hash((self.s, self.start)) + + def advance(self): + return Item(self.rule, self.ptr + 1, self.start) + + def __eq__(self, other): + return self is other or (self.s == other.s and self.start == other.start) + + def __hash__(self): + return self._hash + + def __repr__(self): + before = ( expansion.name for expansion in self.rule.expansion[:self.ptr] ) + after = ( expansion.name for expansion in self.rule.expansion[self.ptr:] ) + symbol = "{} ::= {}* {}".format(self.rule.origin.name, ' '.join(before), ' '.join(after)) + return '%s (%d)' % (symbol, self.start) + + +class TransitiveItem(Item): + __slots__ = ('recognized', 'reduction', 'column', 'next_titem') + def __init__(self, recognized, trule, originator, start): + super(TransitiveItem, self).__init__(trule.rule, trule.ptr, trule.start) + self.recognized = recognized + self.reduction = originator + self.column = start + self.next_titem = None + self._hash = hash((self.s, self.start, self.recognized)) + + def __eq__(self, other): + if not isinstance(other, TransitiveItem): + return False + return self is other or (type(self.s) == type(other.s) and self.s == other.s and self.start == other.start and self.recognized == other.recognized) + + def __hash__(self): + return self._hash + + def __repr__(self): + before = ( expansion.name for expansion in self.rule.expansion[:self.ptr] ) + after = ( expansion.name for expansion in self.rule.expansion[self.ptr:] ) + return '{} : {} -> {}* {} ({}, {})'.format(self.recognized.name, self.rule.origin.name, ' '.join(before), ' '.join(after), self.column, self.start) diff --git a/testbed/lark-parser__lark/lark/parsers/earley_forest.py b/testbed/lark-parser__lark/lark/parsers/earley_forest.py new file mode 100644 index 0000000000000000000000000000000000000000..532dedf13fc510ad77497ba3e3813e24404fed2c --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/earley_forest.py @@ -0,0 +1,740 @@ +""""This module implements an SPPF implementation + +This is used as the primary output mechanism for the Earley parser +in order to store complex ambiguities. + +Full reference and more details is here: +http://www.bramvandersanden.com/post/2014/06/shared-packed-parse-forest/ +""" + +from random import randint +from math import isinf +from collections import deque +from operator import attrgetter +from importlib import import_module +from functools import partial + +from ..parse_tree_builder import AmbiguousIntermediateExpander +from ..visitors import Discard +from ..lexer import Token +from ..utils import logger +from ..tree import Tree + +class ForestNode(object): + pass + +class SymbolNode(ForestNode): + """ + A Symbol Node represents a symbol (or Intermediate LR0). + + Symbol nodes are keyed by the symbol (s). For intermediate nodes + s will be an LR0, stored as a tuple of (rule, ptr). For completed symbol + nodes, s will be a string representing the non-terminal origin (i.e. + the left hand side of the rule). + + The children of a Symbol or Intermediate Node will always be Packed Nodes; + with each Packed Node child representing a single derivation of a production. + + Hence a Symbol Node with a single child is unambiguous. + + :ivar s: A Symbol, or a tuple of (rule, ptr) for an intermediate node. + :ivar start: The index of the start of the substring matched by this + symbol (inclusive). + :ivar end: The index of the end of the substring matched by this + symbol (exclusive). + :ivar is_intermediate: True if this node is an intermediate node. + :ivar priority: The priority of the node's symbol. + """ + __slots__ = ('s', 'start', 'end', '_children', 'paths', 'paths_loaded', 'priority', 'is_intermediate', '_hash') + def __init__(self, s, start, end): + self.s = s + self.start = start + self.end = end + self._children = set() + self.paths = set() + self.paths_loaded = False + + ### We use inf here as it can be safely negated without resorting to conditionals, + # unlike None or float('NaN'), and sorts appropriately. + self.priority = float('-inf') + self.is_intermediate = isinstance(s, tuple) + self._hash = hash((self.s, self.start, self.end)) + + def add_family(self, lr0, rule, start, left, right): + self._children.add(PackedNode(self, lr0, rule, start, left, right)) + + def add_path(self, transitive, node): + self.paths.add((transitive, node)) + + def load_paths(self): + for transitive, node in self.paths: + if transitive.next_titem is not None: + vn = SymbolNode(transitive.next_titem.s, transitive.next_titem.start, self.end) + vn.add_path(transitive.next_titem, node) + self.add_family(transitive.reduction.rule.origin, transitive.reduction.rule, transitive.reduction.start, transitive.reduction.node, vn) + else: + self.add_family(transitive.reduction.rule.origin, transitive.reduction.rule, transitive.reduction.start, transitive.reduction.node, node) + self.paths_loaded = True + + @property + def is_ambiguous(self): + """Returns True if this node is ambiguous.""" + return len(self.children) > 1 + + @property + def children(self): + """Returns a list of this node's children sorted from greatest to + least priority.""" + if not self.paths_loaded: self.load_paths() + return sorted(self._children, key=attrgetter('sort_key')) + + def __iter__(self): + return iter(self._children) + + def __eq__(self, other): + if not isinstance(other, SymbolNode): + return False + return self is other or (type(self.s) == type(other.s) and self.s == other.s and self.start == other.start and self.end is other.end) + + def __hash__(self): + return self._hash + + def __repr__(self): + if self.is_intermediate: + rule = self.s[0] + ptr = self.s[1] + before = ( expansion.name for expansion in rule.expansion[:ptr] ) + after = ( expansion.name for expansion in rule.expansion[ptr:] ) + symbol = "{} ::= {}* {}".format(rule.origin.name, ' '.join(before), ' '.join(after)) + else: + symbol = self.s.name + return "({}, {}, {}, {})".format(symbol, self.start, self.end, self.priority) + +class PackedNode(ForestNode): + """ + A Packed Node represents a single derivation in a symbol node. + + :ivar rule: The rule associated with this node. + :ivar parent: The parent of this node. + :ivar left: The left child of this node. ``None`` if one does not exist. + :ivar right: The right child of this node. ``None`` if one does not exist. + :ivar priority: The priority of this node. + """ + __slots__ = ('parent', 's', 'rule', 'start', 'left', 'right', 'priority', '_hash') + def __init__(self, parent, s, rule, start, left, right): + self.parent = parent + self.s = s + self.start = start + self.rule = rule + self.left = left + self.right = right + self.priority = float('-inf') + self._hash = hash((self.left, self.right)) + + @property + def is_empty(self): + return self.left is None and self.right is None + + @property + def sort_key(self): + """ + Used to sort PackedNode children of SymbolNodes. + A SymbolNode has multiple PackedNodes if it matched + ambiguously. Hence, we use the sort order to identify + the order in which ambiguous children should be considered. + """ + return self.is_empty, -self.priority, self.rule.order + + @property + def children(self): + """Returns a list of this node's children.""" + return [x for x in [self.left, self.right] if x is not None] + + def __iter__(self): + yield self.left + yield self.right + + def __eq__(self, other): + if not isinstance(other, PackedNode): + return False + return self is other or (self.left == other.left and self.right == other.right) + + def __hash__(self): + return self._hash + + def __repr__(self): + if isinstance(self.s, tuple): + rule = self.s[0] + ptr = self.s[1] + before = ( expansion.name for expansion in rule.expansion[:ptr] ) + after = ( expansion.name for expansion in rule.expansion[ptr:] ) + symbol = "{} ::= {}* {}".format(rule.origin.name, ' '.join(before), ' '.join(after)) + else: + symbol = self.s.name + return "({}, {}, {}, {})".format(symbol, self.start, self.priority, self.rule.order) + +class ForestVisitor(object): + """ + An abstract base class for building forest visitors. + + This class performs a controllable depth-first walk of an SPPF. + The visitor will not enter cycles and will backtrack if one is encountered. + Subclasses are notified of cycles through the ``on_cycle`` method. + + Behavior for visit events is defined by overriding the + ``visit*node*`` functions. + + The walk is controlled by the return values of the ``visit*node_in`` + methods. Returning a node(s) will schedule them to be visited. The visitor + will begin to backtrack if no nodes are returned. + """ + + def visit_token_node(self, node): + """Called when a ``Token`` is visited. ``Token`` nodes are always leaves.""" + pass + + def visit_symbol_node_in(self, node): + """Called when a symbol node is visited. Nodes that are returned + will be scheduled to be visited. If ``visit_intermediate_node_in`` + is not implemented, this function will be called for intermediate + nodes as well.""" + pass + + def visit_symbol_node_out(self, node): + """Called after all nodes returned from a corresponding ``visit_symbol_node_in`` + call have been visited. If ``visit_intermediate_node_out`` + is not implemented, this function will be called for intermediate + nodes as well.""" + pass + + def visit_packed_node_in(self, node): + """Called when a packed node is visited. Nodes that are returned + will be scheduled to be visited. """ + pass + + def visit_packed_node_out(self, node): + """Called after all nodes returned from a corresponding ``visit_packed_node_in`` + call have been visited.""" + pass + + def on_cycle(self, node, path): + """Called when a cycle is encountered. + + :param node: The node that causes a cycle. + :param path: The list of nodes being visited: nodes that have been + entered but not exited. The first element is the root in a forest + visit, and the last element is the node visited most recently. + ``path`` should be treated as read-only. + """ + pass + + def get_cycle_in_path(self, node, path): + """A utility function for use in ``on_cycle`` to obtain a slice of + ``path`` that only contains the nodes that make up the cycle.""" + index = len(path) - 1 + while id(path[index]) != id(node): + index -= 1 + return path[index:] + + def visit(self, root): + # Visiting is a list of IDs of all symbol/intermediate nodes currently in + # the stack. It serves two purposes: to detect when we 'recurse' in and out + # of a symbol/intermediate so that we can process both up and down. Also, + # since the SPPF can have cycles it allows us to detect if we're trying + # to recurse into a node that's already on the stack (infinite recursion). + visiting = set() + + # a list of nodes that are currently being visited + # used for the `on_cycle` callback + path = [] + + # We do not use recursion here to walk the Forest due to the limited + # stack size in python. Therefore input_stack is essentially our stack. + input_stack = deque([root]) + + # It is much faster to cache these as locals since they are called + # many times in large parses. + vpno = getattr(self, 'visit_packed_node_out') + vpni = getattr(self, 'visit_packed_node_in') + vsno = getattr(self, 'visit_symbol_node_out') + vsni = getattr(self, 'visit_symbol_node_in') + vino = getattr(self, 'visit_intermediate_node_out', vsno) + vini = getattr(self, 'visit_intermediate_node_in', vsni) + vtn = getattr(self, 'visit_token_node') + oc = getattr(self, 'on_cycle') + + while input_stack: + current = next(reversed(input_stack)) + try: + next_node = next(current) + except StopIteration: + input_stack.pop() + continue + except TypeError: + ### If the current object is not an iterator, pass through to Token/SymbolNode + pass + else: + if next_node is None: + continue + + if id(next_node) in visiting: + oc(next_node, path) + continue + + input_stack.append(next_node) + continue + + if not isinstance(current, ForestNode): + vtn(current) + input_stack.pop() + continue + + current_id = id(current) + if current_id in visiting: + if isinstance(current, PackedNode): + vpno(current) + elif current.is_intermediate: + vino(current) + else: + vsno(current) + input_stack.pop() + path.pop() + visiting.remove(current_id) + continue + else: + visiting.add(current_id) + path.append(current) + if isinstance(current, PackedNode): + next_node = vpni(current) + elif current.is_intermediate: + next_node = vini(current) + else: + next_node = vsni(current) + if next_node is None: + continue + + if not isinstance(next_node, ForestNode) and \ + not isinstance(next_node, Token): + next_node = iter(next_node) + elif id(next_node) in visiting: + oc(next_node, path) + continue + + input_stack.append(next_node) + continue + +class ForestTransformer(ForestVisitor): + """The base class for a bottom-up forest transformation. Most users will + want to use ``TreeForestTransformer`` instead as it has a friendlier + interface and covers most use cases. + + Transformations are applied via inheritance and overriding of the + ``transform*node`` methods. + + ``transform_token_node`` receives a ``Token`` as an argument. + All other methods receive the node that is being transformed and + a list of the results of the transformations of that node's children. + The return value of these methods are the resulting transformations. + + If ``Discard`` is raised in a node's transformation, no data from that node + will be passed to its parent's transformation. + """ + + def __init__(self): + # results of transformations + self.data = dict() + # used to track parent nodes + self.node_stack = deque() + + def transform(self, root): + """Perform a transformation on an SPPF.""" + self.node_stack.append('result') + self.data['result'] = [] + self.visit(root) + assert len(self.data['result']) <= 1 + if self.data['result']: + return self.data['result'][0] + + def transform_symbol_node(self, node, data): + """Transform a symbol node.""" + return node + + def transform_intermediate_node(self, node, data): + """Transform an intermediate node.""" + return node + + def transform_packed_node(self, node, data): + """Transform a packed node.""" + return node + + def transform_token_node(self, node): + """Transform a ``Token``.""" + return node + + def visit_symbol_node_in(self, node): + self.node_stack.append(id(node)) + self.data[id(node)] = [] + return node.children + + def visit_packed_node_in(self, node): + self.node_stack.append(id(node)) + self.data[id(node)] = [] + return node.children + + def visit_token_node(self, node): + try: + transformed = self.transform_token_node(node) + except Discard: + pass + else: + self.data[self.node_stack[-1]].append(transformed) + + def visit_symbol_node_out(self, node): + self.node_stack.pop() + try: + transformed = self.transform_symbol_node(node, self.data[id(node)]) + except Discard: + pass + else: + self.data[self.node_stack[-1]].append(transformed) + finally: + del self.data[id(node)] + + def visit_intermediate_node_out(self, node): + self.node_stack.pop() + try: + transformed = self.transform_intermediate_node(node, self.data[id(node)]) + except Discard: + pass + else: + self.data[self.node_stack[-1]].append(transformed) + finally: + del self.data[id(node)] + + def visit_packed_node_out(self, node): + self.node_stack.pop() + try: + transformed = self.transform_packed_node(node, self.data[id(node)]) + except Discard: + pass + else: + self.data[self.node_stack[-1]].append(transformed) + finally: + del self.data[id(node)] + +class ForestSumVisitor(ForestVisitor): + """ + A visitor for prioritizing ambiguous parts of the Forest. + + This visitor is used when support for explicit priorities on + rules is requested (whether normal, or invert). It walks the + forest (or subsets thereof) and cascades properties upwards + from the leaves. + + It would be ideal to do this during parsing, however this would + require processing each Earley item multiple times. That's + a big performance drawback; so running a forest walk is the + lesser of two evils: there can be significantly more Earley + items created during parsing than there are SPPF nodes in the + final tree. + """ + def visit_packed_node_in(self, node): + yield node.left + yield node.right + + def visit_symbol_node_in(self, node): + return iter(node.children) + + def visit_packed_node_out(self, node): + priority = node.rule.options.priority if not node.parent.is_intermediate and node.rule.options.priority else 0 + priority += getattr(node.right, 'priority', 0) + priority += getattr(node.left, 'priority', 0) + node.priority = priority + + def visit_symbol_node_out(self, node): + node.priority = max(child.priority for child in node.children) + +class PackedData(): + """Used in transformationss of packed nodes to distinguish the data + that comes from the left child and the right child. + """ + + def __init__(self, node, data): + self.left = None + self.right = None + if data: + if node.left: + self.left = data[0] + if len(data) > 1 and node.right: + self.right = data[1] + elif node.right: + self.right = data[0] + +class ForestToParseTree(ForestTransformer): + """Used by the earley parser when ambiguity equals 'resolve' or + 'explicit'. Transforms an SPPF into an (ambiguous) parse tree. + + tree_class: The tree class to use for construction + callbacks: A dictionary of rules to functions that output a tree + prioritizer: A ``ForestVisitor`` that manipulates the priorities of + ForestNodes + resolve_ambiguity: If True, ambiguities will be resolved based on + priorities. Otherwise, `_ambig` nodes will be in the resulting + tree. + """ + + def __init__(self, tree_class=Tree, callbacks=dict(), prioritizer=ForestSumVisitor(), resolve_ambiguity=True): + super(ForestToParseTree, self).__init__() + self.tree_class = tree_class + self.callbacks = callbacks + self.prioritizer = prioritizer + self.resolve_ambiguity = resolve_ambiguity + self._on_cycle_retreat = False + + def on_cycle(self, node, path): + logger.warning("Cycle encountered in the SPPF at node: %s. " + "As infinite ambiguities cannot be represented in a tree, " + "this family of derivations will be discarded.", node) + if self.resolve_ambiguity: + # TODO: choose a different path if cycle is encountered + logger.warning("At this time, using ambiguity resolution for SPPFs " + "with cycles may result in None being returned.") + self._on_cycle_retreat = True + + def _check_cycle(self, node): + if self._on_cycle_retreat: + raise Discard() + + def _collapse_ambig(self, children): + new_children = [] + for child in children: + if hasattr(child, 'data') and child.data == '_ambig': + new_children += child.children + else: + new_children.append(child) + return new_children + + def _call_rule_func(self, node, data): + # called when transforming children of symbol nodes + # data is a list of trees or tokens that correspond to the + # symbol's rule expansion + return self.callbacks[node.rule](data) + + def _call_ambig_func(self, node, data): + # called when transforming a symbol node + # data is a list of trees where each tree's data is + # equal to the name of the symbol or one of its aliases. + if len(data) > 1: + return self.tree_class('_ambig', data) + elif data: + return data[0] + raise Discard() + + def transform_symbol_node(self, node, data): + self._check_cycle(node) + data = self._collapse_ambig(data) + return self._call_ambig_func(node, data) + + def transform_intermediate_node(self, node, data): + self._check_cycle(node) + if len(data) > 1: + children = [self.tree_class('_inter', c) for c in data] + return self.tree_class('_iambig', children) + return data[0] + + def transform_packed_node(self, node, data): + self._check_cycle(node) + children = [] + assert len(data) <= 2 + data = PackedData(node, data) + if data.left is not None: + if node.left.is_intermediate and isinstance(data.left, list): + children += data.left + else: + children.append(data.left) + if data.right is not None: + children.append(data.right) + if node.parent.is_intermediate: + return children + return self._call_rule_func(node, children) + + def visit_symbol_node_in(self, node): + self._on_cycle_retreat = False + super(ForestToParseTree, self).visit_symbol_node_in(node) + if self.prioritizer and node.is_ambiguous and isinf(node.priority): + self.prioritizer.visit(node) + if self.resolve_ambiguity: + return node.children[0] + return node.children + + def visit_packed_node_in(self, node): + self._on_cycle_retreat = False + return super(ForestToParseTree, self).visit_packed_node_in(node) + + def visit_token_node(self, node): + self._on_cycle_retreat = False + return super(ForestToParseTree, self).visit_token_node(node) + +def handles_ambiguity(func): + """Decorator for methods of subclasses of ``TreeForestTransformer``. + Denotes that the method should receive a list of transformed derivations.""" + func.handles_ambiguity = True + return func + +class TreeForestTransformer(ForestToParseTree): + """A ``ForestTransformer`` with a tree ``Transformer``-like interface. + By default, it will construct a tree. + + Methods provided via inheritance are called based on the rule/symbol + names of nodes in the forest. + + Methods that act on rules will receive a list of the results of the + transformations of the rule's children. By default, trees and tokens. + + Methods that act on tokens will receive a token. + + Alternatively, methods that act on rules may be annotated with + ``handles_ambiguity``. In this case, the function will receive a list + of all the transformations of all the derivations of the rule. + By default, a list of trees where each tree.data is equal to the + rule name or one of its aliases. + + Non-tree transformations are made possible by override of + ``__default__``, ``__default_token__``, and ``__default_ambig__``. + + .. note:: + + Tree shaping features such as inlined rules and token filtering are + not built into the transformation. Positions are also not + propagated. + + :param tree_class: The tree class to use for construction + :param prioritizer: A ``ForestVisitor`` that manipulates the priorities of + nodes in the SPPF. + :param resolve_ambiguity: If True, ambiguities will be resolved based on + priorities. + """ + + def __init__(self, tree_class=Tree, prioritizer=ForestSumVisitor(), resolve_ambiguity=True): + super(TreeForestTransformer, self).__init__(tree_class, dict(), prioritizer, resolve_ambiguity) + + def __default__(self, name, data): + """Default operation on tree (for override). + + Returns a tree with name with data as children. + """ + return self.tree_class(name, data) + + def __default_ambig__(self, name, data): + """Default operation on ambiguous rule (for override). + + Wraps data in an '_ambig_' node if it contains more than + one element. + """ + if len(data) > 1: + return self.tree_class('_ambig', data) + elif data: + return data[0] + raise Discard() + + def __default_token__(self, node): + """Default operation on ``Token`` (for override). + + Returns ``node``. + """ + return node + + def transform_token_node(self, node): + return getattr(self, node.type, self.__default_token__)(node) + + def _call_rule_func(self, node, data): + name = node.rule.alias or node.rule.options.template_source or node.rule.origin.name + user_func = getattr(self, name, self.__default__) + if user_func == self.__default__ or hasattr(user_func, 'handles_ambiguity'): + user_func = partial(self.__default__, name) + if not self.resolve_ambiguity: + wrapper = partial(AmbiguousIntermediateExpander, self.tree_class) + user_func = wrapper(user_func) + return user_func(data) + + def _call_ambig_func(self, node, data): + name = node.s.name + user_func = getattr(self, name, self.__default_ambig__) + if user_func == self.__default_ambig__ or not hasattr(user_func, 'handles_ambiguity'): + user_func = partial(self.__default_ambig__, name) + return user_func(data) + +class ForestToPyDotVisitor(ForestVisitor): + """ + A Forest visitor which writes the SPPF to a PNG. + + The SPPF can get really large, really quickly because + of the amount of meta-data it stores, so this is probably + only useful for trivial trees and learning how the SPPF + is structured. + """ + def __init__(self, rankdir="TB"): + self.pydot = import_module('pydot') + self.graph = self.pydot.Dot(graph_type='digraph', rankdir=rankdir) + + def visit(self, root, filename): + super(ForestToPyDotVisitor, self).visit(root) + self.graph.write_png(filename) + + def visit_token_node(self, node): + graph_node_id = str(id(node)) + graph_node_label = "\"{}\"".format(node.value.replace('"', '\\"')) + graph_node_color = 0x808080 + graph_node_style = "\"filled,rounded\"" + graph_node_shape = "diamond" + graph_node = self.pydot.Node(graph_node_id, style=graph_node_style, fillcolor="#{:06x}".format(graph_node_color), shape=graph_node_shape, label=graph_node_label) + self.graph.add_node(graph_node) + + def visit_packed_node_in(self, node): + graph_node_id = str(id(node)) + graph_node_label = repr(node) + graph_node_color = 0x808080 + graph_node_style = "filled" + graph_node_shape = "diamond" + graph_node = self.pydot.Node(graph_node_id, style=graph_node_style, fillcolor="#{:06x}".format(graph_node_color), shape=graph_node_shape, label=graph_node_label) + self.graph.add_node(graph_node) + yield node.left + yield node.right + + def visit_packed_node_out(self, node): + graph_node_id = str(id(node)) + graph_node = self.graph.get_node(graph_node_id)[0] + for child in [node.left, node.right]: + if child is not None: + child_graph_node_id = str(id(child)) + child_graph_node = self.graph.get_node(child_graph_node_id)[0] + self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node)) + else: + #### Try and be above the Python object ID range; probably impl. specific, but maybe this is okay. + child_graph_node_id = str(randint(100000000000000000000000000000,123456789012345678901234567890)) + child_graph_node_style = "invis" + child_graph_node = self.pydot.Node(child_graph_node_id, style=child_graph_node_style, label="None") + child_edge_style = "invis" + self.graph.add_node(child_graph_node) + self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node, style=child_edge_style)) + + def visit_symbol_node_in(self, node): + graph_node_id = str(id(node)) + graph_node_label = repr(node) + graph_node_color = 0x808080 + graph_node_style = "\"filled\"" + if node.is_intermediate: + graph_node_shape = "ellipse" + else: + graph_node_shape = "rectangle" + graph_node = self.pydot.Node(graph_node_id, style=graph_node_style, fillcolor="#{:06x}".format(graph_node_color), shape=graph_node_shape, label=graph_node_label) + self.graph.add_node(graph_node) + return iter(node.children) + + def visit_symbol_node_out(self, node): + graph_node_id = str(id(node)) + graph_node = self.graph.get_node(graph_node_id)[0] + for child in node.children: + child_graph_node_id = str(id(child)) + child_graph_node = self.graph.get_node(child_graph_node_id)[0] + self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node)) diff --git a/testbed/lark-parser__lark/lark/parsers/grammar_analysis.py b/testbed/lark-parser__lark/lark/parsers/grammar_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..737cb02afa07b802d42822e1c665fd45ea4ca651 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/grammar_analysis.py @@ -0,0 +1,185 @@ +from collections import Counter, defaultdict + +from ..utils import bfs, fzset, classify +from ..exceptions import GrammarError +from ..grammar import Rule, Terminal, NonTerminal + + +class RulePtr(object): + __slots__ = ('rule', 'index') + + def __init__(self, rule, index): + assert isinstance(rule, Rule) + assert index <= len(rule.expansion) + self.rule = rule + self.index = index + + def __repr__(self): + before = [x.name for x in self.rule.expansion[:self.index]] + after = [x.name for x in self.rule.expansion[self.index:]] + return '<%s : %s * %s>' % (self.rule.origin.name, ' '.join(before), ' '.join(after)) + + @property + def next(self): + return self.rule.expansion[self.index] + + def advance(self, sym): + assert self.next == sym + return RulePtr(self.rule, self.index+1) + + @property + def is_satisfied(self): + return self.index == len(self.rule.expansion) + + def __eq__(self, other): + return self.rule == other.rule and self.index == other.index + def __hash__(self): + return hash((self.rule, self.index)) + + +# state generation ensures no duplicate LR0ItemSets +class LR0ItemSet(object): + __slots__ = ('kernel', 'closure', 'transitions', 'lookaheads') + + def __init__(self, kernel, closure): + self.kernel = fzset(kernel) + self.closure = fzset(closure) + self.transitions = {} + self.lookaheads = defaultdict(set) + + def __repr__(self): + return '{%s | %s}' % (', '.join([repr(r) for r in self.kernel]), ', '.join([repr(r) for r in self.closure])) + + +def update_set(set1, set2): + if not set2 or set1 > set2: + return False + + copy = set(set1) + set1 |= set2 + return set1 != copy + +def calculate_sets(rules): + """Calculate FOLLOW sets. + + Adapted from: http://lara.epfl.ch/w/cc09:algorithm_for_first_and_follow_sets""" + symbols = {sym for rule in rules for sym in rule.expansion} | {rule.origin for rule in rules} + + # foreach grammar rule X ::= Y(1) ... Y(k) + # if k=0 or {Y(1),...,Y(k)} subset of NULLABLE then + # NULLABLE = NULLABLE union {X} + # for i = 1 to k + # if i=1 or {Y(1),...,Y(i-1)} subset of NULLABLE then + # FIRST(X) = FIRST(X) union FIRST(Y(i)) + # for j = i+1 to k + # if i=k or {Y(i+1),...Y(k)} subset of NULLABLE then + # FOLLOW(Y(i)) = FOLLOW(Y(i)) union FOLLOW(X) + # if i+1=j or {Y(i+1),...,Y(j-1)} subset of NULLABLE then + # FOLLOW(Y(i)) = FOLLOW(Y(i)) union FIRST(Y(j)) + # until none of NULLABLE,FIRST,FOLLOW changed in last iteration + + NULLABLE = set() + FIRST = {} + FOLLOW = {} + for sym in symbols: + FIRST[sym]={sym} if sym.is_term else set() + FOLLOW[sym]=set() + + # Calculate NULLABLE and FIRST + changed = True + while changed: + changed = False + + for rule in rules: + if set(rule.expansion) <= NULLABLE: + if update_set(NULLABLE, {rule.origin}): + changed = True + + for i, sym in enumerate(rule.expansion): + if set(rule.expansion[:i]) <= NULLABLE: + if update_set(FIRST[rule.origin], FIRST[sym]): + changed = True + else: + break + + # Calculate FOLLOW + changed = True + while changed: + changed = False + + for rule in rules: + for i, sym in enumerate(rule.expansion): + if i==len(rule.expansion)-1 or set(rule.expansion[i+1:]) <= NULLABLE: + if update_set(FOLLOW[sym], FOLLOW[rule.origin]): + changed = True + + for j in range(i+1, len(rule.expansion)): + if set(rule.expansion[i+1:j]) <= NULLABLE: + if update_set(FOLLOW[sym], FIRST[rule.expansion[j]]): + changed = True + + return FIRST, FOLLOW, NULLABLE + + +class GrammarAnalyzer(object): + def __init__(self, parser_conf, debug=False): + self.debug = debug + + root_rules = {start: Rule(NonTerminal('$root_' + start), [NonTerminal(start), Terminal('$END')]) + for start in parser_conf.start} + + rules = parser_conf.rules + list(root_rules.values()) + self.rules_by_origin = classify(rules, lambda r: r.origin) + + if len(rules) != len(set(rules)): + duplicates = [item for item, count in Counter(rules).items() if count > 1] + raise GrammarError("Rules defined twice: %s" % ', '.join(str(i) for i in duplicates)) + + for r in rules: + for sym in r.expansion: + if not (sym.is_term or sym in self.rules_by_origin): + raise GrammarError("Using an undefined rule: %s" % sym) + + self.start_states = {start: self.expand_rule(root_rule.origin) + for start, root_rule in root_rules.items()} + + self.end_states = {start: fzset({RulePtr(root_rule, len(root_rule.expansion))}) + for start, root_rule in root_rules.items()} + + lr0_root_rules = {start: Rule(NonTerminal('$root_' + start), [NonTerminal(start)]) + for start in parser_conf.start} + + lr0_rules = parser_conf.rules + list(lr0_root_rules.values()) + assert(len(lr0_rules) == len(set(lr0_rules))) + + self.lr0_rules_by_origin = classify(lr0_rules, lambda r: r.origin) + + # cache RulePtr(r, 0) in r (no duplicate RulePtr objects) + self.lr0_start_states = {start: LR0ItemSet([RulePtr(root_rule, 0)], self.expand_rule(root_rule.origin, self.lr0_rules_by_origin)) + for start, root_rule in lr0_root_rules.items()} + + self.FIRST, self.FOLLOW, self.NULLABLE = calculate_sets(rules) + + def expand_rule(self, source_rule, rules_by_origin=None): + "Returns all init_ptrs accessible by rule (recursive)" + + if rules_by_origin is None: + rules_by_origin = self.rules_by_origin + + init_ptrs = set() + def _expand_rule(rule): + assert not rule.is_term, rule + + for r in rules_by_origin[rule]: + init_ptr = RulePtr(r, 0) + init_ptrs.add(init_ptr) + + if r.expansion: # if not empty rule + new_r = init_ptr.next + if not new_r.is_term: + yield new_r + + for _ in bfs([source_rule], _expand_rule): + pass + + return fzset(init_ptrs) diff --git a/testbed/lark-parser__lark/lark/parsers/lalr_analysis.py b/testbed/lark-parser__lark/lark/parsers/lalr_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..8745f46ed120da89e5f82220bdbde3482db9b888 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/lalr_analysis.py @@ -0,0 +1,294 @@ +"""This module builds a LALR(1) transition-table for lalr_parser.py + +For now, shift/reduce conflicts are automatically resolved as shifts. +""" + +# Author: Erez Shinan (2017) +# Email : erezshin@gmail.com + +from collections import defaultdict + +from ..utils import classify, classify_bool, bfs, fzset, Enumerator, logger +from ..exceptions import GrammarError + +from .grammar_analysis import GrammarAnalyzer, Terminal, LR0ItemSet +from ..grammar import Rule + +###{standalone + +class Action: + def __init__(self, name): + self.name = name + def __str__(self): + return self.name + def __repr__(self): + return str(self) + +Shift = Action('Shift') +Reduce = Action('Reduce') + + +class ParseTable: + def __init__(self, states, start_states, end_states): + self.states = states + self.start_states = start_states + self.end_states = end_states + + def serialize(self, memo): + tokens = Enumerator() + rules = Enumerator() + + states = { + state: {tokens.get(token): ((1, arg.serialize(memo)) if action is Reduce else (0, arg)) + for token, (action, arg) in actions.items()} + for state, actions in self.states.items() + } + + return { + 'tokens': tokens.reversed(), + 'states': states, + 'start_states': self.start_states, + 'end_states': self.end_states, + } + + @classmethod + def deserialize(cls, data, memo): + tokens = data['tokens'] + states = { + state: {tokens[token]: ((Reduce, Rule.deserialize(arg, memo)) if action==1 else (Shift, arg)) + for token, (action, arg) in actions.items()} + for state, actions in data['states'].items() + } + return cls(states, data['start_states'], data['end_states']) + + +class IntParseTable(ParseTable): + + @classmethod + def from_ParseTable(cls, parse_table): + enum = list(parse_table.states) + state_to_idx = {s:i for i,s in enumerate(enum)} + int_states = {} + + for s, la in parse_table.states.items(): + la = {k:(v[0], state_to_idx[v[1]]) if v[0] is Shift else v + for k,v in la.items()} + int_states[ state_to_idx[s] ] = la + + + start_states = {start:state_to_idx[s] for start, s in parse_table.start_states.items()} + end_states = {start:state_to_idx[s] for start, s in parse_table.end_states.items()} + return cls(int_states, start_states, end_states) + +###} + + +# digraph and traverse, see The Theory and Practice of Compiler Writing + +# computes F(x) = G(x) union (union { G(y) | x R y }) +# X: nodes +# R: relation (function mapping node -> list of nodes that satisfy the relation) +# G: set valued function +def digraph(X, R, G): + F = {} + S = [] + N = {} + for x in X: + N[x] = 0 + for x in X: + # this is always true for the first iteration, but N[x] may be updated in traverse below + if N[x] == 0: + traverse(x, S, N, X, R, G, F) + return F + +# x: single node +# S: stack +# N: weights +# X: nodes +# R: relation (see above) +# G: set valued function +# F: set valued function we are computing (map of input -> output) +def traverse(x, S, N, X, R, G, F): + S.append(x) + d = len(S) + N[x] = d + F[x] = G[x] + for y in R[x]: + if N[y] == 0: + traverse(y, S, N, X, R, G, F) + n_x = N[x] + assert(n_x > 0) + n_y = N[y] + assert(n_y != 0) + if (n_y > 0) and (n_y < n_x): + N[x] = n_y + F[x].update(F[y]) + if N[x] == d: + f_x = F[x] + while True: + z = S.pop() + N[z] = -1 + F[z] = f_x + if z == x: + break + + +class LALR_Analyzer(GrammarAnalyzer): + def __init__(self, parser_conf, debug=False): + GrammarAnalyzer.__init__(self, parser_conf, debug) + self.nonterminal_transitions = [] + self.directly_reads = defaultdict(set) + self.reads = defaultdict(set) + self.includes = defaultdict(set) + self.lookback = defaultdict(set) + + + def compute_lr0_states(self): + self.lr0_states = set() + # map of kernels to LR0ItemSets + cache = {} + + def step(state): + _, unsat = classify_bool(state.closure, lambda rp: rp.is_satisfied) + + d = classify(unsat, lambda rp: rp.next) + for sym, rps in d.items(): + kernel = fzset({rp.advance(sym) for rp in rps}) + new_state = cache.get(kernel, None) + if new_state is None: + closure = set(kernel) + for rp in kernel: + if not rp.is_satisfied and not rp.next.is_term: + closure |= self.expand_rule(rp.next, self.lr0_rules_by_origin) + new_state = LR0ItemSet(kernel, closure) + cache[kernel] = new_state + + state.transitions[sym] = new_state + yield new_state + + self.lr0_states.add(state) + + for _ in bfs(self.lr0_start_states.values(), step): + pass + + def compute_reads_relations(self): + # handle start state + for root in self.lr0_start_states.values(): + assert(len(root.kernel) == 1) + for rp in root.kernel: + assert(rp.index == 0) + self.directly_reads[(root, rp.next)] = set([ Terminal('$END') ]) + + for state in self.lr0_states: + seen = set() + for rp in state.closure: + if rp.is_satisfied: + continue + s = rp.next + # if s is a not a nonterminal + if s not in self.lr0_rules_by_origin: + continue + if s in seen: + continue + seen.add(s) + nt = (state, s) + self.nonterminal_transitions.append(nt) + dr = self.directly_reads[nt] + r = self.reads[nt] + next_state = state.transitions[s] + for rp2 in next_state.closure: + if rp2.is_satisfied: + continue + s2 = rp2.next + # if s2 is a terminal + if s2 not in self.lr0_rules_by_origin: + dr.add(s2) + if s2 in self.NULLABLE: + r.add((next_state, s2)) + + def compute_includes_lookback(self): + for nt in self.nonterminal_transitions: + state, nonterminal = nt + includes = [] + lookback = self.lookback[nt] + for rp in state.closure: + if rp.rule.origin != nonterminal: + continue + # traverse the states for rp(.rule) + state2 = state + for i in range(rp.index, len(rp.rule.expansion)): + s = rp.rule.expansion[i] + nt2 = (state2, s) + state2 = state2.transitions[s] + if nt2 not in self.reads: + continue + for j in range(i + 1, len(rp.rule.expansion)): + if not rp.rule.expansion[j] in self.NULLABLE: + break + else: + includes.append(nt2) + # state2 is at the final state for rp.rule + if rp.index == 0: + for rp2 in state2.closure: + if (rp2.rule == rp.rule) and rp2.is_satisfied: + lookback.add((state2, rp2.rule)) + for nt2 in includes: + self.includes[nt2].add(nt) + + def compute_lookaheads(self): + read_sets = digraph(self.nonterminal_transitions, self.reads, self.directly_reads) + follow_sets = digraph(self.nonterminal_transitions, self.includes, read_sets) + + for nt, lookbacks in self.lookback.items(): + for state, rule in lookbacks: + for s in follow_sets[nt]: + state.lookaheads[s].add(rule) + + def compute_lalr1_states(self): + m = {} + reduce_reduce = [] + for state in self.lr0_states: + actions = {} + for la, next_state in state.transitions.items(): + actions[la] = (Shift, next_state.closure) + for la, rules in state.lookaheads.items(): + if len(rules) > 1: + reduce_reduce.append((la, rules)) + if la in actions: + if self.debug: + logger.warning('Shift/Reduce conflict for terminal %s: (resolving as shift)', la.name) + logger.warning(' * %s', list(rules)[0]) + else: + actions[la] = (Reduce, list(rules)[0]) + m[state] = { k.name: v for k, v in actions.items() } + + if reduce_reduce: + msgs = [ 'Reduce/Reduce collision in %s between the following rules: %s' + % (la, ''.join([ '\n\t\t- ' + str(r) for r in rules ])) + for la, rules in reduce_reduce] + raise GrammarError('\n\n'.join(msgs)) + + states = { k.closure: v for k, v in m.items() } + + # compute end states + end_states = {} + for state in states: + for rp in state: + for start in self.lr0_start_states: + if rp.rule.origin.name == ('$root_' + start) and rp.is_satisfied: + assert(not start in end_states) + end_states[start] = state + + _parse_table = ParseTable(states, { start: state.closure for start, state in self.lr0_start_states.items() }, end_states) + + if self.debug: + self.parse_table = _parse_table + else: + self.parse_table = IntParseTable.from_ParseTable(_parse_table) + + def compute_lalr(self): + self.compute_lr0_states() + self.compute_reads_relations() + self.compute_includes_lookback() + self.compute_lookaheads() + self.compute_lalr1_states() \ No newline at end of file diff --git a/testbed/lark-parser__lark/lark/parsers/lalr_parser.py b/testbed/lark-parser__lark/lark/parsers/lalr_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..433f3ef76ef89e6b35785611426769ef50154cc8 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/lalr_parser.py @@ -0,0 +1,119 @@ +"""This module implements a LALR(1) Parser +""" +# Author: Erez Shinan (2017) +# Email : erezshin@gmail.com +from ..exceptions import UnexpectedToken +from ..lexer import Token +from ..utils import Enumerator, Serialize + +from .lalr_analysis import LALR_Analyzer, Shift, Reduce, IntParseTable +from .lalr_puppet import ParserPuppet + +###{standalone + +class LALR_Parser(object): + def __init__(self, parser_conf, debug=False): + assert all(r.options.priority is None for r in parser_conf.rules), "LALR doesn't yet support prioritization" + analysis = LALR_Analyzer(parser_conf, debug=debug) + analysis.compute_lalr() + callbacks = parser_conf.callbacks + + self._parse_table = analysis.parse_table + self.parser_conf = parser_conf + self.parser = _Parser(analysis.parse_table, callbacks, debug) + + @classmethod + def deserialize(cls, data, memo, callbacks, debug=False): + inst = cls.__new__(cls) + inst._parse_table = IntParseTable.deserialize(data, memo) + inst.parser = _Parser(inst._parse_table, callbacks, debug) + return inst + + def serialize(self, memo): + return self._parse_table.serialize(memo) + + def parse(self, *args): + return self.parser.parse(*args) + + +class _Parser: + def __init__(self, parse_table, callbacks, debug=False): + self.parse_table = parse_table + self.callbacks = callbacks + self.debug = debug + + def parse(self, seq, start, set_state=None, value_stack=None, state_stack=None): + token = None + stream = iter(seq) + states = self.parse_table.states + start_state = self.parse_table.start_states[start] + end_state = self.parse_table.end_states[start] + + state_stack = state_stack or [start_state] + value_stack = value_stack or [] + + if set_state: set_state(start_state) + + def get_action(token): + state = state_stack[-1] + try: + return states[state][token.type] + except KeyError: + expected = {s for s in states[state].keys() if s.isupper()} + try: + puppet = ParserPuppet(self, state_stack, value_stack, start, stream, set_state) + except NameError: # For standalone parser + puppet = None + raise UnexpectedToken(token, expected, state=state, puppet=puppet) + + def reduce(rule): + size = len(rule.expansion) + if size: + s = value_stack[-size:] + del state_stack[-size:] + del value_stack[-size:] + else: + s = [] + + value = self.callbacks[rule](s) + + _action, new_state = states[state_stack[-1]][rule.origin.name] + assert _action is Shift + state_stack.append(new_state) + value_stack.append(value) + + # Main LALR-parser loop + try: + for token in stream: + while True: + action, arg = get_action(token) + assert arg != end_state + + if action is Shift: + state_stack.append(arg) + value_stack.append(token) + if set_state: set_state(arg) + break # next token + else: + reduce(arg) + except Exception as e: + if self.debug: + print("") + print("STATE STACK DUMP") + print("----------------") + for i, s in enumerate(state_stack): + print('%d)' % i , s) + print("") + + raise + + token = Token.new_borrow_pos('$END', '', token) if token else Token('$END', '', 0, 1, 1) + while True: + _action, arg = get_action(token) + assert(_action is Reduce) + reduce(arg) + if state_stack[-1] == end_state: + return value_stack[-1] + +###} + diff --git a/testbed/lark-parser__lark/lark/parsers/lalr_puppet.py b/testbed/lark-parser__lark/lark/parsers/lalr_puppet.py new file mode 100644 index 0000000000000000000000000000000000000000..e006c1756387810979a00dec9f13470cd818cd2b --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/lalr_puppet.py @@ -0,0 +1,134 @@ +# This module provide a LALR puppet, which is used to debugging and error handling + +from copy import deepcopy + +from .lalr_analysis import Shift, Reduce +from .. import Token +from ..exceptions import ParseError + + +class ParserPuppet(object): + """ParserPuppet gives you advanced control over error handling when parsing with LALR. + + For a simpler, more streamlined interface, see the ``on_error`` argument to ``Lark.parse()``. + """ + def __init__(self, parser, state_stack, value_stack, start, stream, set_state): + self.parser = parser + self._state_stack = state_stack + self._value_stack = value_stack + self._start = start + self._stream = stream + self._set_state = set_state + + self.result = None + + def feed_token(self, token): + """Feed the parser with a token, and advance it to the next state, as if it recieved it from the lexer. + + Note that ``token`` has to be an instance of ``Token``. + """ + end_state = self.parser.parse_table.end_states[self._start] + state_stack = self._state_stack + value_stack = self._value_stack + + state = state_stack[-1] + action, arg = self.parser.parse_table.states[state][token.type] + if arg == end_state: + raise ParseError(arg) + + while action is Reduce: + rule = arg + size = len(rule.expansion) + if size: + s = value_stack[-size:] + del state_stack[-size:] + del value_stack[-size:] + else: + s = [] + + value = self.parser.callbacks[rule](s) + + _action, new_state = self.parser.parse_table.states[state_stack[-1]][rule.origin.name] + assert _action is Shift + state_stack.append(new_state) + value_stack.append(value) + + if state_stack[-1] == end_state: + self.result = value_stack[-1] + return self.result + + state = state_stack[-1] + try: + action, arg = self.parser.parse_table.states[state][token.type] + except KeyError as e: + raise ParseError(e) + assert arg != end_state + + assert action is Shift + state_stack.append(arg) + value_stack.append(token) + + def copy(self): + """Create a new puppet with a separate state. + + Calls to feed_token() won't affect the old puppet, and vice-versa. + """ + return type(self)( + self.parser, + list(self._state_stack), + deepcopy(self._value_stack), + self._start, + self._stream, + self._set_state, + ) + + def __eq__(self, other): + if not isinstance(other, ParserPuppet): + return False + + return ( + self._state_stack == other._state_stack and + self._value_stack == other._value_stack and + self._stream == other._stream and + self._start == other._start + ) + + def __hash__(self): + return hash((tuple(self._state_stack), self._start)) + + def pretty(self): + """Print the output of ``choices()`` in a way that's easier to read.""" + out = ["Puppet choices:"] + for k, v in self.choices().items(): + out.append('\t- %s -> %s' % (k, v)) + out.append('stack size: %s' % len(self._state_stack)) + return '\n'.join(out) + + def choices(self): + """Returns a dictionary of token types, matched to their action in the parser. + + Only returns token types that are accepted by the current state. + + Updated by ``feed_token()``. + """ + return self.parser.parse_table.states[self._state_stack[-1]] + + def accepts(self): + accepts = set() + for t in self.choices(): + if t.isupper(): # is terminal? + new_puppet = self.copy() + try: + new_puppet.feed_token(Token(t, '')) + except ParseError: + pass + else: + accepts.add(t) + return accepts + + def resume_parse(self): + """Resume parsing from the current puppet state.""" + return self.parser.parse( + self._stream, self._start, self._set_state, + self._value_stack, self._state_stack + ) diff --git a/testbed/lark-parser__lark/lark/parsers/xearley.py b/testbed/lark-parser__lark/lark/parsers/xearley.py new file mode 100644 index 0000000000000000000000000000000000000000..256fc2c477ff4ea973e4df8e2dc566fc3c7ca626 --- /dev/null +++ b/testbed/lark-parser__lark/lark/parsers/xearley.py @@ -0,0 +1,152 @@ +"""This module implements an experimental Earley parser with a dynamic lexer + +The core Earley algorithm used here is based on Elizabeth Scott's implementation, here: + https://www.sciencedirect.com/science/article/pii/S1571066108001497 + +That is probably the best reference for understanding the algorithm here. + +The Earley parser outputs an SPPF-tree as per that document. The SPPF tree format +is better documented here: + http://www.bramvandersanden.com/post/2014/06/shared-packed-parse-forest/ + +Instead of running a lexer beforehand, or using a costy char-by-char method, this parser +uses regular expressions by necessity, achieving high-performance while maintaining all of +Earley's power in parsing any CFG. +""" + +from collections import defaultdict + +from ..tree import Tree +from ..exceptions import UnexpectedCharacters +from ..lexer import Token +from ..grammar import Terminal +from .earley import Parser as BaseParser +from .earley_forest import SymbolNode + + +class Parser(BaseParser): + def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, ignore = (), complete_lex = False, debug=False, tree_class=Tree): + BaseParser.__init__(self, parser_conf, term_matcher, resolve_ambiguity, debug, tree_class) + self.ignore = [Terminal(t) for t in ignore] + self.complete_lex = complete_lex + + def _parse(self, stream, columns, to_scan, start_symbol=None): + + def scan(i, to_scan): + """The core Earley Scanner. + + This is a custom implementation of the scanner that uses the + Lark lexer to match tokens. The scan list is built by the + Earley predictor, based on the previously completed tokens. + This ensures that at each phase of the parse we have a custom + lexer context, allowing for more complex ambiguities.""" + + node_cache = {} + + # 1) Loop the expectations and ask the lexer to match. + # Since regexp is forward looking on the input stream, and we only + # want to process tokens when we hit the point in the stream at which + # they complete, we push all tokens into a buffer (delayed_matches), to + # be held possibly for a later parse step when we reach the point in the + # input stream at which they complete. + for item in set(to_scan): + m = match(item.expect, stream, i) + if m: + t = Token(item.expect.name, m.group(0), i, text_line, text_column) + delayed_matches[m.end()].append( (item, i, t) ) + + if self.complete_lex: + s = m.group(0) + for j in range(1, len(s)): + m = match(item.expect, s[:-j]) + if m: + t = Token(item.expect.name, m.group(0), i, text_line, text_column) + delayed_matches[i+m.end()].append( (item, i, t) ) + + # Remove any items that successfully matched in this pass from the to_scan buffer. + # This ensures we don't carry over tokens that already matched, if we're ignoring below. + to_scan.remove(item) + + # 3) Process any ignores. This is typically used for e.g. whitespace. + # We carry over any unmatched items from the to_scan buffer to be matched again after + # the ignore. This should allow us to use ignored symbols in non-terminals to implement + # e.g. mandatory spacing. + for x in self.ignore: + m = match(x, stream, i) + if m: + # Carry over any items still in the scan buffer, to past the end of the ignored items. + delayed_matches[m.end()].extend([(item, i, None) for item in to_scan ]) + + # If we're ignoring up to the end of the file, # carry over the start symbol if it already completed. + delayed_matches[m.end()].extend([(item, i, None) for item in columns[i] if item.is_complete and item.s == start_symbol]) + + next_to_scan = set() + next_set = set() + columns.append(next_set) + transitives.append({}) + + ## 4) Process Tokens from delayed_matches. + # This is the core of the Earley scanner. Create an SPPF node for each Token, + # and create the symbol node in the SPPF tree. Advance the item that completed, + # and add the resulting new item to either the Earley set (for processing by the + # completer/predictor) or the to_scan buffer for the next parse step. + for item, start, token in delayed_matches[i+1]: + if token is not None: + token.end_line = text_line + token.end_column = text_column + 1 + token.end_pos = i + 1 + + new_item = item.advance() + label = (new_item.s, new_item.start, i) + new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label)) + new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token) + else: + new_item = item + + if new_item.expect in self.TERMINALS: + # add (B ::= Aai+1.B, h, y) to Q' + next_to_scan.add(new_item) + else: + # add (B ::= Aa+1.B, h, y) to Ei+1 + next_set.add(new_item) + + del delayed_matches[i+1] # No longer needed, so unburden memory + + if not next_set and not delayed_matches and not next_to_scan: + raise UnexpectedCharacters(stream, i, text_line, text_column, {item.expect.name for item in to_scan}, set(to_scan)) + + return next_to_scan + + + delayed_matches = defaultdict(list) + match = self.term_matcher + + # Cache for nodes & tokens created in a particular parse step. + transitives = [{}] + + text_line = 1 + text_column = 1 + + ## The main Earley loop. + # Run the Prediction/Completion cycle for any Items in the current Earley set. + # Completions will be added to the SPPF tree, and predictions will be recursively + # processed down to terminals/empty nodes to be added to the scanner for the next + # step. + i = 0 + for token in stream: + self.predict_and_complete(i, to_scan, columns, transitives) + + to_scan = scan(i, to_scan) + + if token == '\n': + text_line += 1 + text_column = 1 + else: + text_column += 1 + i += 1 + + self.predict_and_complete(i, to_scan, columns, transitives) + + ## Column is now the final column in the parse. + assert i == len(columns)-1 + return to_scan diff --git a/testbed/lark-parser__lark/lark/reconstruct.py b/testbed/lark-parser__lark/lark/reconstruct.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cff3195f8099eaf0885ebce71d6ca7f4bdd098 --- /dev/null +++ b/testbed/lark-parser__lark/lark/reconstruct.py @@ -0,0 +1,104 @@ +"""Reconstruct text from a tree, based on Lark grammar""" + +import unicodedata + +from .tree import Tree +from .visitors import Transformer_InPlace +from .lexer import Token, PatternStr +from .grammar import Terminal, NonTerminal + +from .tree_matcher import TreeMatcher, is_discarded_terminal + +def is_iter_empty(i): + try: + _ = next(i) + return False + except StopIteration: + return True + + +class WriteTokensTransformer(Transformer_InPlace): + "Inserts discarded tokens into their correct place, according to the rules of grammar" + + def __init__(self, tokens, term_subs): + self.tokens = tokens + self.term_subs = term_subs + + def __default__(self, data, children, meta): + if not getattr(meta, 'match_tree', False): + return Tree(data, children) + + iter_args = iter(children) + to_write = [] + for sym in meta.orig_expansion: + if is_discarded_terminal(sym): + try: + v = self.term_subs[sym.name](sym) + except KeyError: + t = self.tokens[sym.name] + if not isinstance(t.pattern, PatternStr): + raise NotImplementedError("Reconstructing regexps not supported yet: %s" % t) + + v = t.pattern.value + to_write.append(v) + else: + x = next(iter_args) + if isinstance(x, list): + to_write += x + else: + if isinstance(x, Token): + assert Terminal(x.type) == sym, x + else: + assert NonTerminal(x.data) == sym, (sym, x) + to_write.append(x) + + assert is_iter_empty(iter_args) + return to_write + + +def _isalnum(x): + # Categories defined here: https://www.python.org/dev/peps/pep-3131/ + return unicodedata.category(x) in ['Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Mn', 'Mc', 'Nd', 'Pc'] + +class Reconstructor(TreeMatcher): + """ + A Reconstructor that will, given a full parse Tree, generate source code. + + Note: + The reconstructor cannot generate values from regexps. If you need to produce discarded + regexes, such as newlines, use `term_subs` and provide default values for them. + + Paramters: + parser: a Lark instance + term_subs: a dictionary of [Terminal name as str] to [output text as str] + """ + + def __init__(self, parser, term_subs=None): + TreeMatcher.__init__(self, parser) + + self.write_tokens = WriteTokensTransformer({t.name:t for t in self.tokens}, term_subs or {}) + + def _reconstruct(self, tree): + unreduced_tree = self.match_tree(tree, tree.data) + + res = self.write_tokens.transform(unreduced_tree) + for item in res: + if isinstance(item, Tree): + # TODO use orig_expansion.rulename to support templates + for x in self._reconstruct(item): + yield x + else: + yield item + + def reconstruct(self, tree, postproc=None): + x = self._reconstruct(tree) + if postproc: + x = postproc(x) + y = [] + prev_item = '' + for item in x: + if prev_item and item and _isalnum(prev_item[-1]) and _isalnum(item[0]): + y.append(' ') + y.append(item) + prev_item = item + return ''.join(y) diff --git a/testbed/lark-parser__lark/lark/tools/__init__.py b/testbed/lark-parser__lark/lark/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/lark-parser__lark/lark/tools/nearley.py b/testbed/lark-parser__lark/lark/tools/nearley.py new file mode 100644 index 0000000000000000000000000000000000000000..af2789e964f57d5429e8a6c953b5c0735a0a6543 --- /dev/null +++ b/testbed/lark-parser__lark/lark/tools/nearley.py @@ -0,0 +1,196 @@ +"Converts Nearley grammars to Lark" + +import os.path +import sys +import codecs +import argparse + + +from lark import Lark, InlineTransformer + +nearley_grammar = r""" + start: (ruledef|directive)+ + + directive: "@" NAME (STRING|NAME) + | "@" JS -> js_code + ruledef: NAME "->" expansions + | NAME REGEXP "->" expansions -> macro + expansions: expansion ("|" expansion)* + + expansion: expr+ js + + ?expr: item (":" /[+*?]/)? + + ?item: rule|string|regexp|null + | "(" expansions ")" + + rule: NAME + string: STRING + regexp: REGEXP + null: "null" + JS: /{%.*?%}/s + js: JS? + + NAME: /[a-zA-Z_$]\w*/ + COMMENT: /#[^\n]*/ + REGEXP: /\[.*?\]/ + + %import common.ESCAPED_STRING -> STRING + %import common.WS + %ignore WS + %ignore COMMENT + + """ + +nearley_grammar_parser = Lark(nearley_grammar, parser='earley', lexer='standard') + +def _get_rulename(name): + name = {'_': '_ws_maybe', '__':'_ws'}.get(name, name) + return 'n_' + name.replace('$', '__DOLLAR__').lower() + +class NearleyToLark(InlineTransformer): + def __init__(self): + self._count = 0 + self.extra_rules = {} + self.extra_rules_rev = {} + self.alias_js_code = {} + + def _new_function(self, code): + name = 'alias_%d' % self._count + self._count += 1 + + self.alias_js_code[name] = code + return name + + def _extra_rule(self, rule): + if rule in self.extra_rules_rev: + return self.extra_rules_rev[rule] + + name = 'xrule_%d' % len(self.extra_rules) + assert name not in self.extra_rules + self.extra_rules[name] = rule + self.extra_rules_rev[rule] = name + return name + + def rule(self, name): + return _get_rulename(name) + + def ruledef(self, name, exps): + return '!%s: %s' % (_get_rulename(name), exps) + + def expr(self, item, op): + rule = '(%s)%s' % (item, op) + return self._extra_rule(rule) + + def regexp(self, r): + return '/%s/' % r + + def null(self): + return '' + + def string(self, s): + return self._extra_rule(s) + + def expansion(self, *x): + x, js = x[:-1], x[-1] + if js.children: + js_code ,= js.children + js_code = js_code[2:-2] + alias = '-> ' + self._new_function(js_code) + else: + alias = '' + return ' '.join(x) + alias + + def expansions(self, *x): + return '%s' % ('\n |'.join(x)) + + def start(self, *rules): + return '\n'.join(filter(None, rules)) + +def _nearley_to_lark(g, builtin_path, n2l, js_code, folder_path, includes): + rule_defs = [] + + tree = nearley_grammar_parser.parse(g) + for statement in tree.children: + if statement.data == 'directive': + directive, arg = statement.children + if directive in ('builtin', 'include'): + folder = builtin_path if directive == 'builtin' else folder_path + path = os.path.join(folder, arg[1:-1]) + if path not in includes: + includes.add(path) + with codecs.open(path, encoding='utf8') as f: + text = f.read() + rule_defs += _nearley_to_lark(text, builtin_path, n2l, js_code, os.path.abspath(os.path.dirname(path)), includes) + else: + assert False, directive + elif statement.data == 'js_code': + code ,= statement.children + code = code[2:-2] + js_code.append(code) + elif statement.data == 'macro': + pass # TODO Add support for macros! + elif statement.data == 'ruledef': + rule_defs.append( n2l.transform(statement) ) + else: + raise Exception("Unknown statement: %s" % statement) + + return rule_defs + + +def create_code_for_nearley_grammar(g, start, builtin_path, folder_path, es6=False): + import js2py + + emit_code = [] + def emit(x=None): + if x: + emit_code.append(x) + emit_code.append('\n') + + js_code = ['function id(x) {return x[0];}'] + n2l = NearleyToLark() + rule_defs = _nearley_to_lark(g, builtin_path, n2l, js_code, folder_path, set()) + lark_g = '\n'.join(rule_defs) + lark_g += '\n'+'\n'.join('!%s: %s' % item for item in n2l.extra_rules.items()) + + emit('from lark import Lark, Transformer') + emit() + emit('grammar = ' + repr(lark_g)) + emit() + + for alias, code in n2l.alias_js_code.items(): + js_code.append('%s = (%s);' % (alias, code)) + + if es6: + emit(js2py.translate_js6('\n'.join(js_code))) + else: + emit(js2py.translate_js('\n'.join(js_code))) + emit('class TransformNearley(Transformer):') + for alias in n2l.alias_js_code: + emit(" %s = var.get('%s').to_python()" % (alias, alias)) + emit(" __default__ = lambda self, n, c, m: c if c else None") + + emit() + emit('parser = Lark(grammar, start="n_%s", maybe_placeholders=False)' % start) + emit('def parse(text):') + emit(' return TransformNearley().transform(parser.parse(text))') + + return ''.join(emit_code) + +def main(fn, start, nearley_lib, es6=False): + with codecs.open(fn, encoding='utf8') as f: + grammar = f.read() + return create_code_for_nearley_grammar(grammar, start, os.path.join(nearley_lib, 'builtin'), os.path.abspath(os.path.dirname(fn)), es6=es6) + +def get_arg_parser(): + parser = argparse.ArgumentParser('Reads Nearley grammar (with js functions) outputs an equivalent lark parser.') + parser.add_argument('nearley_grammar', help='Path to the file containing the nearley grammar') + parser.add_argument('start_rule', help='Rule within the nearley grammar to make the base rule') + parser.add_argument('nearley_lib', help='Path to root directory of nearley codebase (used for including builtins)') + parser.add_argument('--es6', help='Enable experimental ES6 support', action='store_true') + return parser + +if __name__ == '__main__': + parser = get_arg_parser() + args = parser.parse_args() + print(main(fn=args.nearley_grammar, start=args.start_rule, nearley_lib=args.nearley_lib, es6=args.es6)) diff --git a/testbed/lark-parser__lark/lark/tools/serialize.py b/testbed/lark-parser__lark/lark/tools/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..fb69d35ace959356c697b501114b38c570055311 --- /dev/null +++ b/testbed/lark-parser__lark/lark/tools/serialize.py @@ -0,0 +1,39 @@ +import codecs +import sys +import json + +from lark import Lark +from lark.grammar import RuleOptions, Rule +from lark.lexer import TerminalDef + +import argparse + +argparser = argparse.ArgumentParser(prog='python -m lark.tools.serialize') #description='''Lark Serialization Tool -- Stores Lark's internal state & LALR analysis as a convenient JSON file''') + +argparser.add_argument('grammar_file', type=argparse.FileType('r'), help='A valid .lark file') +argparser.add_argument('-o', '--out', type=argparse.FileType('w'), default=sys.stdout, help='json file path to create (default=stdout)') +argparser.add_argument('-s', '--start', default='start', help='start symbol (default="start")', nargs='+') +argparser.add_argument('-l', '--lexer', default='standard', choices=['standard', 'contextual'], help='lexer type (default="standard")') + + +def serialize(infile, outfile, lexer, start): + lark_inst = Lark(infile, parser="lalr", lexer=lexer, start=start) # TODO contextual + + data, memo = lark_inst.memo_serialize([TerminalDef, Rule]) + outfile.write('{\n') + outfile.write(' "data": %s,\n' % json.dumps(data)) + outfile.write(' "memo": %s\n' % json.dumps(memo)) + outfile.write('}\n') + + +def main(): + if len(sys.argv) == 1 or '-h' in sys.argv or '--help' in sys.argv: + print("Lark Serialization Tool - Stores Lark's internal state & LALR analysis as a JSON file") + print("") + argparser.print_help() + else: + args = argparser.parse_args() + serialize(args.grammar_file, args.out, args.lexer, args.start) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/testbed/lark-parser__lark/lark/tools/standalone.py b/testbed/lark-parser__lark/lark/tools/standalone.py new file mode 100644 index 0000000000000000000000000000000000000000..f2af015c488d409e7ead8675d8fa62e7290c8201 --- /dev/null +++ b/testbed/lark-parser__lark/lark/tools/standalone.py @@ -0,0 +1,167 @@ +from __future__ import print_function + +###{standalone +# +# +# Lark Stand-alone Generator Tool +# ---------------------------------- +# Generates a stand-alone LALR(1) parser with a standard lexer +# +# Git: https://github.com/erezsh/lark +# Author: Erez Shinan (erezshin@gmail.com) +# +# +# >>> LICENSE +# +# This tool and its generated code use a separate license from Lark, +# and are subject to the terms of the Mozilla Public License, v. 2.0. +# If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# If you wish to purchase a commercial license for this tool and its +# generated code, you may contact me via email or otherwise. +# +# If MPL2 is incompatible with your free or open-source project, +# contact me and we'll work it out. +# +# + +import os +from io import open +###} + +import codecs +import sys +import token, tokenize +import os +from pprint import pprint +from os import path +from collections import defaultdict +from functools import partial + +import lark +from lark import Lark +from lark.parsers.lalr_analysis import Reduce + + +from lark.grammar import RuleOptions, Rule +from lark.lexer import TerminalDef + +_dir = path.dirname(__file__) +_larkdir = path.join(_dir, path.pardir) + + +EXTRACT_STANDALONE_FILES = [ + 'tools/standalone.py', + 'exceptions.py', + 'utils.py', + 'tree.py', + 'visitors.py', + 'indenter.py', + 'grammar.py', + 'lexer.py', + 'common.py', + 'parse_tree_builder.py', + 'parsers/lalr_parser.py', + 'parsers/lalr_analysis.py', + 'parser_frontends.py', + 'lark.py', +] + +def extract_sections(lines): + section = None + text = [] + sections = defaultdict(list) + for l in lines: + if l.startswith('###'): + if l[3] == '{': + section = l[4:].strip() + elif l[3] == '}': + sections[section] += text + section = None + text = [] + else: + raise ValueError(l) + elif section: + text.append(l) + + return {name:''.join(text) for name, text in sections.items()} + + +def strip_docstrings(line_gen): + """ Strip comments and docstrings from a file. + Based on code from: https://stackoverflow.com/questions/1769332/script-to-remove-python-comments-docstrings + """ + res = [] + + prev_toktype = token.INDENT + last_lineno = -1 + last_col = 0 + + tokgen = tokenize.generate_tokens(line_gen) + for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen: + if slineno > last_lineno: + last_col = 0 + if scol > last_col: + res.append(" " * (scol - last_col)) + if toktype == token.STRING and prev_toktype == token.INDENT: + # Docstring + res.append("#--") + elif toktype == tokenize.COMMENT: + # Comment + res.append("##\n") + else: + res.append(ttext) + prev_toktype = toktype + last_col = ecol + last_lineno = elineno + + return ''.join(res) + + +def main(fobj, start, print=print): + lark_inst = Lark(fobj, parser="lalr", lexer="contextual", start=start) + + print('# The file was automatically generated by Lark v%s' % lark.__version__) + print('__version__ = "%s"' % lark.__version__) + print() + + for i, pyfile in enumerate(EXTRACT_STANDALONE_FILES): + with open(os.path.join(_larkdir, pyfile)) as f: + code = extract_sections(f)['standalone'] + if i: # if not this file + code = strip_docstrings(partial(next, iter(code.splitlines(True)))) + print(code) + + data, m = lark_inst.memo_serialize([TerminalDef, Rule]) + print( 'DATA = (' ) + # pprint(data, width=160) + print(data) + print(')') + print( 'MEMO = (') + print(m) + print(')') + + + print('Shift = 0') + print('Reduce = 1') + print("def Lark_StandAlone(**kwargs):") + print(" return Lark._load_from_dict(DATA, MEMO, **kwargs)") + + + +if __name__ == '__main__': + if len(sys.argv) < 2: + print("Lark Stand-alone Generator Tool") + print("Usage: python -m lark.tools.standalone []") + sys.exit(1) + + if len(sys.argv) == 3: + fn, start = sys.argv[1:] + elif len(sys.argv) == 2: + fn, start = sys.argv[1], 'start' + else: + assert False, sys.argv + + with codecs.open(fn, encoding='utf8') as f: + main(f, start) diff --git a/testbed/lark-parser__lark/lark/tree.py b/testbed/lark-parser__lark/lark/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7114bb0f0d0926c82950303a15e512a55b4d55 --- /dev/null +++ b/testbed/lark-parser__lark/lark/tree.py @@ -0,0 +1,209 @@ +try: + from future_builtins import filter +except ImportError: + pass + +from copy import deepcopy + + +###{standalone +from collections import OrderedDict + + +class Meta: + def __init__(self): + self.empty = True + + +class Tree(object): + """The main tree class. + + Creates a new tree, and stores "data" and "children" in attributes of the same name. + Trees can be hashed and compared. + + Parameters: + data: The name of the rule or alias + children: List of matched sub-rules and terminals + meta: Line & Column numbers (if ``propagate_positions`` is enabled). + meta attributes: line, column, start_pos, end_line, end_column, end_pos + """ + def __init__(self, data, children, meta=None): + self.data = data + self.children = children + self._meta = meta + + @property + def meta(self): + if self._meta is None: + self._meta = Meta() + return self._meta + + def __repr__(self): + return 'Tree(%r, %r)' % (self.data, self.children) + + def _pretty_label(self): + return self.data + + def _pretty(self, level, indent_str): + if len(self.children) == 1 and not isinstance(self.children[0], Tree): + return [ indent_str*level, self._pretty_label(), '\t', '%s' % (self.children[0],), '\n'] + + l = [ indent_str*level, self._pretty_label(), '\n' ] + for n in self.children: + if isinstance(n, Tree): + l += n._pretty(level+1, indent_str) + else: + l += [ indent_str*(level+1), '%s' % (n,), '\n' ] + + return l + + def pretty(self, indent_str=' '): + """Returns an indented string representation of the tree. + + Great for debugging. + """ + return ''.join(self._pretty(0, indent_str)) + + def __eq__(self, other): + try: + return self.data == other.data and self.children == other.children + except AttributeError: + return False + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash((self.data, tuple(self.children))) + + def iter_subtrees(self): + """Depth-first iteration. + + Iterates over all the subtrees, never returning to the same node twice (Lark's parse-tree is actually a DAG). + """ + queue = [self] + subtrees = OrderedDict() + for subtree in queue: + subtrees[id(subtree)] = subtree + queue += [c for c in reversed(subtree.children) + if isinstance(c, Tree) and id(c) not in subtrees] + + del queue + return reversed(list(subtrees.values())) + + def find_pred(self, pred): + """Returns all nodes of the tree that evaluate pred(node) as true.""" + return filter(pred, self.iter_subtrees()) + + def find_data(self, data): + """Returns all nodes of the tree whose data equals the given data.""" + return self.find_pred(lambda t: t.data == data) + +###} + + def expand_kids_by_index(self, *indices): + "Expand (inline) children at the given indices" + for i in sorted(indices, reverse=True): # reverse so that changing tail won't affect indices + kid = self.children[i] + self.children[i:i+1] = kid.children + + def scan_values(self, pred): + for c in self.children: + if isinstance(c, Tree): + for t in c.scan_values(pred): + yield t + else: + if pred(c): + yield c + + def iter_subtrees_topdown(self): + """Breadth-first iteration. + + Iterates over all the subtrees, return nodes in order like pretty() does. + """ + stack = [self] + while stack: + node = stack.pop() + if not isinstance(node, Tree): + continue + yield node + for n in reversed(node.children): + stack.append(n) + + def __deepcopy__(self, memo): + return type(self)(self.data, deepcopy(self.children, memo), meta=self._meta) + + def copy(self): + return type(self)(self.data, self.children) + + def set(self, data, children): + self.data = data + self.children = children + + # XXX Deprecated! Here for backwards compatibility <0.6.0 + @property + def line(self): + return self.meta.line + @property + def column(self): + return self.meta.column + @property + def end_line(self): + return self.meta.end_line + @property + def end_column(self): + return self.meta.end_column + + +class SlottedTree(Tree): + __slots__ = 'data', 'children', 'rule', '_meta' + + +def pydot__tree_to_png(tree, filename, rankdir="LR", **kwargs): + graph = pydot__tree_to_graph(tree, rankdir, **kwargs) + graph.write_png(filename) + + +def pydot__tree_to_dot(tree, filename, rankdir="LR", **kwargs): + graph = pydot__tree_to_graph(tree, rankdir, **kwargs) + graph.write(filename) + +def pydot__tree_to_graph(tree, rankdir="LR", **kwargs): + """Creates a colorful image that represents the tree (data+children, without meta) + + Possible values for `rankdir` are "TB", "LR", "BT", "RL", corresponding to + directed graphs drawn from top to bottom, from left to right, from bottom to + top, and from right to left, respectively. + + `kwargs` can be any graph attribute (e. g. `dpi=200`). For a list of + possible attributes, see https://www.graphviz.org/doc/info/attrs.html. + """ + + import pydot + graph = pydot.Dot(graph_type='digraph', rankdir=rankdir, **kwargs) + + i = [0] + + def new_leaf(leaf): + node = pydot.Node(i[0], label=repr(leaf)) + i[0] += 1 + graph.add_node(node) + return node + + def _to_pydot(subtree): + color = hash(subtree.data) & 0xffffff + color |= 0x808080 + + subnodes = [_to_pydot(child) if isinstance(child, Tree) else new_leaf(child) + for child in subtree.children] + node = pydot.Node(i[0], style="filled", fillcolor="#%x"%color, label=subtree.data) + i[0] += 1 + graph.add_node(node) + + for subnode in subnodes: + graph.add_edge(pydot.Edge(node, subnode)) + + return node + + _to_pydot(tree) + return graph diff --git a/testbed/lark-parser__lark/lark/tree_matcher.py b/testbed/lark-parser__lark/lark/tree_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8c1f17a705929be113973b8277aa1063ff29c10b --- /dev/null +++ b/testbed/lark-parser__lark/lark/tree_matcher.py @@ -0,0 +1,178 @@ +"""Tree matcher based on Lark grammar""" + +import re +from collections import defaultdict + +from . import Tree, Token +from .common import ParserConf +from .parsers import earley +from .grammar import Rule, Terminal, NonTerminal + + +def is_discarded_terminal(t): + return t.is_term and t.filter_out + + +class _MakeTreeMatch: + def __init__(self, name, expansion): + self.name = name + self.expansion = expansion + + def __call__(self, args): + t = Tree(self.name, args) + t.meta.match_tree = True + t.meta.orig_expansion = self.expansion + return t + + +def _best_from_group(seq, group_key, cmp_key): + d = {} + for item in seq: + key = group_key(item) + if key in d: + v1 = cmp_key(item) + v2 = cmp_key(d[key]) + if v2 > v1: + d[key] = item + else: + d[key] = item + return list(d.values()) + + +def _best_rules_from_group(rules): + rules = _best_from_group(rules, lambda r: r, lambda r: -len(r.expansion)) + rules.sort(key=lambda r: len(r.expansion)) + return rules + + +def _match(term, token): + if isinstance(token, Tree): + name, _args = parse_rulename(term.name) + return token.data == name + elif isinstance(token, Token): + return term == Terminal(token.type) + assert False + + +def make_recons_rule(origin, expansion, old_expansion): + return Rule(origin, expansion, alias=_MakeTreeMatch(origin.name, old_expansion)) + + +def make_recons_rule_to_term(origin, term): + return make_recons_rule(origin, [Terminal(term.name)], [term]) + + +def parse_rulename(s): + "Parse rule names that may contain a template syntax (like rule{a, b, ...})" + name, args_str = re.match(r'(\w+)(?:{(.+)})?', s).groups() + args = args_str and [a.strip() for a in args_str.split(',')] + return name, args + + +class TreeMatcher: + """Match the elements of a tree node, based on an ontology + provided by a Lark grammar. + + Supports templates and inlined rules (`rule{a, b,..}` and `_rule`) + + Initiialize with an instance of Lark. + """ + + def __init__(self, parser): + # XXX TODO calling compile twice returns different results! + assert parser.options.maybe_placeholders == False + # XXX TODO: we just ignore the potential existence of a postlexer + self.tokens, rules, _extra = parser.grammar.compile(parser.options.start, set()) + + self.rules_for_root = defaultdict(list) + + self.rules = list(self._build_recons_rules(rules)) + self.rules.reverse() + + # Choose the best rule from each group of {rule => [rule.alias]}, since we only really need one derivation. + self.rules = _best_rules_from_group(self.rules) + + self.parser = parser + self._parser_cache = {} + + def _build_recons_rules(self, rules): + "Convert tree-parsing/construction rules to tree-matching rules" + expand1s = {r.origin for r in rules if r.options.expand1} + + aliases = defaultdict(list) + for r in rules: + if r.alias: + aliases[r.origin].append(r.alias) + + rule_names = {r.origin for r in rules} + nonterminals = {sym for sym in rule_names + if sym.name.startswith('_') or sym in expand1s or sym in aliases} + + seen = set() + for r in rules: + recons_exp = [sym if sym in nonterminals else Terminal(sym.name) + for sym in r.expansion if not is_discarded_terminal(sym)] + + # Skip self-recursive constructs + if recons_exp == [r.origin] and r.alias is None: + continue + + sym = NonTerminal(r.alias) if r.alias else r.origin + rule = make_recons_rule(sym, recons_exp, r.expansion) + + if sym in expand1s and len(recons_exp) != 1: + self.rules_for_root[sym.name].append(rule) + + if sym.name not in seen: + yield make_recons_rule_to_term(sym, sym) + seen.add(sym.name) + else: + if sym.name.startswith('_') or sym in expand1s: + yield rule + else: + self.rules_for_root[sym.name].append(rule) + + for origin, rule_aliases in aliases.items(): + for alias in rule_aliases: + yield make_recons_rule_to_term(origin, NonTerminal(alias)) + yield make_recons_rule_to_term(origin, origin) + + def match_tree(self, tree, rulename): + """Match the elements of `tree` to the symbols of rule `rulename`. + + Parameters: + tree (Tree): the tree node to match + rulename (str): The expected full rule name (including template args) + + Returns: + Tree: an unreduced tree that matches `rulename` + + Raises: + UnexpectedToken: If no match was found. + + Note: + It's the callers' responsibility match the tree recursively. + """ + if rulename: + # validate + name, _args = parse_rulename(rulename) + assert tree.data == name + else: + rulename = tree.data + + # TODO: ambiguity? + try: + parser = self._parser_cache[rulename] + except KeyError: + rules = self.rules + _best_rules_from_group(self.rules_for_root[rulename]) + + # TODO pass callbacks through dict, instead of alias? + callbacks = {rule: rule.alias for rule in rules} + conf = ParserConf(rules, callbacks, [rulename]) + parser = earley.Parser(conf, _match, resolve_ambiguity=True) + self._parser_cache[rulename] = parser + + # find a full derivation + unreduced_tree = parser.parse(tree.children, rulename) + assert unreduced_tree.data == rulename + return unreduced_tree diff --git a/testbed/lark-parser__lark/lark/utils.py b/testbed/lark-parser__lark/lark/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfcf0bc106256a03a0a7c59e0596b881886a2a2 --- /dev/null +++ b/testbed/lark-parser__lark/lark/utils.py @@ -0,0 +1,335 @@ +import sys +import os +from functools import reduce +from ast import literal_eval +from collections import deque + +###{standalone +import logging +logger = logging.getLogger("lark") +logger.addHandler(logging.StreamHandler()) +# Set to highest level, since we have some warnings amongst the code +# By default, we should not output any log messages +logger.setLevel(logging.CRITICAL) + + +def classify(seq, key=None, value=None): + d = {} + for item in seq: + k = key(item) if (key is not None) else item + v = value(item) if (value is not None) else item + if k in d: + d[k].append(v) + else: + d[k] = [v] + return d + + +def _deserialize(data, namespace, memo): + if isinstance(data, dict): + if '__type__' in data: # Object + class_ = namespace[data['__type__']] + return class_.deserialize(data, memo) + elif '@' in data: + return memo[data['@']] + return {key:_deserialize(value, namespace, memo) for key, value in data.items()} + elif isinstance(data, list): + return [_deserialize(value, namespace, memo) for value in data] + return data + + +class Serialize(object): + """Safe-ish serialization interface that doesn't rely on Pickle + + Attributes: + __serialize_fields__ (List[str]): Fields (aka attributes) to serialize. + __serialize_namespace__ (list): List of classes that deserialization is allowed to instanciate. + Should include all field types that aren't builtin types. + """ + + def memo_serialize(self, types_to_memoize): + memo = SerializeMemoizer(types_to_memoize) + return self.serialize(memo), memo.serialize() + + def serialize(self, memo=None): + if memo and memo.in_types(self): + return {'@': memo.memoized.get(self)} + + fields = getattr(self, '__serialize_fields__') + res = {f: _serialize(getattr(self, f), memo) for f in fields} + res['__type__'] = type(self).__name__ + postprocess = getattr(self, '_serialize', None) + if postprocess: + postprocess(res, memo) + return res + + @classmethod + def deserialize(cls, data, memo): + namespace = getattr(cls, '__serialize_namespace__', {}) + namespace = {c.__name__:c for c in namespace} + + fields = getattr(cls, '__serialize_fields__') + + if '@' in data: + return memo[data['@']] + + inst = cls.__new__(cls) + for f in fields: + try: + setattr(inst, f, _deserialize(data[f], namespace, memo)) + except KeyError as e: + raise KeyError("Cannot find key for class", cls, e) + postprocess = getattr(inst, '_deserialize', None) + if postprocess: + postprocess() + return inst + + +class SerializeMemoizer(Serialize): + "A version of serialize that memoizes objects to reduce space" + + __serialize_fields__ = 'memoized', + + def __init__(self, types_to_memoize): + self.types_to_memoize = tuple(types_to_memoize) + self.memoized = Enumerator() + + def in_types(self, value): + return isinstance(value, self.types_to_memoize) + + def serialize(self): + return _serialize(self.memoized.reversed(), None) + + @classmethod + def deserialize(cls, data, namespace, memo): + return _deserialize(data, namespace, memo) + + + +try: + STRING_TYPE = basestring +except NameError: # Python 3 + STRING_TYPE = str + + +import types +from functools import wraps, partial +from contextlib import contextmanager + +Str = type(u'') +try: + classtype = types.ClassType # Python2 +except AttributeError: + classtype = type # Python3 + +def smart_decorator(f, create_decorator): + if isinstance(f, types.FunctionType): + return wraps(f)(create_decorator(f, True)) + + elif isinstance(f, (classtype, type, types.BuiltinFunctionType)): + return wraps(f)(create_decorator(f, False)) + + elif isinstance(f, types.MethodType): + return wraps(f)(create_decorator(f.__func__, True)) + + elif isinstance(f, partial): + # wraps does not work for partials in 2.7: https://bugs.python.org/issue3445 + return wraps(f.func)(create_decorator(lambda *args, **kw: f(*args[1:], **kw), True)) + + else: + return create_decorator(f.__func__.__call__, True) + +try: + import regex +except ImportError: + regex = None + +import sys, re +Py36 = (sys.version_info[:2] >= (3, 6)) + +import sre_parse +import sre_constants +categ_pattern = re.compile(r'\\p{[A-Za-z_]+}') +def get_regexp_width(expr): + if regex: + # Since `sre_parse` cannot deal with Unicode categories of the form `\p{Mn}`, we replace these with + # a simple letter, which makes no difference as we are only trying to get the possible lengths of the regex + # match here below. + regexp_final = re.sub(categ_pattern, 'A', expr) + else: + if re.search(categ_pattern, expr): + raise ImportError('`regex` module must be installed in order to use Unicode categories.', expr) + regexp_final = expr + try: + return [int(x) for x in sre_parse.parse(regexp_final).getwidth()] + except sre_constants.error: + raise ValueError(expr) + +###} + + +def dedup_list(l): + """Given a list (l) will removing duplicates from the list, + preserving the original order of the list. Assumes that + the list entries are hashable.""" + dedup = set() + return [ x for x in l if not (x in dedup or dedup.add(x))] + + + + +try: + from contextlib import suppress # Python 3 +except ImportError: + @contextmanager + def suppress(*excs): + '''Catch and dismiss the provided exception + + >>> x = 'hello' + >>> with suppress(IndexError): + ... x = x[10] + >>> x + 'hello' + ''' + try: + yield + except excs: + pass + + + + +try: + compare = cmp +except NameError: + def compare(a, b): + if a == b: + return 0 + elif a > b: + return 1 + return -1 + + + +class Enumerator(Serialize): + def __init__(self): + self.enums = {} + + def get(self, item): + if item not in self.enums: + self.enums[item] = len(self.enums) + return self.enums[item] + + def __len__(self): + return len(self.enums) + + def reversed(self): + r = {v: k for k, v in self.enums.items()} + assert len(r) == len(self.enums) + return r + + +def eval_escaping(s): + w = '' + i = iter(s) + for n in i: + w += n + if n == '\\': + try: + n2 = next(i) + except StopIteration: + raise ValueError("Literal ended unexpectedly (bad escaping): `%r`" % s) + if n2 == '\\': + w += '\\\\' + elif n2 not in 'uxnftr': + w += '\\' + w += n2 + w = w.replace('\\"', '"').replace("'", "\\'") + + to_eval = "u'''%s'''" % w + try: + s = literal_eval(to_eval) + except SyntaxError as e: + raise ValueError(s, e) + + return s + + +def combine_alternatives(lists): + """ + Accepts a list of alternatives, and enumerates all their possible concatinations. + + Examples: + >>> combine_alternatives([range(2), [4,5]]) + [[0, 4], [0, 5], [1, 4], [1, 5]] + + >>> combine_alternatives(["abc", "xy", '$']) + [['a', 'x', '$'], ['a', 'y', '$'], ['b', 'x', '$'], ['b', 'y', '$'], ['c', 'x', '$'], ['c', 'y', '$']] + + >>> combine_alternatives([]) + [[]] + """ + if not lists: + return [[]] + assert all(l for l in lists), lists + init = [[x] for x in lists[0]] + return reduce(lambda a,b: [i+[j] for i in a for j in b], lists[1:], init) + + +class FS: + open = open + exists = os.path.exists + + +def isascii(s): + """ str.isascii only exists in python3.7+ """ + try: + return s.isascii() + except AttributeError: + try: + s.encode('ascii') + return True + except (UnicodeDecodeError, UnicodeEncodeError): + return False + + +class fzset(frozenset): + def __repr__(self): + return '{%s}' % ', '.join(map(repr, self)) + + +def classify_bool(seq, pred): + true_elems = [] + false_elems = [] + + for elem in seq: + if pred(elem): + true_elems.append(elem) + else: + false_elems.append(elem) + + return true_elems, false_elems + + +def bfs(initial, expand): + open_q = deque(list(initial)) + visited = set(open_q) + while open_q: + node = open_q.popleft() + yield node + for next_node in expand(node): + if next_node not in visited: + visited.add(next_node) + open_q.append(next_node) + + +def _serialize(value, memo): + if isinstance(value, Serialize): + return value.serialize(memo) + elif isinstance(value, list): + return [_serialize(elem, memo) for elem in value] + elif isinstance(value, frozenset): + return list(value) # TODO reversible? + elif isinstance(value, dict): + return {key:_serialize(elem, memo) for key, elem in value.items()} + return value \ No newline at end of file diff --git a/testbed/lark-parser__lark/lark/visitors.py b/testbed/lark-parser__lark/lark/visitors.py new file mode 100644 index 0000000000000000000000000000000000000000..14896e57fad5eec2d983ac7d6d533747ca4c8239 --- /dev/null +++ b/testbed/lark-parser__lark/lark/visitors.py @@ -0,0 +1,460 @@ +from functools import wraps + +from .utils import smart_decorator, combine_alternatives +from .tree import Tree +from .exceptions import VisitError, GrammarError +from .lexer import Token + +###{standalone +from inspect import getmembers, getmro + +class Discard(Exception): + """When raising the Discard exception in a transformer callback, + that node is discarded and won't appear in the parent. + """ + pass + +# Transformers + +class _Decoratable: + "Provides support for decorating methods with @v_args" + + @classmethod + def _apply_decorator(cls, decorator, **kwargs): + mro = getmro(cls) + assert mro[0] is cls + libmembers = {name for _cls in mro[1:] for name, _ in getmembers(_cls)} + for name, value in getmembers(cls): + + # Make sure the function isn't inherited (unless it's overwritten) + if name.startswith('_') or (name in libmembers and name not in cls.__dict__): + continue + if not callable(value): + continue + + # Skip if v_args already applied (at the function level) + if hasattr(cls.__dict__[name], 'vargs_applied') or hasattr(value, 'vargs_applied'): + continue + + static = isinstance(cls.__dict__[name], (staticmethod, classmethod)) + setattr(cls, name, decorator(value, static=static, **kwargs)) + return cls + + def __class_getitem__(cls, _): + return cls + + +class Transformer(_Decoratable): + """Transformers visit each node of the tree, and run the appropriate method on it according to the node's data. + + Calls its methods (provided by user via inheritance) according to ``tree.data``. + The returned value replaces the old one in the structure. + + They work bottom-up (or depth-first), starting with the leaves and ending at the root of the tree. + Transformers can be used to implement map & reduce patterns. Because nodes are reduced from leaf to root, + at any point the callbacks may assume the children have already been transformed (if applicable). + + ``Transformer`` can do anything ``Visitor`` can do, but because it reconstructs the tree, + it is slightly less efficient. It can be used to implement map or reduce patterns. + + All these classes implement the transformer interface: + + - ``Transformer`` - Recursively transforms the tree. This is the one you probably want. + - ``Transformer_InPlace`` - Non-recursive. Changes the tree in-place instead of returning new instances + - ``Transformer_InPlaceRecursive`` - Recursive. Changes the tree in-place instead of returning new instances + + Parameters: + visit_tokens: By default, transformers only visit rules. + visit_tokens=True will tell ``Transformer`` to visit tokens + as well. This is a slightly slower alternative to lexer_callbacks + but it's easier to maintain and works for all algorithms + (even when there isn't a lexer). + + """ + __visit_tokens__ = True # For backwards compatibility + + def __init__(self, visit_tokens=True): + self.__visit_tokens__ = visit_tokens + + def _call_userfunc(self, tree, new_children=None): + # Assumes tree is already transformed + children = new_children if new_children is not None else tree.children + try: + f = getattr(self, tree.data) + except AttributeError: + return self.__default__(tree.data, children, tree.meta) + else: + try: + wrapper = getattr(f, 'visit_wrapper', None) + if wrapper is not None: + return f.visit_wrapper(f, tree.data, children, tree.meta) + else: + return f(children) + except (GrammarError, Discard): + raise + except Exception as e: + raise VisitError(tree.data, tree, e) + + def _call_userfunc_token(self, token): + try: + f = getattr(self, token.type) + except AttributeError: + return self.__default_token__(token) + else: + try: + return f(token) + except (GrammarError, Discard): + raise + except Exception as e: + raise VisitError(token.type, token, e) + + + def _transform_children(self, children): + for c in children: + try: + if isinstance(c, Tree): + yield self._transform_tree(c) + elif self.__visit_tokens__ and isinstance(c, Token): + yield self._call_userfunc_token(c) + else: + yield c + except Discard: + pass + + def _transform_tree(self, tree): + children = list(self._transform_children(tree.children)) + return self._call_userfunc(tree, children) + + def transform(self, tree): + return self._transform_tree(tree) + + def __mul__(self, other): + return TransformerChain(self, other) + + def __default__(self, data, children, meta): + """Default operation on tree (for override) + + Function that is called on if a function with a corresponding name has not been found. + Defaults to reconstruct the Tree. + """ + return Tree(data, children, meta) + + def __default_token__(self, token): + """Default operation on token (for override) + + Function that is called on if a function with a corresponding name has not been found. + Defaults to just return the argument. + """ + return token + + + +class InlineTransformer(Transformer): # XXX Deprecated + def _call_userfunc(self, tree, new_children=None): + # Assumes tree is already transformed + children = new_children if new_children is not None else tree.children + try: + f = getattr(self, tree.data) + except AttributeError: + return self.__default__(tree.data, children, tree.meta) + else: + return f(*children) + + +class TransformerChain(object): + def __init__(self, *transformers): + self.transformers = transformers + + def transform(self, tree): + for t in self.transformers: + tree = t.transform(tree) + return tree + + def __mul__(self, other): + return TransformerChain(*self.transformers + (other,)) + + +class Transformer_InPlace(Transformer): + "Non-recursive. Changes the tree in-place instead of returning new instances" + def _transform_tree(self, tree): # Cancel recursion + return self._call_userfunc(tree) + + def transform(self, tree): + for subtree in tree.iter_subtrees(): + subtree.children = list(self._transform_children(subtree.children)) + + return self._transform_tree(tree) + + +class Transformer_NonRecursive(Transformer): + "Non-recursive. Doesn't change the original tree." + + def transform(self, tree): + # Tree to postfix + rev_postfix = [] + q = [tree] + while q: + t = q.pop() + rev_postfix.append( t ) + if isinstance(t, Tree): + q += t.children + + # Postfix to tree + stack = [] + for x in reversed(rev_postfix): + if isinstance(x, Tree): + size = len(x.children) + if size: + args = stack[-size:] + del stack[-size:] + else: + args = [] + stack.append(self._call_userfunc(x, args)) + else: + stack.append(x) + + t ,= stack # We should have only one tree remaining + return t + + + +class Transformer_InPlaceRecursive(Transformer): + "Recursive. Changes the tree in-place instead of returning new instances" + def _transform_tree(self, tree): + tree.children = list(self._transform_children(tree.children)) + return self._call_userfunc(tree) + + + +# Visitors + +class VisitorBase: + def _call_userfunc(self, tree): + return getattr(self, tree.data, self.__default__)(tree) + + def __default__(self, tree): + "Default operation on tree (for override)" + return tree + + def __class_getitem__(cls, _): + return cls + + +class Visitor(VisitorBase): + """Bottom-up visitor, non-recursive. + + Visits the tree, starting with the leaves and finally the root (bottom-up) + Calls its methods (provided by user via inheritance) according to ``tree.data`` + """ + + def visit(self, tree): + for subtree in tree.iter_subtrees(): + self._call_userfunc(subtree) + return tree + + def visit_topdown(self,tree): + for subtree in tree.iter_subtrees_topdown(): + self._call_userfunc(subtree) + return tree + + +class Visitor_Recursive(VisitorBase): + """Bottom-up visitor, recursive. + + Visits the tree, starting with the leaves and finally the root (bottom-up) + Calls its methods (provided by user via inheritance) according to ``tree.data`` + """ + + def visit(self, tree): + for child in tree.children: + if isinstance(child, Tree): + self.visit(child) + + self._call_userfunc(tree) + return tree + + def visit_topdown(self,tree): + self._call_userfunc(tree) + + for child in tree.children: + if isinstance(child, Tree): + self.visit_topdown(child) + + return tree + + + +def visit_children_decor(func): + "See Interpreter" + @wraps(func) + def inner(cls, tree): + values = cls.visit_children(tree) + return func(cls, values) + return inner + + +class Interpreter(_Decoratable): + """Interpreter walks the tree starting at the root. + + Visits the tree, starting with the root and finally the leaves (top-down) + + For each tree node, it calls its methods (provided by user via inheritance) according to ``tree.data``. + + Unlike ``Transformer`` and ``Visitor``, the Interpreter doesn't automatically visit its sub-branches. + The user has to explicitly call ``visit``, ``visit_children``, or use the ``@visit_children_decor``. + This allows the user to implement branching and loops. + """ + + def visit(self, tree): + f = getattr(self, tree.data) + wrapper = getattr(f, 'visit_wrapper', None) + if wrapper is not None: + return f.visit_wrapper(f, tree.data, tree.children, tree.meta) + else: + return f(tree) + + def visit_children(self, tree): + return [self.visit(child) if isinstance(child, Tree) else child + for child in tree.children] + + def __getattr__(self, name): + return self.__default__ + + def __default__(self, tree): + return self.visit_children(tree) + + + + +# Decorators + +def _apply_decorator(obj, decorator, **kwargs): + try: + _apply = obj._apply_decorator + except AttributeError: + return decorator(obj, **kwargs) + else: + return _apply(decorator, **kwargs) + + + +def _inline_args__func(func): + @wraps(func) + def create_decorator(_f, with_self): + if with_self: + def f(self, children): + return _f(self, *children) + else: + def f(self, children): + return _f(*children) + return f + + return smart_decorator(func, create_decorator) + + +def inline_args(obj): # XXX Deprecated + return _apply_decorator(obj, _inline_args__func) + + + +def _visitor_args_func_dec(func, visit_wrapper=None, static=False): + def create_decorator(_f, with_self): + if with_self: + def f(self, *args, **kwargs): + return _f(self, *args, **kwargs) + else: + def f(self, *args, **kwargs): + return _f(*args, **kwargs) + return f + + if static: + f = wraps(func)(create_decorator(func, False)) + else: + f = smart_decorator(func, create_decorator) + f.vargs_applied = True + f.visit_wrapper = visit_wrapper + return f + + +def _vargs_inline(f, data, children, meta): + return f(*children) +def _vargs_meta_inline(f, data, children, meta): + return f(meta, *children) +def _vargs_meta(f, data, children, meta): + return f(children, meta) # TODO swap these for consistency? Backwards incompatible! +def _vargs_tree(f, data, children, meta): + return f(Tree(data, children, meta)) + + +def v_args(inline=False, meta=False, tree=False, wrapper=None): + """A convenience decorator factory for modifying the behavior of user-supplied visitor methods. + + By default, callback methods of transformers/visitors accept one argument - a list of the node's children. + + ``v_args`` can modify this behavior. When used on a transformer/visitor class definition, + it applies to all the callback methods inside it. + + Parameters: + inline: Children are provided as ``*args`` instead of a list argument (not recommended for very long lists). + meta: Provides two arguments: ``children`` and ``meta`` (instead of just the first) + tree: Provides the entire tree as the argument, instead of the children. + + Example: + :: + + @v_args(inline=True) + class SolveArith(Transformer): + def add(self, left, right): + return left + right + + + class ReverseNotation(Transformer_InPlace): + @v_args(tree=True) + def tree_node(self, tree): + tree.children = tree.children[::-1] + """ + if tree and (meta or inline): + raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.") + + func = None + if meta: + if inline: + func = _vargs_meta_inline + else: + func = _vargs_meta + elif inline: + func = _vargs_inline + elif tree: + func = _vargs_tree + + if wrapper is not None: + if func is not None: + raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.") + func = wrapper + + def _visitor_args_dec(obj): + return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func) + return _visitor_args_dec + + +###} + + +#--- Visitor Utilities --- + +class CollapseAmbiguities(Transformer): + """ + Transforms a tree that contains any number of _ambig nodes into a list of trees, + each one containing an unambiguous tree. + + The length of the resulting list is the product of the length of all _ambig nodes. + + Warning: This may quickly explode for highly ambiguous trees. + + """ + def _ambig(self, options): + return sum(options, []) + def __default__(self, data, children_lists, meta): + return [Tree(data, children, meta) for children in combine_alternatives(children_lists)] + def __default_token__(self, t): + return [t] diff --git a/testbed/lark-parser__lark/readthedocs.yml b/testbed/lark-parser__lark/readthedocs.yml new file mode 100644 index 0000000000000000000000000000000000000000..4636dc73157833736afeea2231cfc0d69caa3a80 --- /dev/null +++ b/testbed/lark-parser__lark/readthedocs.yml @@ -0,0 +1,12 @@ +version: 2 + +formats: all + +python: + version: 3.7 + install: + - requirements: docs/requirements.txt + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: docs/conf.py diff --git a/testbed/lark-parser__lark/test-requirements.txt b/testbed/lark-parser__lark/test-requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d304ee8f73931e2b3212bcf62d1ac78f50b08f56 --- /dev/null +++ b/testbed/lark-parser__lark/test-requirements.txt @@ -0,0 +1,2 @@ +Js2Py==0.68 +regex \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/__init__.py b/testbed/lark-parser__lark/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/lark-parser__lark/tests/__main__.py b/testbed/lark-parser__lark/tests/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec89e372200a3f6c7252bf1fc2078b5de2e0aec --- /dev/null +++ b/testbed/lark-parser__lark/tests/__main__.py @@ -0,0 +1,41 @@ +from __future__ import absolute_import, print_function + +import unittest +import logging +from lark import logger + +from .test_trees import TestTrees +from .test_tools import TestStandalone +from .test_cache import TestCache +from .test_grammar import TestGrammar +from .test_reconstructor import TestReconstructor + +try: + from .test_nearley.test_nearley import TestNearley +except ImportError: + logger.warning("Warning: Skipping tests for Nearley grammar imports (js2py required)") + +# from .test_selectors import TestSelectors +# from .test_grammars import TestPythonG, TestConfigG + +from .test_logger import Testlogger + +from .test_parser import ( + TestLalrStandard, + TestEarleyStandard, + TestCykStandard, + TestLalrContextual, + TestEarleyDynamic, + TestLalrCustom, + + # TestFullEarleyStandard, + TestFullEarleyDynamic, + TestFullEarleyDynamic_complete, + + TestParsers, + ) + +logger.setLevel(logging.INFO) + +if __name__ == '__main__': + unittest.main() diff --git a/testbed/lark-parser__lark/tests/grammars/ab.lark b/testbed/lark-parser__lark/tests/grammars/ab.lark new file mode 100644 index 0000000000000000000000000000000000000000..33a985ad642977119ddfc9c89dc5b890353bb7aa --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/ab.lark @@ -0,0 +1,10 @@ +startab: expr + +expr: A B + | A expr B + +A: "a" +B: "b" + +%import common.WS +%ignore WS diff --git a/testbed/lark-parser__lark/tests/grammars/leading_underscore_grammar.lark b/testbed/lark-parser__lark/tests/grammars/leading_underscore_grammar.lark new file mode 100644 index 0000000000000000000000000000000000000000..b09a2f4a840bb1d11753d7a78d528c79ff83e2f1 --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/leading_underscore_grammar.lark @@ -0,0 +1,6 @@ +A: "A" + +_SEP: "x" +_a: A + +c: _a _SEP \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/grammars/templates.lark b/testbed/lark-parser__lark/tests/grammars/templates.lark new file mode 100644 index 0000000000000000000000000000000000000000..1631188e719631d0fa648f50d79506211e51210d --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/templates.lark @@ -0,0 +1 @@ +sep{item, delim}: item (delim item)* \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/grammars/test.lark b/testbed/lark-parser__lark/tests/grammars/test.lark new file mode 100644 index 0000000000000000000000000000000000000000..3c3cbcfd84aa818d3e763078cce13a21689929b6 --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/test.lark @@ -0,0 +1,3 @@ +%import common.NUMBER +%import common.WORD +%import common.WS diff --git a/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar.lark b/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar.lark new file mode 100644 index 0000000000000000000000000000000000000000..1af59538a4464656ac11b74102e47fb8073a2df0 --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar.lark @@ -0,0 +1,4 @@ + +start: rule_to_import + +%import .test_relative_import_of_nested_grammar__grammar_to_import.rule_to_import \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar__grammar_to_import.lark b/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar__grammar_to_import.lark new file mode 100644 index 0000000000000000000000000000000000000000..6a40e2bb8eeebadedfaaa87b8a3cac2692e621aa --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar__grammar_to_import.lark @@ -0,0 +1,4 @@ + +rule_to_import: NESTED_TERMINAL + +%import .test_relative_import_of_nested_grammar__nested_grammar.NESTED_TERMINAL diff --git a/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar__nested_grammar.lark b/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar__nested_grammar.lark new file mode 100644 index 0000000000000000000000000000000000000000..2d4a2a8afb7e13fbc791e0bca6d20d1972605727 --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/test_relative_import_of_nested_grammar__nested_grammar.lark @@ -0,0 +1 @@ +NESTED_TERMINAL: "N" diff --git a/testbed/lark-parser__lark/tests/grammars/test_unicode.lark b/testbed/lark-parser__lark/tests/grammars/test_unicode.lark new file mode 100644 index 0000000000000000000000000000000000000000..9731d0a69e731b17a8cd7b85ed8906283e386740 --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/test_unicode.lark @@ -0,0 +1 @@ +UNICODE : /[a-zØ-öø-ÿ]/ \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/grammars/three_rules_using_same_token.lark b/testbed/lark-parser__lark/tests/grammars/three_rules_using_same_token.lark new file mode 100644 index 0000000000000000000000000000000000000000..8b41ad23d144047921597432ec0e7a43c90f8463 --- /dev/null +++ b/testbed/lark-parser__lark/tests/grammars/three_rules_using_same_token.lark @@ -0,0 +1,7 @@ +%import common.INT + +a: A +b: A +c: A + +A: "A" \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/test_cache.py b/testbed/lark-parser__lark/tests/test_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4a07d7a3c10390c181db9ad5c1ab33aed0a28853 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_cache.py @@ -0,0 +1,101 @@ +from __future__ import absolute_import + +import sys +from unittest import TestCase, main + +from lark import Lark, Tree +from lark.lexer import Lexer, Token +import lark.lark as lark_module + +try: + from StringIO import StringIO +except ImportError: + from io import BytesIO as StringIO + +import tempfile, os + + +class MockFile(StringIO): + def close(self): + pass + def __enter__(self): + return self + def __exit__(self, *args): + pass + +class MockFS: + def __init__(self): + self.files = {} + + def open(self, name, mode=None): + if name not in self.files: + f = self.files[name] = MockFile() + else: + f = self.files[name] + f.seek(0) + return f + + def exists(self, name): + return name in self.files + + +class CustomLexer(Lexer): + def __init__(self, lexer_conf): + pass + + def lex(self, data): + for obj in data: + yield Token('A', obj) + + +class TestCache(TestCase): + def setUp(self): + pass + + def test_simple(self): + g = '''start: "a"''' + + fn = "bla" + + fs = lark_module.FS + mock_fs = MockFS() + try: + lark_module.FS = mock_fs + Lark(g, parser='lalr', cache=fn) + assert fn in mock_fs.files + parser = Lark(g, parser='lalr', cache=fn) + assert parser.parse('a') == Tree('start', []) + + mock_fs.files = {} + assert len(mock_fs.files) == 0 + Lark(g, parser='lalr', cache=True) + assert len(mock_fs.files) == 1 + parser = Lark(g, parser='lalr', cache=True) + assert parser.parse('a') == Tree('start', []) + + parser = Lark(g+' "b"', parser='lalr', cache=True) + assert len(mock_fs.files) == 2 + assert parser.parse('ab') == Tree('start', []) + + parser = Lark(g, parser='lalr', cache=True) + assert parser.parse('a') == Tree('start', []) + + # Test with custom lexer + mock_fs.files = {} + parser = Lark(g, parser='lalr', lexer=CustomLexer, cache=True) + parser = Lark(g, parser='lalr', lexer=CustomLexer, cache=True) + assert len(mock_fs.files) == 1 + assert parser.parse('a') == Tree('start', []) + + # Test options persistence + mock_fs.files = {} + Lark(g, parser="lalr", debug=True, cache=True) + parser = Lark(g, parser="lalr", debug=True, cache=True) + assert parser.options.options['debug'] + finally: + lark_module.FS = fs + + + +if __name__ == '__main__': + main() diff --git a/testbed/lark-parser__lark/tests/test_grammar.py b/testbed/lark-parser__lark/tests/test_grammar.py new file mode 100644 index 0000000000000000000000000000000000000000..363f897e2b6868cf2a32d42bcba860c5edc6e8e3 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_grammar.py @@ -0,0 +1,31 @@ +from __future__ import absolute_import + +import sys +from unittest import TestCase, main + +from lark import Lark +from lark.load_grammar import GrammarLoader, GrammarError + + +class TestGrammar(TestCase): + def setUp(self): + pass + + def test_errors(self): + for msg, examples in GrammarLoader.ERRORS: + for example in examples: + try: + p = Lark(example) + except GrammarError as e: + assert msg in str(e) + else: + assert False, "example did not raise an error" + + + + +if __name__ == '__main__': + main() + + + diff --git a/testbed/lark-parser__lark/tests/test_logger.py b/testbed/lark-parser__lark/tests/test_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..93dc8ed4f356e41e6512cb55fcbad11e261452a4 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_logger.py @@ -0,0 +1,65 @@ +import logging +from contextlib import contextmanager +from lark import Lark, logger +from unittest import TestCase, main + +try: + from StringIO import StringIO +except ImportError: + from io import StringIO + +@contextmanager +def capture_log(): + stream = StringIO() + orig_handler = logger.handlers[0] + del logger.handlers[:] + logger.addHandler(logging.StreamHandler(stream)) + yield stream + del logger.handlers[:] + logger.addHandler(orig_handler) + +class Testlogger(TestCase): + + def test_debug(self): + logger.setLevel(logging.DEBUG) + collision_grammar = ''' + start: as as + as: a* + a: "a" + ''' + with capture_log() as log: + Lark(collision_grammar, parser='lalr', debug=True) + + log = log.getvalue() + # since there are conflicts about A + # symbol A should appear in the log message for hint + self.assertIn("A", log) + + def test_non_debug(self): + logger.setLevel(logging.DEBUG) + collision_grammar = ''' + start: as as + as: a* + a: "a" + ''' + with capture_log() as log: + Lark(collision_grammar, parser='lalr', debug=False) + log = log.getvalue() + # no log messge + self.assertEqual(len(log), 0) + + def test_loglevel_higher(self): + logger.setLevel(logging.ERROR) + collision_grammar = ''' + start: as as + as: a* + a: "a" + ''' + with capture_log() as log: + Lark(collision_grammar, parser='lalr', debug=True) + log = log.getvalue() + # no log messge + self.assertEqual(len(log), 0) + +if __name__ == '__main__': + main() diff --git a/testbed/lark-parser__lark/tests/test_nearley/__init__.py b/testbed/lark-parser__lark/tests/test_nearley/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/lark-parser__lark/tests/test_nearley/grammars/include_unicode.ne b/testbed/lark-parser__lark/tests/test_nearley/grammars/include_unicode.ne new file mode 100644 index 0000000000000000000000000000000000000000..b04c2a917f31d5bb220883545de0f530476d3a94 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_nearley/grammars/include_unicode.ne @@ -0,0 +1,3 @@ +@include "unicode.ne" + +main -> x diff --git a/testbed/lark-parser__lark/tests/test_nearley/grammars/unicode.ne b/testbed/lark-parser__lark/tests/test_nearley/grammars/unicode.ne new file mode 100644 index 0000000000000000000000000000000000000000..c930830d620549d9a6c35a6a13c96a0182954759 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_nearley/grammars/unicode.ne @@ -0,0 +1 @@ +x -> "±a" diff --git a/testbed/lark-parser__lark/tests/test_nearley/test_nearley.py b/testbed/lark-parser__lark/tests/test_nearley/test_nearley.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad64497741222f7ed60832aa6a1d2d7877c36ff --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_nearley/test_nearley.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import unittest +import logging +import os +import codecs + +from lark import logger +from lark.tools.nearley import create_code_for_nearley_grammar, main as nearley_tool_main + +logger.setLevel(logging.INFO) + +TEST_PATH = os.path.abspath(os.path.dirname(__file__)) +NEARLEY_PATH = os.path.join(TEST_PATH, 'nearley') +BUILTIN_PATH = os.path.join(NEARLEY_PATH, 'builtin') + +if not os.path.exists(NEARLEY_PATH): + logger.warn("Nearley not installed. Skipping Nearley tests!") + raise ImportError("Skipping Nearley tests!") + +import js2py # Ensures that js2py exists, to avoid failing tests + + +class TestNearley(unittest.TestCase): + def test_css(self): + fn = os.path.join(NEARLEY_PATH, 'examples/csscolor.ne') + with open(fn) as f: + grammar = f.read() + + code = create_code_for_nearley_grammar(grammar, 'csscolor', BUILTIN_PATH, os.path.dirname(fn)) + d = {} + exec (code, d) + parse = d['parse'] + + c = parse('#a199ff') + assert c['r'] == 161 + assert c['g'] == 153 + assert c['b'] == 255 + + c = parse('rgb(255, 70%, 3)') + assert c['r'] == 255 + assert c['g'] == 178 + assert c['b'] == 3 + + def test_include(self): + fn = os.path.join(NEARLEY_PATH, 'test/grammars/folder-test.ne') + with open(fn) as f: + grammar = f.read() + + code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, os.path.dirname(fn)) + d = {} + exec (code, d) + parse = d['parse'] + + parse('a') + parse('b') + + def test_multi_include(self): + fn = os.path.join(NEARLEY_PATH, 'test/grammars/multi-include-test.ne') + with open(fn) as f: + grammar = f.read() + + code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, os.path.dirname(fn)) + d = {} + exec (code, d) + parse = d['parse'] + + parse('a') + parse('b') + parse('c') + + def test_utf8(self): + grammar = u'main -> "±a"' + code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, './') + d = {} + exec (code, d) + parse = d['parse'] + + parse(u'±a') + + def test_backslash(self): + grammar = r'main -> "\""' + code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, './') + d = {} + exec (code, d) + parse = d['parse'] + parse(u'"') + + def test_null(self): + grammar = r'main -> "a" | null' + code = create_code_for_nearley_grammar(grammar, 'main', BUILTIN_PATH, './') + d = {} + exec (code, d) + parse = d['parse'] + parse('a') + parse('') + + def test_utf8_2(self): + fn = os.path.join(TEST_PATH, 'grammars/unicode.ne') + nearley_tool_main(fn, 'x', NEARLEY_PATH) + + def test_include_utf8(self): + fn = os.path.join(TEST_PATH, 'grammars/include_unicode.ne') + nearley_tool_main(fn, 'main', NEARLEY_PATH) + + +if __name__ == '__main__': + unittest.main() diff --git a/testbed/lark-parser__lark/tests/test_parser.py b/testbed/lark-parser__lark/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c38b81e5602e3d4a75f7e757003a97e795a029a0 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_parser.py @@ -0,0 +1,2228 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import re +import unittest +import logging +import os +import sys +from copy import copy, deepcopy + +from lark.utils import Py36, isascii + +from lark import Token + +try: + from cStringIO import StringIO as cStringIO +except ImportError: + # Available only in Python 2.x, 3.x only has io.StringIO from below + cStringIO = None +from io import ( + StringIO as uStringIO, + BytesIO, + open, + ) + + +try: + import regex +except ImportError: + regex = None + +from lark import logger +from lark.lark import Lark +from lark.exceptions import GrammarError, ParseError, UnexpectedToken, UnexpectedInput, UnexpectedCharacters +from lark.tree import Tree +from lark.visitors import Transformer, Transformer_InPlace, v_args +from lark.grammar import Rule +from lark.lexer import TerminalDef, Lexer, TraditionalLexer + +logger.setLevel(logging.INFO) + + +__path__ = os.path.dirname(__file__) +def _read(n, *args): + with open(os.path.join(__path__, n), *args) as f: + return f.read() + +class TestParsers(unittest.TestCase): + def test_big_list(self): + Lark(r""" + start: {} + """.format( + "|".join(['"%s"'%i for i in range(250)]) + )) + + def test_same_ast(self): + "Tests that Earley and LALR parsers produce equal trees" + g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")" + name_list: NAME | name_list "," NAME + NAME: /\w+/ """, parser='lalr') + l = g.parse('(a,b,c,*x)') + + g = Lark(r"""start: "(" name_list ("," "*" NAME)? ")" + name_list: NAME | name_list "," NAME + NAME: /\w/+ """) + l2 = g.parse('(a,b,c,*x)') + assert l == l2, '%s != %s' % (l.pretty(), l2.pretty()) + + def test_infinite_recurse(self): + g = """start: a + a: a | "a" + """ + + self.assertRaises(GrammarError, Lark, g, parser='lalr') + + # TODO: should it? shouldn't it? + # l = Lark(g, parser='earley', lexer='dynamic') + # self.assertRaises(ParseError, l.parse, 'a') + + def test_propagate_positions(self): + g = Lark("""start: a + a: "a" + """, propagate_positions=True) + + r = g.parse('a') + self.assertEqual( r.children[0].meta.line, 1 ) + + g = Lark("""start: x + x: a + a: "a" + """, propagate_positions=True) + + r = g.parse('a') + self.assertEqual( r.children[0].meta.line, 1 ) + + def test_expand1(self): + + g = Lark("""start: a + ?a: b + b: "x" + """) + + r = g.parse('x') + self.assertEqual( r.children[0].data, "b" ) + + g = Lark("""start: a + ?a: b -> c + b: "x" + """) + + r = g.parse('x') + self.assertEqual( r.children[0].data, "c" ) + + g = Lark("""start: a + ?a: B -> c + B: "x" + """) + self.assertEqual( r.children[0].data, "c" ) + + + g = Lark("""start: a + ?a: b b -> c + b: "x" + """) + r = g.parse('xx') + self.assertEqual( r.children[0].data, "c" ) + + def test_comment_in_rule_definition(self): + g = Lark("""start: a + a: "a" + // A comment + // Another comment + | "b" + // Still more + + c: "unrelated" + """) + r = g.parse('b') + self.assertEqual( r.children[0].data, "a" ) + + def test_visit_tokens(self): + class T(Transformer): + def a(self, children): + return children[0] + "!" + def A(self, tok): + return tok.update(value=tok.upper()) + + # Test regular + g = """start: a + a : A + A: "x" + """ + p = Lark(g, parser='lalr') + r = T(False).transform(p.parse("x")) + self.assertEqual( r.children, ["x!"] ) + r = T().transform(p.parse("x")) + self.assertEqual( r.children, ["X!"] ) + + # Test internal transformer + p = Lark(g, parser='lalr', transformer=T()) + r = p.parse("x") + self.assertEqual( r.children, ["X!"] ) + + def test_vargs_meta(self): + + @v_args(meta=True) + class T1(Transformer): + def a(self, children, meta): + assert not children + return meta.line + + def start(self, children, meta): + return children + + @v_args(meta=True, inline=True) + class T2(Transformer): + def a(self, meta): + return meta.line + + def start(self, meta, *res): + return list(res) + + for T in (T1, T2): + for internal in [False, True]: + try: + g = Lark(r"""start: a+ + a : "x" _NL? + _NL: /\n/+ + """, parser='lalr', transformer=T() if internal else None, propagate_positions=True) + except NotImplementedError: + assert internal + continue + + res = g.parse("xx\nx\nxxx\n\n\nxx") + assert not internal + res = T().transform(res) + + self.assertEqual(res, [1, 1, 2, 3, 3, 3, 6, 6]) + + def test_vargs_tree(self): + tree = Lark(''' + start: a a a + !a: "A" + ''').parse('AAA') + tree_copy = deepcopy(tree) + + @v_args(tree=True) + class T(Transformer): + def a(self, tree): + return 1 + def start(self, tree): + return tree.children + + res = T().transform(tree) + self.assertEqual(res, [1, 1, 1]) + self.assertEqual(tree, tree_copy) + + + + def test_embedded_transformer(self): + class T(Transformer): + def a(self, children): + return "" + def b(self, children): + return "" + def c(self, children): + return "" + + # Test regular + g = Lark("""start: a + a : "x" + """, parser='lalr') + r = T().transform(g.parse("x")) + self.assertEqual( r.children, [""] ) + + + g = Lark("""start: a + a : "x" + """, parser='lalr', transformer=T()) + r = g.parse("x") + self.assertEqual( r.children, [""] ) + + + # Test Expand1 + g = Lark("""start: a + ?a : b + b : "x" + """, parser='lalr') + r = T().transform(g.parse("x")) + self.assertEqual( r.children, [""] ) + + + g = Lark("""start: a + ?a : b + b : "x" + """, parser='lalr', transformer=T()) + r = g.parse("x") + self.assertEqual( r.children, [""] ) + + # Test Expand1 -> Alias + g = Lark("""start: a + ?a : b b -> c + b : "x" + """, parser='lalr') + r = T().transform(g.parse("xx")) + self.assertEqual( r.children, [""] ) + + + g = Lark("""start: a + ?a : b b -> c + b : "x" + """, parser='lalr', transformer=T()) + r = g.parse("xx") + self.assertEqual( r.children, [""] ) + + def test_embedded_transformer_inplace(self): + @v_args(tree=True) + class T1(Transformer_InPlace): + def a(self, tree): + assert isinstance(tree, Tree), tree + tree.children.append("tested") + return tree + + def b(self, tree): + return Tree(tree.data, tree.children + ['tested2']) + + @v_args(tree=True) + class T2(Transformer): + def a(self, tree): + assert isinstance(tree, Tree), tree + tree.children.append("tested") + return tree + + def b(self, tree): + return Tree(tree.data, tree.children + ['tested2']) + + class T3(Transformer): + @v_args(tree=True) + def a(self, tree): + assert isinstance(tree, Tree) + tree.children.append("tested") + return tree + + @v_args(tree=True) + def b(self, tree): + return Tree(tree.data, tree.children + ['tested2']) + + for t in [T1(), T2(), T3()]: + for internal in [False, True]: + g = Lark("""start: a b + a : "x" + b : "y" + """, parser='lalr', transformer=t if internal else None) + r = g.parse("xy") + if not internal: + r = t.transform(r) + + a, b = r.children + self.assertEqual(a.children, ["tested"]) + self.assertEqual(b.children, ["tested2"]) + + def test_alias(self): + Lark("""start: ["a"] "b" ["c"] "e" ["f"] ["g"] ["h"] "x" -> d """) + + + +def _make_full_earley_test(LEXER): + def _Lark(grammar, **kwargs): + return Lark(grammar, lexer=LEXER, parser='earley', propagate_positions=True, **kwargs) + class _TestFullEarley(unittest.TestCase): + def test_anon(self): + # Fails an Earley implementation without special handling for empty rules, + # or re-processing of already completed rules. + g = Lark(r"""start: B + B: ("ab"|/[^b]/)+ + """, lexer=LEXER) + + self.assertEqual( g.parse('abc').children[0], 'abc') + + def test_earley(self): + g = Lark("""start: A "b" c + A: "a"+ + c: "abc" + """, parser="earley", lexer=LEXER) + x = g.parse('aaaababc') + + def test_earley2(self): + grammar = """ + start: statement+ + + statement: "r" + | "c" /[a-z]/+ + + %ignore " " + """ + + program = """c b r""" + + l = Lark(grammar, parser='earley', lexer=LEXER) + l.parse(program) + + + @unittest.skipIf(LEXER=='dynamic', "Only relevant for the dynamic_complete parser") + def test_earley3(self): + """Tests prioritization and disambiguation for pseudo-terminals (there should be only one result) + + By default, `+` should immitate regexp greedy-matching + """ + grammar = """ + start: A A + A: "a"+ + """ + + l = Lark(grammar, parser='earley', lexer=LEXER) + res = l.parse("aaa") + self.assertEqual(set(res.children), {'aa', 'a'}) + # XXX TODO fix Earley to maintain correct order + # i.e. terminals it imitate greedy search for terminals, but lazy search for rules + # self.assertEqual(res.children, ['aa', 'a']) + + def test_earley4(self): + grammar = """ + start: A A? + A: "a"+ + """ + + l = Lark(grammar, parser='earley', lexer=LEXER) + res = l.parse("aaa") + assert set(res.children) == {'aa', 'a'} or res.children == ['aaa'] + # XXX TODO fix Earley to maintain correct order + # i.e. terminals it imitate greedy search for terminals, but lazy search for rules + # self.assertEqual(res.children, ['aaa']) + + def test_earley_repeating_empty(self): + # This was a sneaky bug! + + grammar = """ + !start: "a" empty empty "b" + empty: empty2 + empty2: + """ + + parser = Lark(grammar, parser='earley', lexer=LEXER) + res = parser.parse('ab') + + empty_tree = Tree('empty', [Tree('empty2', [])]) + self.assertSequenceEqual(res.children, ['a', empty_tree, empty_tree, 'b']) + + @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer") + def test_earley_explicit_ambiguity(self): + # This was a sneaky bug! + + grammar = """ + start: a b | ab + a: "a" + b: "b" + ab: "ab" + """ + + parser = Lark(grammar, parser='earley', lexer=LEXER, ambiguity='explicit') + ambig_tree = parser.parse('ab') + self.assertEqual( ambig_tree.data, '_ambig') + self.assertEqual( len(ambig_tree.children), 2) + + @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer") + def test_ambiguity1(self): + grammar = """ + start: cd+ "e" + + !cd: "c" + | "d" + | "cd" + + """ + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse('cde') + + assert ambig_tree.data == '_ambig', ambig_tree + assert len(ambig_tree.children) == 2 + + @unittest.skipIf(LEXER=='standard', "Requires dynamic lexer") + def test_ambiguity2(self): + grammar = """ + ANY: /[a-zA-Z0-9 ]+/ + a.2: "A" b+ + b.2: "B" + c: ANY + + start: (a|c)* + """ + l = Lark(grammar, parser='earley', lexer=LEXER) + res = l.parse('ABX') + expected = Tree('start', [ + Tree('a', [ + Tree('b', []) + ]), + Tree('c', [ + 'X' + ]) + ]) + self.assertEqual(res, expected) + + def test_ambiguous_intermediate_node(self): + grammar = """ + start: ab bc d? + !ab: "A" "B"? + !bc: "B"? "C" + !d: "D" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCD") + expected = { + Tree('start', [Tree('ab', ['A']), Tree('bc', ['B', 'C']), Tree('d', ['D'])]), + Tree('start', [Tree('ab', ['A', 'B']), Tree('bc', ['C']), Tree('d', ['D'])]) + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_ambiguous_symbol_and_intermediate_nodes(self): + grammar = """ + start: ab bc cd + !ab: "A" "B"? + !bc: "B"? "C"? + !cd: "C"? "D" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCD") + expected = { + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', ['C']), + Tree('cd', ['D']) + ]), + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', []), + Tree('cd', ['C', 'D']) + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B', 'C']), + Tree('cd', ['D']) + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B']), + Tree('cd', ['C', 'D']) + ]), + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_nested_ambiguous_intermediate_nodes(self): + grammar = """ + start: ab bc cd e? + !ab: "A" "B"? + !bc: "B"? "C"? + !cd: "C"? "D" + !e: "E" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCDE") + expected = { + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', ['C']), + Tree('cd', ['D']), + Tree('e', ['E']) + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B', 'C']), + Tree('cd', ['D']), + Tree('e', ['E']) + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B']), + Tree('cd', ['C', 'D']), + Tree('e', ['E']) + ]), + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', []), + Tree('cd', ['C', 'D']), + Tree('e', ['E']) + ]), + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_nested_ambiguous_intermediate_nodes2(self): + grammar = """ + start: ab bc cd de f + !ab: "A" "B"? + !bc: "B"? "C"? + !cd: "C"? "D"? + !de: "D"? "E" + !f: "F" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCDEF") + expected = { + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', ['C']), + Tree('cd', ['D']), + Tree('de', ['E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B', 'C']), + Tree('cd', ['D']), + Tree('de', ['E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B']), + Tree('cd', ['C', 'D']), + Tree('de', ['E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B']), + Tree('cd', ['C']), + Tree('de', ['D', 'E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A', "B"]), + Tree('bc', []), + Tree('cd', ['C']), + Tree('de', ['D', 'E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A']), + Tree('bc', ['B', 'C']), + Tree('cd', []), + Tree('de', ['D', 'E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', []), + Tree('cd', ['C', 'D']), + Tree('de', ['E']), + Tree('f', ['F']), + ]), + Tree('start', [ + Tree('ab', ['A', 'B']), + Tree('bc', ['C']), + Tree('cd', []), + Tree('de', ['D', 'E']), + Tree('f', ['F']), + ]), + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_ambiguous_intermediate_node_unnamed_token(self): + grammar = """ + start: ab bc "D" + !ab: "A" "B"? + !bc: "B"? "C" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCD") + expected = { + Tree('start', [Tree('ab', ['A']), Tree('bc', ['B', 'C'])]), + Tree('start', [Tree('ab', ['A', 'B']), Tree('bc', ['C'])]) + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_ambiguous_intermediate_node_inlined_rule(self): + grammar = """ + start: ab _bc d? + !ab: "A" "B"? + _bc: "B"? "C" + !d: "D" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCD") + expected = { + Tree('start', [Tree('ab', ['A']), Tree('d', ['D'])]), + Tree('start', [Tree('ab', ['A', 'B']), Tree('d', ['D'])]) + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_ambiguous_intermediate_node_conditionally_inlined_rule(self): + grammar = """ + start: ab bc d? + !ab: "A" "B"? + !?bc: "B"? "C" + !d: "D" + """ + + l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER) + ambig_tree = l.parse("ABCD") + expected = { + Tree('start', [Tree('ab', ['A']), Tree('bc', ['B', 'C']), Tree('d', ['D'])]), + Tree('start', [Tree('ab', ['A', 'B']), 'C', Tree('d', ['D'])]) + } + self.assertEqual(ambig_tree.data, '_ambig') + self.assertEqual(set(ambig_tree.children), expected) + + def test_fruitflies_ambig(self): + grammar = """ + start: noun verb noun -> simple + | noun verb "like" noun -> comparative + + noun: adj? NOUN + verb: VERB + adj: ADJ + + NOUN: "flies" | "bananas" | "fruit" + VERB: "like" | "flies" + ADJ: "fruit" + + %import common.WS + %ignore WS + """ + parser = Lark(grammar, ambiguity='explicit', lexer=LEXER) + tree = parser.parse('fruit flies like bananas') + + expected = Tree('_ambig', [ + Tree('comparative', [ + Tree('noun', ['fruit']), + Tree('verb', ['flies']), + Tree('noun', ['bananas']) + ]), + Tree('simple', [ + Tree('noun', [Tree('adj', ['fruit']), 'flies']), + Tree('verb', ['like']), + Tree('noun', ['bananas']) + ]) + ]) + + # self.assertEqual(tree, expected) + self.assertEqual(tree.data, expected.data) + self.assertEqual(set(tree.children), set(expected.children)) + + + @unittest.skipIf(LEXER!='dynamic_complete', "Only relevant for the dynamic_complete parser") + def test_explicit_ambiguity2(self): + grammar = r""" + start: NAME+ + NAME: /\w+/ + %ignore " " + """ + text = """cat""" + + parser = _Lark(grammar, start='start', ambiguity='explicit') + tree = parser.parse(text) + self.assertEqual(tree.data, '_ambig') + + combinations = {tuple(str(s) for s in t.children) for t in tree.children} + self.assertEqual(combinations, { + ('cat',), + ('ca', 't'), + ('c', 'at'), + ('c', 'a' ,'t') + }) + + def test_term_ambig_resolve(self): + grammar = r""" + !start: NAME+ + NAME: /\w+/ + %ignore " " + """ + text = """foo bar""" + + parser = Lark(grammar) + tree = parser.parse(text) + self.assertEqual(tree.children, ['foo', 'bar']) + + + + + + + # @unittest.skipIf(LEXER=='dynamic', "Not implemented in Dynamic Earley yet") # TODO + # def test_not_all_derivations(self): + # grammar = """ + # start: cd+ "e" + + # !cd: "c" + # | "d" + # | "cd" + + # """ + # l = Lark(grammar, parser='earley', ambiguity='explicit', lexer=LEXER, earley__all_derivations=False) + # x = l.parse('cde') + # assert x.data != '_ambig', x + # assert len(x.children) == 1 + + _NAME = "TestFullEarley" + LEXER.capitalize() + _TestFullEarley.__name__ = _NAME + globals()[_NAME] = _TestFullEarley + +class CustomLexer(Lexer): + """ + Purpose of this custom lexer is to test the integration, + so it uses the traditionalparser as implementation without custom lexing behaviour. + """ + def __init__(self, lexer_conf): + self.lexer = TraditionalLexer(copy(lexer_conf)) + def lex(self, *args, **kwargs): + return self.lexer.lex(*args, **kwargs) + +def _tree_structure_check(a, b): + """ + Checks that both Tree objects have the same structure, without checking their values. + """ + assert a.data == b.data and len(a.children) == len(b.children) + for ca,cb in zip(a.children, b.children): + assert type(ca) == type(cb) + if isinstance(ca, Tree): + _tree_structure_check(ca, cb) + elif isinstance(ca, Token): + assert ca.type == cb.type + else: + assert ca == cb + +class DualBytesLark: + """ + A helper class that wraps both a normal parser, and a parser for bytes. + It automatically transforms `.parse` calls for both lexer, returning the value from the text lexer + It always checks that both produce the same output/error + + NOTE: Not currently used, but left here for future debugging. + """ + + def __init__(self, g, *args, **kwargs): + self.text_lexer = Lark(g, *args, use_bytes=False, **kwargs) + g = self.text_lexer.grammar_source.lower() + if '\\u' in g or not isascii(g): + # Bytes re can't deal with uniode escapes + self.bytes_lark = None + else: + # Everything here should work, so use `use_bytes='force'` + self.bytes_lark = Lark(self.text_lexer.grammar_source, *args, use_bytes='force', **kwargs) + + def parse(self, text, start=None): + # TODO: Easy workaround, more complex checks would be beneficial + if not isascii(text) or self.bytes_lark is None: + return self.text_lexer.parse(text, start) + try: + rv = self.text_lexer.parse(text, start) + except Exception as e: + try: + self.bytes_lark.parse(text.encode(), start) + except Exception as be: + assert type(e) == type(be), "Parser with and without `use_bytes` raise different exceptions" + raise e + assert False, "Parser without `use_bytes` raises exception, with doesn't" + try: + bv = self.bytes_lark.parse(text.encode(), start) + except Exception as be: + assert False, "Parser without `use_bytes` doesn't raise an exception, with does" + _tree_structure_check(rv, bv) + return rv + + @classmethod + def open(cls, grammar_filename, rel_to=None, **options): + if rel_to: + basepath = os.path.dirname(rel_to) + grammar_filename = os.path.join(basepath, grammar_filename) + with open(grammar_filename, encoding='utf8') as f: + return cls(f, **options) + + def save(self,f): + self.text_lexer.save(f) + if self.bytes_lark is not None: + self.bytes_lark.save(f) + + def load(self,f): + self.text_lexer = self.text_lexer.load(f) + if self.bytes_lark is not None: + self.bytes_lark.load(f) + +def _make_parser_test(LEXER, PARSER): + lexer_class_or_name = CustomLexer if LEXER == 'custom' else LEXER + def _Lark(grammar, **kwargs): + return Lark(grammar, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs) + def _Lark_open(gfilename, **kwargs): + return Lark.open(gfilename, lexer=lexer_class_or_name, parser=PARSER, propagate_positions=True, **kwargs) + + class _TestParser(unittest.TestCase): + def test_basic1(self): + g = _Lark("""start: a+ b a* "b" a* + b: "b" + a: "a" + """) + + r = g.parse('aaabaab') + self.assertEqual( ''.join(x.data for x in r.children), 'aaabaa' ) + r = g.parse('aaabaaba') + self.assertEqual( ''.join(x.data for x in r.children), 'aaabaaa' ) + + self.assertRaises(ParseError, g.parse, 'aaabaa') + + def test_basic2(self): + # Multiple parsers and colliding tokens + g = _Lark("""start: B A + B: "12" + A: "1" """) + g2 = _Lark("""start: B A + B: "12" + A: "2" """) + x = g.parse('121') + assert x.data == 'start' and x.children == ['12', '1'], x + x = g2.parse('122') + assert x.data == 'start' and x.children == ['12', '2'], x + + + @unittest.skipIf(cStringIO is None, "cStringIO not available") + def test_stringio_bytes(self): + """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object""" + _Lark(cStringIO(b'start: a+ b a* "b" a*\n b: "b"\n a: "a" ')) + + def test_stringio_unicode(self): + """Verify that a Lark can be created from file-like objects other than Python's standard 'file' object""" + _Lark(uStringIO(u'start: a+ b a* "b" a*\n b: "b"\n a: "a" ')) + + def test_unicode(self): + g = _Lark(u"""start: UNIA UNIB UNIA + UNIA: /\xa3/ + UNIB: /\u0101/ + """) + g.parse(u'\xa3\u0101\u00a3') + + def test_unicode2(self): + g = _Lark(r"""start: UNIA UNIB UNIA UNIC + UNIA: /\xa3/ + UNIB: "a\u0101b\ " + UNIC: /a?\u0101c\n/ + """) + g.parse(u'\xa3a\u0101b\\ \u00a3\u0101c\n') + + def test_unicode3(self): + g = _Lark(r"""start: UNIA UNIB UNIA UNIC + UNIA: /\xa3/ + UNIB: "\u0101" + UNIC: /\u0203/ /\n/ + """) + g.parse(u'\xa3\u0101\u00a3\u0203\n') + + def test_hex_escape(self): + g = _Lark(r"""start: A B C + A: "\x01" + B: /\x02/ + C: "\xABCD" + """) + g.parse('\x01\x02\xABCD') + + def test_unicode_literal_range_escape(self): + g = _Lark(r"""start: A+ + A: "\u0061".."\u0063" + """) + g.parse('abc') + + def test_hex_literal_range_escape(self): + g = _Lark(r"""start: A+ + A: "\x01".."\x03" + """) + g.parse('\x01\x02\x03') + + @unittest.skipIf(sys.version_info[0]==2 or sys.version_info[:2]==(3, 4), + "bytes parser isn't perfect in Python2, exceptions don't work correctly") + def test_bytes_utf8(self): + g = r""" + start: BOM? char+ + BOM: "\xef\xbb\xbf" + char: CHAR1 | CHAR2 | CHAR3 | CHAR4 + CONTINUATION_BYTE: "\x80" .. "\xbf" + CHAR1: "\x00" .. "\x7f" + CHAR2: "\xc0" .. "\xdf" CONTINUATION_BYTE + CHAR3: "\xe0" .. "\xef" CONTINUATION_BYTE CONTINUATION_BYTE + CHAR4: "\xf0" .. "\xf7" CONTINUATION_BYTE CONTINUATION_BYTE CONTINUATION_BYTE + """ + g = _Lark(g, use_bytes=True) + s = u"🔣 地? gurīn".encode('utf-8') + self.assertEqual(len(g.parse(s).children), 10) + + for enc, j in [("sjis", u"地球の絵はグリーンでグッド? Chikyuu no e wa guriin de guddo"), + ("sjis", u"売春婦"), + ("euc-jp", u"乂鵬鵠")]: + s = j.encode(enc) + self.assertRaises(UnexpectedCharacters, g.parse, s) + + @unittest.skipIf(PARSER == 'cyk', "Takes forever") + def test_stack_for_ebnf(self): + """Verify that stack depth isn't an issue for EBNF grammars""" + g = _Lark(r"""start: a+ + a : "a" """) + + g.parse("a" * (sys.getrecursionlimit()*2 )) + + def test_expand1_lists_with_one_item(self): + g = _Lark(r"""start: list + ?list: item+ + item : A + A: "a" + """) + r = g.parse("a") + + # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item' + self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',)) + + # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule + self.assertEqual(len(r.children), 1) + + def test_expand1_lists_with_one_item_2(self): + g = _Lark(r"""start: list + ?list: item+ "!" + item : A + A: "a" + """) + r = g.parse("a!") + + # because 'list' is an expand-if-contains-one rule and we only provided one element it should have expanded to 'item' + self.assertSequenceEqual([subtree.data for subtree in r.children], ('item',)) + + # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule + self.assertEqual(len(r.children), 1) + + def test_dont_expand1_lists_with_multiple_items(self): + g = _Lark(r"""start: list + ?list: item+ + item : A + A: "a" + """) + r = g.parse("aa") + + # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule + self.assertEqual(len(r.children), 1) + + # Sanity check: verify that 'list' contains the two 'item's we've given it + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ('item', 'item')) + + def test_dont_expand1_lists_with_multiple_items_2(self): + g = _Lark(r"""start: list + ?list: item+ "!" + item : A + A: "a" + """) + r = g.parse("aa!") + + # because 'list' is an expand-if-contains-one rule and we've provided more than one element it should *not* have expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule + self.assertEqual(len(r.children), 1) + + # Sanity check: verify that 'list' contains the two 'item's we've given it + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ('item', 'item')) + + + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_empty_expand1_list(self): + g = _Lark(r"""start: list + ?list: item* + item : A + A: "a" + """) + r = g.parse("") + + # because 'list' is an expand-if-contains-one rule and we've provided less than one element (i.e. none) it should *not* have expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule + self.assertEqual(len(r.children), 1) + + # Sanity check: verify that 'list' contains no 'item's as we've given it none + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ()) + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_empty_expand1_list_2(self): + g = _Lark(r"""start: list + ?list: item* "!"? + item : A + A: "a" + """) + r = g.parse("") + + # because 'list' is an expand-if-contains-one rule and we've provided less than one element (i.e. none) it should *not* have expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # regardless of the amount of items: there should be only *one* child in 'start' because 'list' isn't an expand-all rule + self.assertEqual(len(r.children), 1) + + # Sanity check: verify that 'list' contains no 'item's as we've given it none + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ()) + + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_empty_flatten_list(self): + g = _Lark(r"""start: list + list: | item "," list + item : A + A: "a" + """) + r = g.parse("") + + # Because 'list' is a flatten rule it's top-level element should *never* be expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # Sanity check: verify that 'list' contains no 'item's as we've given it none + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ()) + + @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)") + def test_single_item_flatten_list(self): + g = _Lark(r"""start: list + list: | item "," list + item : A + A: "a" + """) + r = g.parse("a,") + + # Because 'list' is a flatten rule it's top-level element should *never* be expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # Sanity check: verify that 'list' contains exactly the one 'item' we've given it + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ('item',)) + + @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)") + def test_multiple_item_flatten_list(self): + g = _Lark(r"""start: list + #list: | item "," list + item : A + A: "a" + """) + r = g.parse("a,a,") + + # Because 'list' is a flatten rule it's top-level element should *never* be expanded + self.assertSequenceEqual([subtree.data for subtree in r.children], ('list',)) + + # Sanity check: verify that 'list' contains exactly the two 'item's we've given it + [list] = r.children + self.assertSequenceEqual([item.data for item in list.children], ('item', 'item')) + + @unittest.skipIf(True, "Flattening list isn't implemented (and may never be)") + def test_recurse_flatten(self): + """Verify that stack depth doesn't get exceeded on recursive rules marked for flattening.""" + g = _Lark(r"""start: a | start a + a : A + A : "a" """) + + # Force PLY to write to the debug log, but prevent writing it to the terminal (uses repr() on the half-built + # STree data structures, which uses recursion). + g.parse("a" * (sys.getrecursionlimit() // 4)) + + def test_token_collision(self): + g = _Lark(r"""start: "Hello" NAME + NAME: /\w/+ + %ignore " " + """) + x = g.parse('Hello World') + self.assertSequenceEqual(x.children, ['World']) + x = g.parse('Hello HelloWorld') + self.assertSequenceEqual(x.children, ['HelloWorld']) + + def test_token_collision_WS(self): + g = _Lark(r"""start: "Hello" NAME + NAME: /\w/+ + %import common.WS + %ignore WS + """) + x = g.parse('Hello World') + self.assertSequenceEqual(x.children, ['World']) + x = g.parse('Hello HelloWorld') + self.assertSequenceEqual(x.children, ['HelloWorld']) + + def test_token_collision2(self): + g = _Lark(""" + !start: "starts" + + %import common.LCASE_LETTER + """) + + x = g.parse("starts") + self.assertSequenceEqual(x.children, ['starts']) + + def test_templates(self): + g = _Lark(r""" + start: "[" sep{NUMBER, ","} "]" + sep{item, delim}: item (delim item)* + NUMBER: /\d+/ + %ignore " " + """) + x = g.parse("[1, 2, 3, 4]") + self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])]) + x = g.parse("[1]") + self.assertSequenceEqual(x.children, [Tree('sep', ['1'])]) + + def test_templates_recursion(self): + g = _Lark(r""" + start: "[" _sep{NUMBER, ","} "]" + _sep{item, delim}: item | _sep{item, delim} delim item + NUMBER: /\d+/ + %ignore " " + """) + x = g.parse("[1, 2, 3, 4]") + self.assertSequenceEqual(x.children, ['1', '2', '3', '4']) + x = g.parse("[1]") + self.assertSequenceEqual(x.children, ['1']) + + def test_templates_import(self): + g = _Lark_open("test_templates_import.lark", rel_to=__file__) + x = g.parse("[1, 2, 3, 4]") + self.assertSequenceEqual(x.children, [Tree('sep', ['1', '2', '3', '4'])]) + x = g.parse("[1]") + self.assertSequenceEqual(x.children, [Tree('sep', ['1'])]) + + def test_templates_alias(self): + g = _Lark(r""" + start: expr{"C"} + expr{t}: "A" t + | "B" t -> b + """) + x = g.parse("AC") + self.assertSequenceEqual(x.children, [Tree('expr', [])]) + x = g.parse("BC") + self.assertSequenceEqual(x.children, [Tree('b', [])]) + + def test_templates_modifiers(self): + g = _Lark(r""" + start: expr{"B"} + !expr{t}: "A" t + """) + x = g.parse("AB") + self.assertSequenceEqual(x.children, [Tree('expr', ["A", "B"])]) + g = _Lark(r""" + start: _expr{"B"} + !_expr{t}: "A" t + """) + x = g.parse("AB") + self.assertSequenceEqual(x.children, ["A", "B"]) + g = _Lark(r""" + start: expr{b} + b: "B" + ?expr{t}: "A" t + """) + x = g.parse("AB") + self.assertSequenceEqual(x.children, [Tree('b',[])]) + + def test_templates_templates(self): + g = _Lark('''start: a{b} + a{t}: t{"a"} + b{x}: x''') + x = g.parse('a') + self.assertSequenceEqual(x.children, [Tree('a', [Tree('b',[])])]) + + def test_g_regex_flags(self): + g = _Lark(""" + start: "a" /b+/ C + C: "C" | D + D: "D" E + E: "e" + """, g_regex_flags=re.I) + x1 = g.parse("ABBc") + x2 = g.parse("abdE") + + # def test_string_priority(self): + # g = _Lark("""start: (A | /a?bb/)+ + # A: "a" """) + # x = g.parse('abb') + # self.assertEqual(len(x.children), 2) + + # # This parse raises an exception because the lexer will always try to consume + # # "a" first and will never match the regular expression + # # This behavior is subject to change!! + # # Thie won't happen with ambiguity handling. + # g = _Lark("""start: (A | /a?ab/)+ + # A: "a" """) + # self.assertRaises(LexError, g.parse, 'aab') + + def test_undefined_rule(self): + self.assertRaises(GrammarError, _Lark, """start: a""") + + def test_undefined_token(self): + self.assertRaises(GrammarError, _Lark, """start: A""") + + def test_rule_collision(self): + g = _Lark("""start: "a"+ "b" + | "a"+ """) + x = g.parse('aaaa') + x = g.parse('aaaab') + + def test_rule_collision2(self): + g = _Lark("""start: "a"* "b" + | "a"+ """) + x = g.parse('aaaa') + x = g.parse('aaaab') + x = g.parse('b') + + def test_token_not_anon(self): + """Tests that "a" is matched as an anonymous token, and not A. + """ + + g = _Lark("""start: "a" + A: "a" """) + x = g.parse('a') + self.assertEqual(len(x.children), 0, '"a" should be considered anonymous') + + g = _Lark("""start: "a" A + A: "a" """) + x = g.parse('aa') + self.assertEqual(len(x.children), 1, 'only "a" should be considered anonymous') + self.assertEqual(x.children[0].type, "A") + + g = _Lark("""start: /a/ + A: /a/ """) + x = g.parse('a') + self.assertEqual(len(x.children), 1) + self.assertEqual(x.children[0].type, "A", "A isn't associated with /a/") + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_maybe(self): + g = _Lark("""start: ["a"] """) + x = g.parse('a') + x = g.parse('') + + def test_start(self): + g = _Lark("""a: "a" a? """, start='a') + x = g.parse('a') + x = g.parse('aa') + x = g.parse('aaa') + + def test_alias(self): + g = _Lark("""start: "a" -> b """) + x = g.parse('a') + self.assertEqual(x.data, "b") + + def test_token_ebnf(self): + g = _Lark("""start: A + A: "a"* ("b"? "c".."e")+ + """) + x = g.parse('abcde') + x = g.parse('dd') + + def test_backslash(self): + g = _Lark(r"""start: "\\" "a" + """) + x = g.parse(r'\a') + + g = _Lark(r"""start: /\\/ /a/ + """) + x = g.parse(r'\a') + + + def test_backslash2(self): + g = _Lark(r"""start: "\"" "-" + """) + x = g.parse('"-') + + g = _Lark(r"""start: /\// /-/ + """) + x = g.parse('/-') + + + + def test_special_chars(self): + g = _Lark(r"""start: "\n" + """) + x = g.parse('\n') + + g = _Lark(r"""start: /\n/ + """) + x = g.parse('\n') + + + # def test_token_recurse(self): + # g = _Lark("""start: A + # A: B + # B: A + # """) + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_empty(self): + # Fails an Earley implementation without special handling for empty rules, + # or re-processing of already completed rules. + g = _Lark(r"""start: _empty a "B" + a: _empty "A" + _empty: + """) + x = g.parse('AB') + + def test_regex_quote(self): + g = r""" + start: SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING + SINGLE_QUOTED_STRING : /'[^']*'/ + DOUBLE_QUOTED_STRING : /"[^"]*"/ + """ + + g = _Lark(g) + self.assertEqual( g.parse('"hello"').children, ['"hello"']) + self.assertEqual( g.parse("'hello'").children, ["'hello'"]) + + @unittest.skipIf(not Py36, "Required re syntax only exists in python3.6+") + def test_join_regex_flags(self): + g = r""" + start: A + A: B C + B: /./s + C: /./ + """ + g = _Lark(g) + self.assertEqual(g.parse(" ").children,[" "]) + self.assertEqual(g.parse("\n ").children,["\n "]) + self.assertRaises(UnexpectedCharacters, g.parse, "\n\n") + + g = r""" + start: A + A: B | C + B: "b"i + C: "c" + """ + g = _Lark(g) + self.assertEqual(g.parse("b").children,["b"]) + self.assertEqual(g.parse("B").children,["B"]) + self.assertEqual(g.parse("c").children,["c"]) + self.assertRaises(UnexpectedCharacters, g.parse, "C") + + + def test_lexer_token_limit(self): + "Python has a stupid limit of 100 groups in a regular expression. Test that we handle this limitation" + tokens = {'A%d'%i:'"%d"'%i for i in range(300)} + g = _Lark("""start: %s + %s""" % (' '.join(tokens), '\n'.join("%s: %s"%x for x in tokens.items()))) + + def test_float_without_lexer(self): + expected_error = UnexpectedCharacters if LEXER.startswith('dynamic') else UnexpectedToken + if PARSER == 'cyk': + expected_error = ParseError + + g = _Lark("""start: ["+"|"-"] float + float: digit* "." digit+ exp? + | digit+ exp + exp: ("e"|"E") ["+"|"-"] digit+ + digit: "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9" + """) + g.parse("1.2") + g.parse("-.2e9") + g.parse("+2e-9") + self.assertRaises( expected_error, g.parse, "+2e-9e") + + def test_keep_all_tokens(self): + l = _Lark("""start: "a"+ """, keep_all_tokens=True) + tree = l.parse('aaa') + self.assertEqual(tree.children, ['a', 'a', 'a']) + + + def test_token_flags(self): + l = _Lark("""!start: "a"i+ + """ + ) + tree = l.parse('aA') + self.assertEqual(tree.children, ['a', 'A']) + + l = _Lark("""!start: /a/i+ + """ + ) + tree = l.parse('aA') + self.assertEqual(tree.children, ['a', 'A']) + + # g = """!start: "a"i "a" + # """ + # self.assertRaises(GrammarError, _Lark, g) + + # g = """!start: /a/i /a/ + # """ + # self.assertRaises(GrammarError, _Lark, g) + + g = """start: NAME "," "a" + NAME: /[a-z_]/i /[a-z0-9_]/i* + """ + l = _Lark(g) + tree = l.parse('ab,a') + self.assertEqual(tree.children, ['ab']) + tree = l.parse('AB,a') + self.assertEqual(tree.children, ['AB']) + + def test_token_flags3(self): + l = _Lark("""!start: ABC+ + ABC: "abc"i + """ + ) + tree = l.parse('aBcAbC') + self.assertEqual(tree.children, ['aBc', 'AbC']) + + def test_token_flags2(self): + g = """!start: ("a"i | /a/ /b/?)+ + """ + l = _Lark(g) + tree = l.parse('aA') + self.assertEqual(tree.children, ['a', 'A']) + + def test_token_flags_verbose(self): + g = _Lark(r"""start: NL | ABC + ABC: / [a-z] /x + NL: /\n/ + """) + x = g.parse('a') + self.assertEqual(x.children, ['a']) + + def test_token_flags_verbose_multiline(self): + g = _Lark(r"""start: ABC + ABC: / a b c + d + e f + /x + """) + x = g.parse('abcdef') + self.assertEqual(x.children, ['abcdef']) + + def test_token_multiline_only_works_with_x_flag(self): + g = r"""start: ABC + ABC: / a b c + d + e f + /i + """ + self.assertRaises( GrammarError, _Lark, g) + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_twice_empty(self): + g = """!start: ("A"?)? + """ + l = _Lark(g) + tree = l.parse('A') + self.assertEqual(tree.children, ['A']) + + tree = l.parse('') + self.assertEqual(tree.children, []) + + def test_undefined_ignore(self): + g = """!start: "A" + + %ignore B + """ + self.assertRaises( GrammarError, _Lark, g) + + def test_alias_in_terminal(self): + g = """start: TERM + TERM: "a" -> alias + """ + self.assertRaises( GrammarError, _Lark, g) + + def test_line_and_column(self): + g = r"""!start: "A" bc "D" + !bc: "B\nC" + """ + l = _Lark(g) + a, bc, d = l.parse("AB\nCD").children + self.assertEqual(a.line, 1) + self.assertEqual(a.column, 1) + + bc ,= bc.children + self.assertEqual(bc.line, 1) + self.assertEqual(bc.column, 2) + + self.assertEqual(d.line, 2) + self.assertEqual(d.column, 2) + + if LEXER != 'dynamic': + self.assertEqual(a.end_line, 1) + self.assertEqual(a.end_column, 2) + self.assertEqual(bc.end_line, 2) + self.assertEqual(bc.end_column, 2) + self.assertEqual(d.end_line, 2) + self.assertEqual(d.end_column, 3) + + + + def test_reduce_cycle(self): + """Tests an edge-condition in the LALR parser, in which a transition state looks exactly like the end state. + It seems that the correct solution is to explicitely distinguish finalization in the reduce() function. + """ + + l = _Lark(""" + term: A + | term term + + A: "a" + + """, start='term') + + tree = l.parse("aa") + self.assertEqual(len(tree.children), 2) + + + @unittest.skipIf(LEXER != 'standard', "Only standard lexers care about token priority") + def test_lexer_prioritization(self): + "Tests effect of priority on result" + + grammar = """ + start: A B | AB + A.2: "a" + B: "b" + AB: "ab" + """ + l = _Lark(grammar) + res = l.parse("ab") + + self.assertEqual(res.children, ['a', 'b']) + self.assertNotEqual(res.children, ['ab']) + + grammar = """ + start: A B | AB + A: "a" + B: "b" + AB.3: "ab" + """ + l = _Lark(grammar) + res = l.parse("ab") + + self.assertNotEqual(res.children, ['a', 'b']) + self.assertEqual(res.children, ['ab']) + + + grammar = """ + start: A B | AB + A: "a" + B.-20: "b" + AB.-10: "ab" + """ + l = _Lark(grammar) + res = l.parse("ab") + self.assertEqual(res.children, ['a', 'b']) + + + grammar = """ + start: A B | AB + A.-99999999999999999999999: "a" + B: "b" + AB: "ab" + """ + l = _Lark(grammar) + res = l.parse("ab") + + self.assertEqual(res.children, ['ab']) + + + + + + + def test_import(self): + grammar = """ + start: NUMBER WORD + + %import common.NUMBER + %import common.WORD + %import common.WS + %ignore WS + + """ + l = _Lark(grammar) + x = l.parse('12 elephants') + self.assertEqual(x.children, ['12', 'elephants']) + + + def test_import_rename(self): + grammar = """ + start: N W + + %import common.NUMBER -> N + %import common.WORD -> W + %import common.WS + %ignore WS + + """ + l = _Lark(grammar) + x = l.parse('12 elephants') + self.assertEqual(x.children, ['12', 'elephants']) + + + def test_relative_import(self): + l = _Lark_open('test_relative_import.lark', rel_to=__file__) + x = l.parse('12 lions') + self.assertEqual(x.children, ['12', 'lions']) + + + def test_relative_import_unicode(self): + l = _Lark_open('test_relative_import_unicode.lark', rel_to=__file__) + x = l.parse(u'Ø') + self.assertEqual(x.children, [u'Ø']) + + + def test_relative_import_rename(self): + l = _Lark_open('test_relative_import_rename.lark', rel_to=__file__) + x = l.parse('12 lions') + self.assertEqual(x.children, ['12', 'lions']) + + + def test_relative_rule_import(self): + l = _Lark_open('test_relative_rule_import.lark', rel_to=__file__) + x = l.parse('xaabby') + self.assertEqual(x.children, [ + 'x', + Tree('expr', ['a', Tree('expr', ['a', 'b']), 'b']), + 'y']) + + + def test_relative_rule_import_drop_ignore(self): + # %ignore rules are dropped on import + l = _Lark_open('test_relative_rule_import_drop_ignore.lark', + rel_to=__file__) + self.assertRaises((ParseError, UnexpectedInput), + l.parse, 'xa abby') + + + def test_relative_rule_import_subrule(self): + l = _Lark_open('test_relative_rule_import_subrule.lark', + rel_to=__file__) + x = l.parse('xaabby') + self.assertEqual(x.children, [ + 'x', + Tree('startab', [ + Tree('grammars__ab__expr', [ + 'a', Tree('grammars__ab__expr', ['a', 'b']), 'b', + ]), + ]), + 'y']) + + + def test_relative_rule_import_subrule_no_conflict(self): + l = _Lark_open( + 'test_relative_rule_import_subrule_no_conflict.lark', + rel_to=__file__) + x = l.parse('xaby') + self.assertEqual(x.children, [Tree('expr', [ + 'x', + Tree('startab', [ + Tree('grammars__ab__expr', ['a', 'b']), + ]), + 'y'])]) + self.assertRaises((ParseError, UnexpectedInput), + l.parse, 'xaxabyby') + + + def test_relative_rule_import_rename(self): + l = _Lark_open('test_relative_rule_import_rename.lark', + rel_to=__file__) + x = l.parse('xaabby') + self.assertEqual(x.children, [ + 'x', + Tree('ab', ['a', Tree('ab', ['a', 'b']), 'b']), + 'y']) + + + def test_multi_import(self): + grammar = """ + start: NUMBER WORD + + %import common (NUMBER, WORD, WS) + %ignore WS + + """ + l = _Lark(grammar) + x = l.parse('12 toucans') + self.assertEqual(x.children, ['12', 'toucans']) + + + def test_relative_multi_import(self): + l = _Lark_open("test_relative_multi_import.lark", rel_to=__file__) + x = l.parse('12 capybaras') + self.assertEqual(x.children, ['12', 'capybaras']) + + def test_relative_import_preserves_leading_underscore(self): + l = _Lark_open("test_relative_import_preserves_leading_underscore.lark", rel_to=__file__) + x = l.parse('Ax') + self.assertEqual(next(x.find_data('c')).children, ['A']) + + def test_relative_import_of_nested_grammar(self): + l = _Lark_open("grammars/test_relative_import_of_nested_grammar.lark", rel_to=__file__) + x = l.parse('N') + self.assertEqual(next(x.find_data('rule_to_import')).children, ['N']) + + def test_relative_import_rules_dependencies_imported_only_once(self): + l = _Lark_open("test_relative_import_rules_dependencies_imported_only_once.lark", rel_to=__file__) + x = l.parse('AAA') + self.assertEqual(next(x.find_data('a')).children, ['A']) + self.assertEqual(next(x.find_data('b')).children, ['A']) + self.assertEqual(next(x.find_data('d')).children, ['A']) + + def test_import_errors(self): + grammar = """ + start: NUMBER WORD + + %import .grammars.bad_test.NUMBER + """ + self.assertRaises(IOError, _Lark, grammar) + + grammar = """ + start: NUMBER WORD + + %import bad_test.NUMBER + """ + self.assertRaises(IOError, _Lark, grammar) + + @unittest.skipIf(LEXER=='dynamic', "%declare/postlex doesn't work with dynamic") + def test_postlex_declare(self): # Note: this test does a lot. maybe split it up? + class TestPostLexer: + def process(self, stream): + for t in stream: + if t.type == 'A': + t.type = 'B' + yield t + else: + yield t + + always_accept = ('A',) + + parser = _Lark(""" + start: B + A: "A" + %declare B + """, postlex=TestPostLexer()) + + test_file = "A" + tree = parser.parse(test_file) + self.assertEqual(tree.children, [Token('B', 'A')]) + + @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules") + def test_earley_prioritization(self): + "Tests effect of priority on result" + + grammar = """ + start: a | b + a.1: "a" + b.2: "a" + """ + + # l = Lark(grammar, parser='earley', lexer='standard') + l = _Lark(grammar) + res = l.parse("a") + self.assertEqual(res.children[0].data, 'b') + + grammar = """ + start: a | b + a.2: "a" + b.1: "a" + """ + + l = _Lark(grammar) + # l = Lark(grammar, parser='earley', lexer='standard') + res = l.parse("a") + self.assertEqual(res.children[0].data, 'a') + + + + @unittest.skipIf(PARSER != 'earley', "Currently only Earley supports priority in rules") + def test_earley_prioritization_sum(self): + "Tests effect of priority on result" + + grammar = """ + start: ab_ b_ a_ | indirection + indirection: a_ bb_ a_ + a_: "a" + b_: "b" + ab_: "ab" + bb_.1: "bb" + """ + + l = Lark(grammar, priority="invert") + res = l.parse('abba') + self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_') + + grammar = """ + start: ab_ b_ a_ | indirection + indirection: a_ bb_ a_ + a_: "a" + b_: "b" + ab_.1: "ab" + bb_: "bb" + """ + + l = Lark(grammar, priority="invert") + res = l.parse('abba') + self.assertEqual(''.join(child.data for child in res.children), 'indirection') + + grammar = """ + start: ab_ b_ a_ | indirection + indirection: a_ bb_ a_ + a_.2: "a" + b_.1: "b" + ab_.3: "ab" + bb_.3: "bb" + """ + + l = Lark(grammar, priority="invert") + res = l.parse('abba') + self.assertEqual(''.join(child.data for child in res.children), 'ab_b_a_') + + grammar = """ + start: ab_ b_ a_ | indirection + indirection: a_ bb_ a_ + a_.1: "a" + b_.1: "b" + ab_.4: "ab" + bb_.3: "bb" + """ + + l = Lark(grammar, priority="invert") + res = l.parse('abba') + self.assertEqual(''.join(child.data for child in res.children), 'indirection') + + + def test_utf8(self): + g = u"""start: a + a: "±a" + """ + l = _Lark(g) + self.assertEqual(l.parse(u'±a'), Tree('start', [Tree('a', [])])) + + g = u"""start: A + A: "±a" + """ + l = _Lark(g) + self.assertEqual(l.parse(u'±a'), Tree('start', [u'\xb1a'])) + + + + @unittest.skipIf(PARSER == 'cyk', "No empty rules") + def test_ignore(self): + grammar = r""" + COMMENT: /(!|(\/\/))[^\n]*/ + %ignore COMMENT + %import common.WS -> _WS + %import common.INT + start: "INT"i _WS+ INT _WS* + """ + + parser = _Lark(grammar) + + tree = parser.parse("int 1 ! This is a comment\n") + self.assertEqual(tree.children, ['1']) + + tree = parser.parse("int 1 ! This is a comment") # A trailing ignore token can be tricky! + self.assertEqual(tree.children, ['1']) + + parser = _Lark(r""" + start : "a"* + %ignore "b" + """) + tree = parser.parse("bb") + self.assertEqual(tree.children, []) + + + def test_regex_escaping(self): + g = _Lark("start: /[ab]/") + g.parse('a') + g.parse('b') + + self.assertRaises( UnexpectedInput, g.parse, 'c') + + _Lark(r'start: /\w/').parse('a') + + g = _Lark(r'start: /\\w/') + self.assertRaises( UnexpectedInput, g.parse, 'a') + g.parse(r'\w') + + _Lark(r'start: /\[/').parse('[') + + _Lark(r'start: /\//').parse('/') + + _Lark(r'start: /\\/').parse('\\') + + _Lark(r'start: /\[ab]/').parse('[ab]') + + _Lark(r'start: /\\[ab]/').parse('\\a') + + _Lark(r'start: /\t/').parse('\t') + + _Lark(r'start: /\\t/').parse('\\t') + + _Lark(r'start: /\\\t/').parse('\\\t') + + _Lark(r'start: "\t"').parse('\t') + + _Lark(r'start: "\\t"').parse('\\t') + + _Lark(r'start: "\\\t"').parse('\\\t') + + + def test_ranged_repeat_rules(self): + g = u"""!start: "A"~3 + """ + l = _Lark(g) + self.assertEqual(l.parse(u'AAA'), Tree('start', ["A", "A", "A"])) + self.assertRaises(ParseError, l.parse, u'AA') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA') + + + g = u"""!start: "A"~0..2 + """ + if PARSER != 'cyk': # XXX CYK currently doesn't support empty grammars + l = _Lark(g) + self.assertEqual(l.parse(u''), Tree('start', [])) + self.assertEqual(l.parse(u'A'), Tree('start', ['A'])) + self.assertEqual(l.parse(u'AA'), Tree('start', ['A', 'A'])) + self.assertRaises((UnexpectedToken, UnexpectedInput), l.parse, u'AAA') + + g = u"""!start: "A"~3..2 + """ + self.assertRaises(GrammarError, _Lark, g) + + g = u"""!start: "A"~2..3 "B"~2 + """ + l = _Lark(g) + self.assertEqual(l.parse(u'AABB'), Tree('start', ['A', 'A', 'B', 'B'])) + self.assertEqual(l.parse(u'AAABB'), Tree('start', ['A', 'A', 'A', 'B', 'B'])) + self.assertRaises(ParseError, l.parse, u'AAAB') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB') + + + def test_ranged_repeat_terms(self): + g = u"""!start: AAA + AAA: "A"~3 + """ + l = _Lark(g) + self.assertEqual(l.parse(u'AAA'), Tree('start', ["AAA"])) + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AA') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAA') + + g = u"""!start: AABB CC + AABB: "A"~0..2 "B"~2 + CC: "C"~1..2 + """ + l = _Lark(g) + self.assertEqual(l.parse(u'AABBCC'), Tree('start', ['AABB', 'CC'])) + self.assertEqual(l.parse(u'BBC'), Tree('start', ['BB', 'C'])) + self.assertEqual(l.parse(u'ABBCC'), Tree('start', ['ABB', 'CC'])) + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAB') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAABBB') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'ABB') + self.assertRaises((ParseError, UnexpectedInput), l.parse, u'AAAABB') + + @unittest.skipIf(PARSER=='earley', "Priority not handled correctly right now") # TODO XXX + def test_priority_vs_embedded(self): + g = """ + A.2: "a" + WORD: ("a".."z")+ + + start: (A | WORD)+ + """ + l = _Lark(g) + t = l.parse('abc') + self.assertEqual(t.children, ['a', 'bc']) + self.assertEqual(t.children[0].type, 'A') + + def test_line_counting(self): + p = _Lark("start: /[^x]+/") + + text = 'hello\nworld' + t = p.parse(text) + tok = t.children[0] + self.assertEqual(tok, text) + self.assertEqual(tok.line, 1) + self.assertEqual(tok.column, 1) + if _LEXER != 'dynamic': + self.assertEqual(tok.end_line, 2) + self.assertEqual(tok.end_column, 6) + + @unittest.skipIf(PARSER=='cyk', "Empty rules") + def test_empty_end(self): + p = _Lark(""" + start: b c d + b: "B" + c: | "C" + d: | "D" + """) + res = p.parse('B') + self.assertEqual(len(res.children), 3) + + @unittest.skipIf(PARSER=='cyk', "Empty rules") + def test_maybe_placeholders(self): + # Anonymous tokens shouldn't count + p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True) + self.assertEqual(p.parse("").children, []) + + # Unless keep_all_tokens=True + p = _Lark("""start: ["a"] ["b"] ["c"] """, maybe_placeholders=True, keep_all_tokens=True) + self.assertEqual(p.parse("").children, [None, None, None]) + + # All invisible constructs shouldn't count + p = _Lark("""start: [A] ["b"] [_c] ["e" "f" _c] + A: "a" + _c: "c" """, maybe_placeholders=True) + self.assertEqual(p.parse("").children, [None]) + self.assertEqual(p.parse("c").children, [None]) + self.assertEqual(p.parse("aefc").children, ['a']) + + # ? shouldn't apply + p = _Lark("""!start: ["a"] "b"? ["c"] """, maybe_placeholders=True) + self.assertEqual(p.parse("").children, [None, None]) + self.assertEqual(p.parse("b").children, [None, 'b', None]) + + p = _Lark("""!start: ["a"] ["b"] ["c"] """, maybe_placeholders=True) + self.assertEqual(p.parse("").children, [None, None, None]) + self.assertEqual(p.parse("a").children, ['a', None, None]) + self.assertEqual(p.parse("b").children, [None, 'b', None]) + self.assertEqual(p.parse("c").children, [None, None, 'c']) + self.assertEqual(p.parse("ab").children, ['a', 'b', None]) + self.assertEqual(p.parse("ac").children, ['a', None, 'c']) + self.assertEqual(p.parse("bc").children, [None, 'b', 'c']) + self.assertEqual(p.parse("abc").children, ['a', 'b', 'c']) + + p = _Lark("""!start: (["a"] "b" ["c"])+ """, maybe_placeholders=True) + self.assertEqual(p.parse("b").children, [None, 'b', None]) + self.assertEqual(p.parse("bb").children, [None, 'b', None, None, 'b', None]) + self.assertEqual(p.parse("abbc").children, ['a', 'b', None, None, 'b', 'c']) + self.assertEqual(p.parse("babbcabcb").children, + [None, 'b', None, + 'a', 'b', None, + None, 'b', 'c', + 'a', 'b', 'c', + None, 'b', None]) + + p = _Lark("""!start: ["a"] ["c"] "b"+ ["a"] ["d"] """, maybe_placeholders=True) + self.assertEqual(p.parse("bb").children, [None, None, 'b', 'b', None, None]) + self.assertEqual(p.parse("bd").children, [None, None, 'b', None, 'd']) + self.assertEqual(p.parse("abba").children, ['a', None, 'b', 'b', 'a', None]) + self.assertEqual(p.parse("cbbbb").children, [None, 'c', 'b', 'b', 'b', 'b', None, None]) + + + def test_escaped_string(self): + "Tests common.ESCAPED_STRING" + grammar = r""" + start: ESCAPED_STRING+ + + %import common (WS_INLINE, ESCAPED_STRING) + %ignore WS_INLINE + """ + + parser = _Lark(grammar) + parser.parse(r'"\\" "b" "c"') + + parser.parse(r'"That" "And a \"b"') + + + def test_meddling_unused(self): + "Unless 'unused' is removed, LALR analysis will fail on reduce-reduce collision" + + grammar = """ + start: EKS* x + x: EKS + unused: x* + EKS: "x" + """ + parser = _Lark(grammar) + + + @unittest.skipIf(PARSER!='lalr' or LEXER=='custom', "Serialize currently only works for LALR parsers without custom lexers (though it should be easy to extend)") + def test_serialize(self): + grammar = """ + start: _ANY b "C" + _ANY: /./ + b: "B" + """ + parser = _Lark(grammar) + s = BytesIO() + parser.save(s) + s.seek(0) + parser2 = Lark.load(s) + self.assertEqual(parser2.parse('ABC'), Tree('start', [Tree('b', [])]) ) + + def test_multi_start(self): + parser = _Lark(''' + a: "x" "a"? + b: "x" "b"? + ''', start=['a', 'b']) + + self.assertEqual(parser.parse('xa', 'a'), Tree('a', [])) + self.assertEqual(parser.parse('xb', 'b'), Tree('b', [])) + + def test_lexer_detect_newline_tokens(self): + # Detect newlines in regular tokens + g = _Lark(r"""start: "go" tail* + !tail : SA "@" | SB "@" | SC "@" | SD "@" + SA : "a" /\n/ + SB : /b./s + SC : "c" /[^a-z]/ + SD : "d" /\s/ + """) + a,b,c,d = [x.children[1] for x in g.parse('goa\n@b\n@c\n@d\n@').children] + self.assertEqual(a.line, 2) + self.assertEqual(b.line, 3) + self.assertEqual(c.line, 4) + self.assertEqual(d.line, 5) + + # Detect newlines in ignored tokens + for re in ['/\\n/', '/[^a-z]/', '/\\s/']: + g = _Lark('''!start: "a" "a" + %ignore {}'''.format(re)) + a, b = g.parse('a\na').children + self.assertEqual(a.line, 1) + self.assertEqual(b.line, 2) + + @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.') + def test_unicode_class(self): + "Tests that character classes from the `regex` module work correctly." + g = _Lark(r"""?start: NAME + NAME: ID_START ID_CONTINUE* + ID_START: /[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_]+/ + ID_CONTINUE: ID_START | /[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]+/""", regex=True) + + self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்') + + @unittest.skipIf(not regex or sys.version_info[0] == 2, 'Unicode and Python 2 do not place nicely together.') + def test_unicode_word(self): + "Tests that a persistent bug in the `re` module works when `regex` is enabled." + g = _Lark(r"""?start: NAME + NAME: /[\w]+/ + """, regex=True) + self.assertEqual(g.parse('வணக்கம்'), 'வணக்கம்') + + _NAME = "Test" + PARSER.capitalize() + LEXER.capitalize() + _TestParser.__name__ = _NAME + _TestParser.__qualname__ = "tests.test_parser." + _NAME + globals()[_NAME] = _TestParser + +# Note: You still have to import them in __main__ for the tests to run +_TO_TEST = [ + ('standard', 'earley'), + ('standard', 'cyk'), + ('dynamic', 'earley'), + ('dynamic_complete', 'earley'), + ('standard', 'lalr'), + ('contextual', 'lalr'), + ('custom', 'lalr'), + # (None, 'earley'), +] + +for _LEXER, _PARSER in _TO_TEST: + _make_parser_test(_LEXER, _PARSER) + +for _LEXER in ('dynamic', 'dynamic_complete'): + _make_full_earley_test(_LEXER) + +if __name__ == '__main__': + unittest.main() diff --git a/testbed/lark-parser__lark/tests/test_reconstructor.py b/testbed/lark-parser__lark/tests/test_reconstructor.py new file mode 100644 index 0000000000000000000000000000000000000000..93c64fef1b85bb0005c90a94de595f48993a7dfe --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_reconstructor.py @@ -0,0 +1,145 @@ +import json +import unittest +from unittest import TestCase +from lark import Lark +from lark.reconstruct import Reconstructor + + +common = """ +%import common (WS_INLINE, NUMBER, WORD) +%ignore WS_INLINE +""" + +def _remove_ws(s): + return s.replace(' ', '').replace('\n','') + +class TestReconstructor(TestCase): + + def assert_reconstruct(self, grammar, code): + parser = Lark(grammar, parser='lalr', maybe_placeholders=False) + tree = parser.parse(code) + new = Reconstructor(parser).reconstruct(tree) + self.assertEqual(_remove_ws(code), _remove_ws(new)) + + def test_starred_rule(self): + + g = """ + start: item* + item: NL + | rule + rule: WORD ":" NUMBER + NL: /(\\r?\\n)+\\s*/ + """ + common + + code = """ + Elephants: 12 + """ + + self.assert_reconstruct(g, code) + + def test_starred_group(self): + + g = """ + start: (rule | NL)* + rule: WORD ":" NUMBER + NL: /(\\r?\\n)+\\s*/ + """ + common + + code = """ + Elephants: 12 + """ + + self.assert_reconstruct(g, code) + + def test_alias(self): + + g = """ + start: line* + line: NL + | rule + | "hello" -> hi + rule: WORD ":" NUMBER + NL: /(\\r?\\n)+\\s*/ + """ + common + + code = """ + Elephants: 12 + hello + """ + + self.assert_reconstruct(g, code) + + def test_keep_tokens(self): + g = """ + start: (NL | stmt)* + stmt: var op var + !op: ("+" | "-" | "*" | "/") + var: WORD + NL: /(\\r?\\n)+\s*/ + """ + common + + code = """ + a+b + """ + + self.assert_reconstruct(g, code) + + def test_expand_rule(self): + g = """ + ?start: (NL | mult_stmt)* + ?mult_stmt: sum_stmt ["*" sum_stmt] + ?sum_stmt: var ["+" var] + var: WORD + NL: /(\\r?\\n)+\s*/ + """ + common + + code = ['a', 'a*b', 'a+b', 'a*b+c', 'a+b*c', 'a+b*c+d'] + + for c in code: + self.assert_reconstruct(g, c) + + def test_json_example(self): + test_json = ''' + { + "empty_object" : {}, + "empty_array" : [], + "booleans" : { "YES" : true, "NO" : false }, + "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ], + "strings" : [ "This", [ "And" , "That", "And a \\"b" ] ], + "nothing" : null + } + ''' + + json_grammar = r""" + ?start: value + + ?value: object + | array + | string + | SIGNED_NUMBER -> number + | "true" -> true + | "false" -> false + | "null" -> null + + array : "[" [value ("," value)*] "]" + object : "{" [pair ("," pair)*] "}" + pair : string ":" value + + string : ESCAPED_STRING + + %import common.ESCAPED_STRING + %import common.SIGNED_NUMBER + %import common.WS + + %ignore WS + """ + + json_parser = Lark(json_grammar, parser='lalr', maybe_placeholders=False) + tree = json_parser.parse(test_json) + + new_json = Reconstructor(json_parser).reconstruct(tree) + self.assertEqual(json.loads(new_json), json.loads(test_json)) + + +if __name__ == '__main__': + unittest.main() diff --git a/testbed/lark-parser__lark/tests/test_relative_import.lark b/testbed/lark-parser__lark/tests/test_relative_import.lark new file mode 100644 index 0000000000000000000000000000000000000000..c614a31d65f2c0d373d43c9ee79190b0b2c3b62a --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_import.lark @@ -0,0 +1,7 @@ +start: NUMBER WORD + +%import .grammars.test.NUMBER +%import common.WORD +%import common.WS +%ignore WS + diff --git a/testbed/lark-parser__lark/tests/test_relative_import_preserves_leading_underscore.lark b/testbed/lark-parser__lark/tests/test_relative_import_preserves_leading_underscore.lark new file mode 100644 index 0000000000000000000000000000000000000000..92c08c6fd2ee828195ed7e3c394dd68452e93f5c --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_import_preserves_leading_underscore.lark @@ -0,0 +1,3 @@ +start: c + +%import .grammars.leading_underscore_grammar.c \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/test_relative_import_rename.lark b/testbed/lark-parser__lark/tests/test_relative_import_rename.lark new file mode 100644 index 0000000000000000000000000000000000000000..c411771544f130d4cce499d74a036cbcaf8052eb --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_import_rename.lark @@ -0,0 +1,7 @@ +start: N WORD + +%import .grammars.test.NUMBER -> N +%import common.WORD +%import common.WS +%ignore WS + diff --git a/testbed/lark-parser__lark/tests/test_relative_import_rules_dependencies_imported_only_once.lark b/testbed/lark-parser__lark/tests/test_relative_import_rules_dependencies_imported_only_once.lark new file mode 100644 index 0000000000000000000000000000000000000000..bc21c7f60f46fead36b6663e6311f1e2cf3ba693 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_import_rules_dependencies_imported_only_once.lark @@ -0,0 +1,5 @@ +%import .grammars.three_rules_using_same_token.a +%import .grammars.three_rules_using_same_token.b +%import .grammars.three_rules_using_same_token.c -> d + +start: a b d diff --git a/testbed/lark-parser__lark/tests/test_relative_import_unicode.lark b/testbed/lark-parser__lark/tests/test_relative_import_unicode.lark new file mode 100644 index 0000000000000000000000000000000000000000..8010537d042fb8ab99bbd24f8b277f5e4cd8fa51 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_import_unicode.lark @@ -0,0 +1,3 @@ +start: UNICODE + +%import .grammars.test_unicode.UNICODE \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/test_relative_multi_import.lark b/testbed/lark-parser__lark/tests/test_relative_multi_import.lark new file mode 100644 index 0000000000000000000000000000000000000000..75c131de720e337c415f246c2d996c334529cc9b --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_multi_import.lark @@ -0,0 +1,4 @@ +start: NUMBER WORD + +%import .grammars.test (NUMBER, WORD, WS) +%ignore WS diff --git a/testbed/lark-parser__lark/tests/test_relative_rule_import.lark b/testbed/lark-parser__lark/tests/test_relative_rule_import.lark new file mode 100644 index 0000000000000000000000000000000000000000..e3a33a5bb95b8544ee8c2573eb3df546e4610454 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_rule_import.lark @@ -0,0 +1,7 @@ +start: X expr Y + +X: "x" +Y: "y" + +%import .grammars.ab.expr + diff --git a/testbed/lark-parser__lark/tests/test_relative_rule_import_drop_ignore.lark b/testbed/lark-parser__lark/tests/test_relative_rule_import_drop_ignore.lark new file mode 100644 index 0000000000000000000000000000000000000000..e3a33a5bb95b8544ee8c2573eb3df546e4610454 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_rule_import_drop_ignore.lark @@ -0,0 +1,7 @@ +start: X expr Y + +X: "x" +Y: "y" + +%import .grammars.ab.expr + diff --git a/testbed/lark-parser__lark/tests/test_relative_rule_import_rename.lark b/testbed/lark-parser__lark/tests/test_relative_rule_import_rename.lark new file mode 100644 index 0000000000000000000000000000000000000000..342b329cb32d1870358b4f734a235f07984843e8 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_rule_import_rename.lark @@ -0,0 +1,7 @@ +start: X ab Y + +X: "x" +Y: "y" + +%import .grammars.ab.expr -> ab + diff --git a/testbed/lark-parser__lark/tests/test_relative_rule_import_subrule.lark b/testbed/lark-parser__lark/tests/test_relative_rule_import_subrule.lark new file mode 100644 index 0000000000000000000000000000000000000000..94d7f809fa422fcf466fb46a5d0254562e91aca8 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_rule_import_subrule.lark @@ -0,0 +1,7 @@ +start: X startab Y + +X: "x" +Y: "y" + +%import .grammars.ab.startab + diff --git a/testbed/lark-parser__lark/tests/test_relative_rule_import_subrule_no_conflict.lark b/testbed/lark-parser__lark/tests/test_relative_rule_import_subrule_no_conflict.lark new file mode 100644 index 0000000000000000000000000000000000000000..839aac1f9e9db028dd3126a3206752a79cfb7fdc --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_relative_rule_import_subrule_no_conflict.lark @@ -0,0 +1,9 @@ +start: expr + +expr: X startab Y + +X: "x" +Y: "y" + +%import .grammars.ab.startab + diff --git a/testbed/lark-parser__lark/tests/test_templates_import.lark b/testbed/lark-parser__lark/tests/test_templates_import.lark new file mode 100644 index 0000000000000000000000000000000000000000..a1272b8e92368648b0e1b319a7d2d51fef25d6c6 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_templates_import.lark @@ -0,0 +1,4 @@ +start: "[" sep{NUMBER, ","} "]" +NUMBER: /\d+/ +%ignore " " +%import .grammars.templates.sep \ No newline at end of file diff --git a/testbed/lark-parser__lark/tests/test_tools.py b/testbed/lark-parser__lark/tests/test_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..ce995d818e826be602d913889ba50d1c35c47172 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_tools.py @@ -0,0 +1,138 @@ +from __future__ import absolute_import, print_function + +import sys +from unittest import TestCase, main + +from functools import partial +from lark.tree import Tree +from lark.tools import standalone + +try: + from StringIO import StringIO +except ImportError: + from io import StringIO + + + + +class TestStandalone(TestCase): + def setUp(self): + pass + + def _create_standalone(self, grammar): + code_buf = StringIO() + pr = partial(print, file=code_buf) + standalone.main(StringIO(grammar), 'start', print=pr) + code = code_buf.getvalue() + + context = {'__doc__': None} + exec(code, context) + return context + + def test_simple(self): + grammar = """ + start: NUMBER WORD + + %import common.NUMBER + %import common.WORD + %import common.WS + %ignore WS + + """ + + context = self._create_standalone(grammar) + + _Lark = context['Lark_StandAlone'] + l = _Lark() + x = l.parse('12 elephants') + self.assertEqual(x.children, ['12', 'elephants']) + x = l.parse('16 candles') + self.assertEqual(x.children, ['16', 'candles']) + + self.assertRaises(context['UnexpectedToken'], l.parse, 'twelve monkeys') + self.assertRaises(context['UnexpectedToken'], l.parse, 'twelve') + self.assertRaises(context['UnexpectedCharacters'], l.parse, '$ talks') + + def test_contextual(self): + grammar = """ + start: a b + a: "A" "B" + b: "AB" + """ + + context = self._create_standalone(grammar) + + _Lark = context['Lark_StandAlone'] + l = _Lark() + x = l.parse('ABAB') + + class T(context['Transformer']): + def a(self, items): + return 'a' + def b(self, items): + return 'b' + start = list + + x = T().transform(x) + self.assertEqual(x, ['a', 'b']) + + l2 = _Lark(transformer=T()) + x = l2.parse('ABAB') + self.assertEqual(x, ['a', 'b']) + + def test_postlex(self): + from lark.indenter import Indenter + class MyIndenter(Indenter): + NL_type = '_NEWLINE' + OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE'] + CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE'] + INDENT_type = '_INDENT' + DEDENT_type = '_DEDENT' + tab_len = 8 + + grammar = r""" + start: "(" ")" _NEWLINE + _NEWLINE: /\n/ + """ + + context = self._create_standalone(grammar) + _Lark = context['Lark_StandAlone'] + + l = _Lark(postlex=MyIndenter()) + x = l.parse('()\n') + self.assertEqual(x, Tree('start', [])) + l = _Lark(postlex=MyIndenter()) + x = l.parse('(\n)\n') + self.assertEqual(x, Tree('start', [])) + + def test_transformer(self): + grammar = r""" + start: some_rule "(" SOME_TERMINAL ")" + some_rule: SOME_TERMINAL + SOME_TERMINAL: /[A-Za-z_][A-Za-z0-9_]*/ + """ + context = self._create_standalone(grammar) + _Lark = context["Lark_StandAlone"] + + _Token = context["Token"] + _Tree = context["Tree"] + + class MyTransformer(context["Transformer"]): + def SOME_TERMINAL(self, token): + return _Token("SOME_TERMINAL", "token is transformed") + + def some_rule(self, children): + return _Tree("rule_is_transformed", []) + + parser = _Lark(transformer=MyTransformer()) + self.assertEqual( + parser.parse("FOO(BAR)"), + _Tree("start", [ + _Tree("rule_is_transformed", []), + _Token("SOME_TERMINAL", "token is transformed") + ]) + ) + + +if __name__ == '__main__': + main() diff --git a/testbed/lark-parser__lark/tests/test_tree_forest_transformer.py b/testbed/lark-parser__lark/tests/test_tree_forest_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..35c5614f7dd12130ef319338d01b65bbd3affe07 --- /dev/null +++ b/testbed/lark-parser__lark/tests/test_tree_forest_transformer.py @@ -0,0 +1,228 @@ +from __future__ import absolute_import + +import unittest + +from lark import Lark +from lark.lexer import Token +from lark.tree import Tree +from lark.visitors import Visitor, Transformer, Discard +from lark.parsers.earley_forest import TreeForestTransformer, handles_ambiguity + +class TestTreeForestTransformer(unittest.TestCase): + + grammar = """ + start: ab bc cd + !ab: "A" "B"? + !bc: "B"? "C"? + !cd: "C"? "D" + """ + + parser = Lark(grammar, parser='earley', ambiguity='forest') + forest = parser.parse("ABCD") + + def test_identity_resolve_ambiguity(self): + l = Lark(self.grammar, parser='earley', ambiguity='resolve') + tree1 = l.parse("ABCD") + tree2 = TreeForestTransformer(resolve_ambiguity=True).transform(self.forest) + self.assertEqual(tree1, tree2) + + def test_identity_explicit_ambiguity(self): + l = Lark(self.grammar, parser='earley', ambiguity='explicit') + tree1 = l.parse("ABCD") + tree2 = TreeForestTransformer(resolve_ambiguity=False).transform(self.forest) + self.assertEqual(tree1, tree2) + + def test_tree_class(self): + + class CustomTree(Tree): + pass + + class TreeChecker(Visitor): + def __default__(self, tree): + assert isinstance(tree, CustomTree) + + tree = TreeForestTransformer(resolve_ambiguity=False, tree_class=CustomTree).transform(self.forest) + TreeChecker().visit(tree) + + def test_token_calls(self): + + visited = [False] * 4 + + class CustomTransformer(TreeForestTransformer): + def A(self, node): + assert node.type == 'A' + visited[0] = True + def B(self, node): + assert node.type == 'B' + visited[1] = True + def C(self, node): + assert node.type == 'C' + visited[2] = True + def D(self, node): + assert node.type == 'D' + visited[3] = True + + tree = CustomTransformer(resolve_ambiguity=False).transform(self.forest) + assert visited == [True] * 4 + + def test_default_token(self): + + token_count = [0] + + class CustomTransformer(TreeForestTransformer): + def __default_token__(self, node): + token_count[0] += 1 + assert isinstance(node, Token) + + tree = CustomTransformer(resolve_ambiguity=True).transform(self.forest) + self.assertEqual(token_count[0], 4) + + def test_rule_calls(self): + + visited_start = [False] + visited_ab = [False] + visited_bc = [False] + visited_cd = [False] + + class CustomTransformer(TreeForestTransformer): + def start(self, data): + visited_start[0] = True + def ab(self, data): + visited_ab[0] = True + def bc(self, data): + visited_bc[0] = True + def cd(self, data): + visited_cd[0] = True + + tree = CustomTransformer(resolve_ambiguity=False).transform(self.forest) + self.assertTrue(visited_start[0]) + self.assertTrue(visited_ab[0]) + self.assertTrue(visited_bc[0]) + self.assertTrue(visited_cd[0]) + + def test_default_rule(self): + + rule_count = [0] + + class CustomTransformer(TreeForestTransformer): + def __default__(self, name, data): + rule_count[0] += 1 + + tree = CustomTransformer(resolve_ambiguity=True).transform(self.forest) + self.assertEqual(rule_count[0], 4) + + def test_default_ambig(self): + + ambig_count = [0] + + class CustomTransformer(TreeForestTransformer): + def __default_ambig__(self, name, data): + if len(data) > 1: + ambig_count[0] += 1 + + tree = CustomTransformer(resolve_ambiguity=False).transform(self.forest) + self.assertEqual(ambig_count[0], 1) + + def test_handles_ambiguity(self): + + class CustomTransformer(TreeForestTransformer): + @handles_ambiguity + def start(self, data): + assert isinstance(data, list) + assert len(data) == 4 + for tree in data: + assert tree.data == 'start' + return 'handled' + + @handles_ambiguity + def ab(self, data): + assert isinstance(data, list) + assert len(data) == 1 + assert data[0].data == 'ab' + + tree = CustomTransformer(resolve_ambiguity=False).transform(self.forest) + self.assertEqual(tree, 'handled') + + def test_discard(self): + + class CustomTransformer(TreeForestTransformer): + def bc(self, data): + raise Discard() + + def D(self, node): + raise Discard() + + class TreeChecker(Transformer): + def bc(self, children): + assert False + + def D(self, token): + assert False + + tree = CustomTransformer(resolve_ambiguity=False).transform(self.forest) + TreeChecker(visit_tokens=True).transform(tree) + + def test_aliases(self): + + visited_ambiguous = [False] + visited_full = [False] + + class CustomTransformer(TreeForestTransformer): + @handles_ambiguity + def start(self, data): + for tree in data: + assert tree.data == 'ambiguous' or tree.data == 'full' + + def ambiguous(self, data): + visited_ambiguous[0] = True + assert len(data) == 3 + assert data[0].data == 'ab' + assert data[1].data == 'bc' + assert data[2].data == 'cd' + return self.tree_class('ambiguous', data) + + def full(self, data): + visited_full[0] = True + assert len(data) == 1 + assert data[0].data == 'abcd' + return self.tree_class('full', data) + + grammar = """ + start: ab bc cd -> ambiguous + | abcd -> full + !ab: "A" "B"? + !bc: "B"? "C"? + !cd: "C"? "D" + !abcd: "ABCD" + """ + + l = Lark(grammar, parser='earley', ambiguity='forest') + forest = l.parse('ABCD') + tree = CustomTransformer(resolve_ambiguity=False).transform(forest) + self.assertTrue(visited_ambiguous[0]) + self.assertTrue(visited_full[0]) + + def test_transformation(self): + + class CustomTransformer(TreeForestTransformer): + def __default__(self, name, data): + result = [] + for item in data: + if isinstance(item, list): + result += item + else: + result.append(item) + return result + + def __default_token__(self, node): + return node.lower() + + def __default_ambig__(self, name, data): + return data[0] + + result = CustomTransformer(resolve_ambiguity=False).transform(self.forest) + expected = ['a', 'b', 'c', 'd'] + self.assertEqual(result, expected) + +if __name__ == '__main__': + unittest.main() diff --git a/testbed/lark-parser__lark/tox.ini b/testbed/lark-parser__lark/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..ef19e2c852d612bf3d8854c6a55689e2cf9553b3 --- /dev/null +++ b/testbed/lark-parser__lark/tox.ini @@ -0,0 +1,27 @@ +[tox] +envlist = py27, py34, py35, py36, py37, py38, py39, pypy, pypy3 +skip_missing_interpreters=true + +[travis] +2.7 = py27 +3.4 = py34 +3.5 = py35 +3.6 = py36 +3.7 = py37 +3.8 = py38 +3.9 = py39 +pypy = pypy +pypy3 = pypy3 + +[testenv] +whitelist_externals = git +deps = + -rtest-requirements.txt + +# to always force recreation and avoid unexpected side effects +recreate=True + +commands= + git submodule sync -q + git submodule update --init + python -m tests {posargs} diff --git a/testbed/matplotlib__matplotlib/.circleci/config.yml b/testbed/matplotlib__matplotlib/.circleci/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..5fc186a4143ac36609ea087c91f8215e5c6cc7d5 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.circleci/config.yml @@ -0,0 +1,253 @@ +# Circle CI configuration file +# https://circleci.com/docs/ + +version: 2.1 + + +####################################### +# Define some common steps as commands. +# + +commands: + check-skip: + steps: + - run: + name: Check-skip + command: | + export git_log=$(git log --max-count=1 --pretty=format:"%B" | tr "\n" " ") + echo "Got commit message:" + echo "${git_log}" + if [[ -v CIRCLE_PULL_REQUEST ]] && ([[ "$git_log" == *"[skip circle]"* ]] || [[ "$git_log" == *"[circle skip]"* ]]); then + echo "Skip detected, exiting job ${CIRCLE_JOB} for PR ${CIRCLE_PULL_REQUEST}." + circleci-agent step halt; + fi + + merge: + steps: + - run: + name: Merge with upstream + command: | + if ! git remote -v | grep upstream; then + git remote add upstream https://github.com/matplotlib/matplotlib.git + fi + git fetch upstream + if [[ "$CIRCLE_BRANCH" != "main" ]] && \ + [[ "$CIRCLE_PR_NUMBER" != "" ]]; then + echo "Merging ${CIRCLE_PR_NUMBER}" + git pull --ff-only upstream "refs/pull/${CIRCLE_PR_NUMBER}/merge" + fi + + apt-install: + steps: + - run: + name: Install apt packages + command: | + sudo apt -qq update + sudo apt install -y \ + inkscape \ + ffmpeg \ + dvipng \ + lmodern \ + cm-super \ + texlive-latex-base \ + texlive-latex-extra \ + texlive-fonts-recommended \ + texlive-latex-recommended \ + texlive-pictures \ + texlive-xetex \ + ttf-wqy-zenhei \ + graphviz \ + fonts-crosextra-carlito \ + fonts-freefont-otf \ + fonts-humor-sans \ + fonts-noto-cjk \ + optipng + + fonts-install: + steps: + - restore_cache: + key: fonts-2 + - run: + name: Install custom fonts + command: | + mkdir -p ~/.local/share/fonts + wget -nc https://github.com/google/fonts/blob/master/ofl/felipa/Felipa-Regular.ttf?raw=true -O ~/.local/share/fonts/Felipa-Regular.ttf || true + fc-cache -f -v + - save_cache: + key: fonts-2 + paths: + - ~/.local/share/fonts/ + + pip-install: + description: Upgrade pip and setuptools and wheel to get as clean an install as possible + steps: + - run: + name: Upgrade pip, setuptools, wheel + command: | + python -m pip install --upgrade --user pip + python -m pip install --upgrade --user wheel + python -m pip install --upgrade --user 'setuptools!=60.6.0' + + doc-deps-install: + parameters: + numpy_version: + type: string + default: "" + steps: + - run: + name: Install Python dependencies + command: | + python -m pip install --user \ + numpy<< parameters.numpy_version >> \ + -r requirements/doc/doc-requirements.txt + python -m pip install --no-deps --user \ + git+https://github.com/matplotlib/mpl-sphinx-theme.git + + mpl-install: + steps: + - run: + name: Install Matplotlib + command: | + if [[ "$CIRCLE_BRANCH" == v*-doc ]]; then + # The v*-doc branches must build against the specified release. + version=${CIRCLE_BRANCH%-doc} + version=${version#v} + python -m pip install matplotlib==${version} + else + python -m pip install --user -ve . + fi + - save_cache: + key: build-deps-1 + paths: + # FreeType 2.6.1 tarball. + - ~/.cache/matplotlib/0a3c7dfbda6da1e8fce29232e8e96d987ababbbf71ebc8c75659e4132c367014 + # Qhull 2020.2 tarball. + - ~/.cache/matplotlib/b5c2d7eb833278881b952c8a52d20179eab87766b00b865000469a45c1838b7e + + doc-build: + steps: + - restore_cache: + keys: + - sphinx-env-v1-{{ .BuildNum }}-{{ .Environment.CIRCLE_JOB }} + - sphinx-env-v1-{{ .Environment.CIRCLE_PREVIOUS_BUILD_NUM }}-{{ .Environment.CIRCLE_JOB }} + - run: + name: Build documentation + command: | + # Set epoch to date of latest tag. + export SOURCE_DATE_EPOCH="$(git log -1 --format=%at $(git describe --abbrev=0))" + # Set release mode only when deploying to devdocs. + if [ "$CIRCLE_PROJECT_USERNAME" = "matplotlib" ] && \ + [ "$CIRCLE_BRANCH" = "main" ] && \ + [ "$CIRCLE_PR_NUMBER" = "" ]; then + export RELEASE_TAG='-t release' + fi + mkdir -p logs + make html O="-T $RELEASE_TAG -j4 -w /tmp/sphinxerrorswarnings.log" + rm -r build/html/_sources + working_directory: doc + - save_cache: + key: sphinx-env-v1-{{ .BuildNum }}-{{ .Environment.CIRCLE_JOB }} + paths: + - doc/build/doctrees + + doc-show-errors-warnings: + steps: + - run: + name: Extract possible build errors and warnings + command: | + (grep "WARNING\|ERROR" /tmp/sphinxerrorswarnings.log || + echo "No errors or warnings") + # Save logs as an artifact, and convert from absolute paths to + # repository-relative paths. + sed "s~$PWD/~~" /tmp/sphinxerrorswarnings.log > \ + doc/logs/sphinx-errors-warnings.log + when: always + - store_artifacts: + path: doc/logs/sphinx-errors-warnings.log + + doc-show-deprecations: + steps: + - run: + name: Extract possible deprecation warnings in examples and tutorials + command: | + (grep -rl DeprecationWarning doc/build/html/gallery || + echo "No deprecation warnings in gallery") + (grep -rl DeprecationWarning doc/build/html/plot_types || + echo "No deprecation warnings in plot_types") + (grep -rl DeprecationWarning doc/build/html/tutorials || + echo "No deprecation warnings in tutorials") + # Save deprecations that are from this absolute directory, and + # convert to repository-relative paths. + (grep -Ero --no-filename "$PWD/.+DeprecationWarning.+$" \ + doc/build/html/{gallery,plot_types,tutorials} || echo) | \ + sed "s~$PWD/~~" > doc/logs/sphinx-deprecations.log + when: always + - store_artifacts: + path: doc/logs/sphinx-deprecations.log + + doc-bundle: + steps: + - run: + name: Bundle sphinx-gallery documentation artifacts + command: > + tar cf doc/build/sphinx-gallery-files.tar.gz + doc/api/_as_gen + doc/gallery + doc/plot_types + doc/tutorials + when: always + - store_artifacts: + path: doc/build/sphinx-gallery-files.tar.gz + + +########################################## +# Here is where the real jobs are defined. +# + +jobs: + docs-python39: + docker: + - image: cimg/python:3.9 + resource_class: large + steps: + - checkout + - check-skip + - merge + + - apt-install + - fonts-install + - pip-install + + - mpl-install + - doc-deps-install + + - doc-build + - doc-show-errors-warnings + - doc-show-deprecations + + - doc-bundle + + - store_artifacts: + path: doc/build/html + - store_test_results: + path: doc/build/test-results + + - add_ssh_keys: + fingerprints: + - "be:c3:c1:d8:fb:a1:0e:37:71:72:d7:a3:40:13:8f:14" + + - deploy: + name: "Deploy new docs" + command: ./.circleci/deploy-docs.sh + +######################################### +# Defining workflows gets us parallelism. +# + +workflows: + version: 2 + build: + jobs: + # NOTE: If you rename this job, then you must update the `if` condition + # and `circleci-jobs` option in `.github/workflows/circleci.yml`. + - docs-python39 diff --git a/testbed/matplotlib__matplotlib/.circleci/deploy-docs.sh b/testbed/matplotlib__matplotlib/.circleci/deploy-docs.sh new file mode 100644 index 0000000000000000000000000000000000000000..8801d5fd073e7e1461ef673383b8d65aead0ffe5 --- /dev/null +++ b/testbed/matplotlib__matplotlib/.circleci/deploy-docs.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +set -e + +if [ "$CIRCLE_PROJECT_USERNAME" != "matplotlib" ] || \ + [ "$CIRCLE_BRANCH" != "main" ] || \ + [[ "$CIRCLE_PULL_REQUEST" == https://github.com/matplotlib/matplotlib/pull/* ]]; then + echo "Not uploading docs for ${CIRCLE_SHA1}"\ + "from non-main branch (${CIRCLE_BRANCH})"\ + "or pull request (${CIRCLE_PULL_REQUEST})"\ + "or non-Matplotlib org (${CIRCLE_PROJECT_USERNAME})." + exit +fi + +git clone git@github.com:matplotlib/devdocs.git + +cd devdocs + +git checkout --orphan gh-pages || true +git reset --hard first_commit + +git rm -rf . +cp -R ../doc/build/html/. . +touch .nojekyll + +git config user.email "MatplotlibCircleBot@nomail" +git config user.name "MatplotlibCircleBot" +git config push.default simple + +git add . +git commit -m "Docs build of $CIRCLE_SHA1" + +git push --set-upstream origin gh-pages --force