{"id":14958085,"url":"https://github.com/pytorch/csprng","last_synced_at":"2026-01-12T01:54:21.512Z","repository":{"id":40659708,"uuid":"263081863","full_name":"pytorch/csprng","owner":"pytorch","description":"Cryptographically secure pseudorandom number generators for PyTorch","archived":false,"fork":false,"pushed_at":"2024-12-04T17:00:17.000Z","size":438,"stargazers_count":117,"open_issues_count":28,"forks_count":28,"subscribers_count":30,"default_branch":"main","last_synced_at":"2025-05-15T00:13:15.046Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://github.com/pytorch/csprng","language":"Batchfile","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pytorch.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-05-11T15:26:41.000Z","updated_at":"2025-04-03T07:57:58.000Z","dependencies_parsed_at":"2024-05-08T17:03:09.449Z","dependency_job_id":"593f7877-6ae7-41b0-bf58-dc10f5bde88c","html_url":"https://github.com/pytorch/csprng","commit_stats":{"total_commits":87,"total_committers":16,"mean_commits":5.4375,"dds":"0.29885057471264365","last_synced_commit":"155edb6754f25f011a143c60088b796b4978d23a"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pytorch%2Fcsprng","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pytorch%2Fcsprng/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pytorch%2Fcsprng/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pytorch%2Fcsprng/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pytorch","download_url":"https://codeload.github.com/pytorch/csprng/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254518383,"owners_count":22084374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-09-24T13:16:12.671Z","updated_at":"2025-05-16T11:02:27.745Z","avatar_url":"https://github.com/pytorch.png","language":"Batchfile","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PyTorch/CSPRNG\n\n[![CircleCI](https://circleci.com/gh/pytorch/csprng.svg?style=shield\u0026circle-token=64701692dd7f13f31019612289f0200fdb661dc2)](https://circleci.com/gh/pytorch/csprng)\n\ntorchcsprng is a [PyTorch C++/CUDA extension](https://pytorch.org/tutorials/advanced/cpp_extension.html) that provides:\n\n- [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) 128-bit encryption/decryption in two modes: [ECB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_(ECB)) and [CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR)) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pytorch/csprng/blob/master/examples/encrypt_decrypt.ipynb)\n- [cryptographically secure pseudorandom number generators](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) for PyTorch. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pytorch/csprng/blob/master/examples/csprng.ipynb)\n\n## Design\n\ntorchcsprng generates a random 128-bit key on CPU using one of its generators and runs\n[AES128](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) in [CTR mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR))\n either on CPU or on GPU using CUDA to generate a random 128 bit state and apply a transformation function to map it to target tensor values.\nThis approach is based on [Parallel Random Numbers: As Easy as 1, 2, 3(John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, D. E. Shaw Research)](http://www.thesalmons.org/john/random123/papers/random123sc11.pdf).\nIt makes torchcsprng both crypto-secure and parallel on CUDA and CPU.\n\n![CSPRNG architecture](.github/csprng_architecture.png)\n\nAdvantages:\n\n- The user can choose either seed-based(for testing) or random device based(fully crypto-secure) generators\n- One generator instance for both CPU and CUDA tensors(because the encryption key is always generated on CPU)\n- CPU random number generation is also parallel(unlike the default PyTorch CPU generator)\n\n## Features\n\ntorchcsprng 0.2.0 exposes new API for tensor encryption/decryption. Tensor encryption/decryption API is dtype agnostic, so a tensor of any dtype can be encrypted and the result can be stored to a tensor of any dtype. An encryption key also can be a tensor of any dtype. Currently torchcsprng supports [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) cipher with 128-bit key in two modes: [ECB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_(ECB)) and [CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR)).\n\n* `torchcsprng.encrypt(input: Tensor, output: Tensor, key: Tensor, cipher: string, mode: string)`\n\n\u003e - `input` tensor can be any CPU or CUDA tensor of any dtype and size in bytes(zero-padding is used to make its size in bytes divisible by block size in bytes)\n\u003e - `output` tensor can have any dtype and the same device as `input` tensor and the size in bytes rounded up to the block size in bytes(16 bytes for AES 128)\n\u003e - `key` tensor can have any dtype and the same device as `input` tensor and size in bytes equal to 16 for AES 128\n\u003e - `cipher` currently can be only one supported value `\"aes128\"`\n\u003e - `mode` currently can be either [`\"ecb\"`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_(ECB)) or [`\"ctr\"`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR))\n\n* `torchcsprng.decrypt(input: Tensor, output: Tensor, key: Tensor, cipher: string, mode: string)`\n\n\u003e - `input` tensor can be any CPU or CUDA tensor of any dtype with size in bytes divisible by the block size in bytes(16 bytes for AES 128)\n\u003e - `output` tensor can have any dtype but the same device as `input` tensor and the same size in bytes as `input` tensor\n\u003e - `key` tensor can have any dtype and the same device as `input` tensor and size in bytes equal to 16 for AES 128\n\u003e - `cipher` currently can be only one supported value `\"aes128\"`\n\u003e - `mode` currently can be either [`\"ecb\"`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_(ECB)) or [`\"ctr\"`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR))\n\ntorchcsprng exposes two methods to create crypto-secure and non-crypto-secure PRNGs:\n\n| Method to create PRNG                              | Is crypto-secure? | Has seed? | Underlying implementation |\n|----------------------------------------------------|-------------------|-----------|---------------------------|\n| create_random_device_generator(token: string=None) |         yes       |    no     | See [std::random_device](https://en.cppreference.com/w/cpp/numeric/random/random_device) and [its constructor](https://en.cppreference.com/w/cpp/numeric/random/random_device/random_device). The implementation in libstdc++ expects token to name the source of random bytes. Possible token values include \"default\", \"rand_s\", \"rdseed\", \"rdrand\", \"rdrnd\", \"/dev/urandom\", \"/dev/random\", \"mt19937\", and integer string specifying the seed of the mt19937 engine. (Token values other than \"default\" are only valid for certain targets.) If token=None then constructs a new std::random_device object with an implementation-defined token. |\n| create_mt19937_generator(seed: int=None)           |         no        |    yes    | See [std::mt19937](https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine) and [its constructor](https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine/mersenne_twister_engine). Constructs a mersenne_twister_engine object, and initializes its internal state sequence to pseudo-random values. If seed=None then seeds the engine with default_seed.|\n\nThe following list of methods supports all forementioned PRNGs:\n\n| Kernel                 | CUDA | CPU |\n|------------------------|------|-----|\n| random_()              | yes  | yes |\n| random_(to)            | yes  | yes |\n| random_(from, to)      | yes  | yes |\n| uniform_(from, to)     | yes  | yes |\n| normal_(mean, std)     | yes  | yes |\n| cauchy_(median, sigma) | yes  | yes |\n| log_normal_(mean, std) | yes  | yes |\n| geometric_(p)          | yes  | yes |\n| exponential_(lambda)   | yes  | yes |\n| randperm(n)            | yes* | yes |\n\n* the calculations are done on CPU and the result is copied to CUDA\n\n## Installation\n\nCSPRNG works with Python 3.6-3.9 on the following operating systems and can be used with PyTorch tensors on the following devices:\n\n| Tensor Device Type | Linux     | macOS         | MS Window      |\n|--------------------|-----------|---------------|----------------| \n| CPU                | Supported | Supported     | Supported      |\n| CUDA               | Supported | Not Supported | Supported since 0.2.0 |\n\nThe following is the corresponding CSPRNG versions and supported Python versions.\n\n| PyTorch | CSPRNG | Python   | CUDA             |\n|---------|--------|----------|------------------|\n| 1.8.0   | 0.2.0  | 3.7-3.9  | 10.1, 10.2, 11.1 |\n| 1.7.1   | 0.1.4  | 3.6-3.8  | 9.2, 10.1, 10.2  |\n| 1.7.0   | 0.1.3  | 3.6-3.8  | 9.2, 10.1, 10.2  |\n| 1.6.0   | 0.1.2  | 3.6-3.8  | 9.2, 10.1, 10.2  |\n\n\n### Binary Installation\n\nAnaconda:\n\n| OS            | CUDA                                           |                                                                                                                                                                                                                                                                                                       |\n|---------------|------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Linux/Windows | 10.1\u003cbr/\u003e\u003cbr/\u003e10.2\u003cbr/\u003e\u003cbr/\u003e11.1\u003cbr/\u003e\u003cbr/\u003eNone | conda install torchcsprng cudatoolkit=10.1 -c pytorch -c conda-forge\u003cbr/\u003e\u003cbr/\u003econda install torchcsprng cudatoolkit=10.2 -c pytorch -c conda-forge\u003cbr/\u003e\u003cbr/\u003econda install torchcsprng cudatoolkit=11.1 -c pytorch -c conda-forge\u003cbr/\u003e\u003cbr/\u003econda install torchcsprng cpuonly -c pytorch -c conda-forge |\n| macOS         | None                                           | conda install torchcsprng -c pytorch                                                                                                                                                                                                                                                          |\n\npip:\n\n| OS            | CUDA                                           |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n|---------------|------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Linux/Windows | 10.1\u003cbr/\u003e\u003cbr/\u003e10.2\u003cbr/\u003e\u003cbr/\u003e11.1\u003cbr/\u003e\u003cbr/\u003eNone | pip install torchcsprng==0.2.0+cu101 torch==1.8.0+cu101 -f https://download.pytorch.org/whl/cu101/torch_stable.html \u003cbr/\u003e\u003cbr/\u003epip install torchcsprng==0.2.0 torch==1.8.0 -f https://download.pytorch.org/whl/cu102/torch_stable.html \u003cbr/\u003e\u003cbr/\u003epip install torchcsprng==0.2.0+cu111 torch==1.8.0+cu111 -f https://download.pytorch.org/whl/cu111/torch_stable.html \u003cbr/\u003e\u003cbr/\u003epip install torchcsprng==0.2.0+cpu torch==1.8.0+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html |\n| macOS         | None                                           | pip install torchcsprng torch                                                                                                                                                                                                                                                                                                                                                                                                                                                     |\n\n### Nightly builds:\n\nAnaconda:\n\n| OS            | CUDA                                           |                                                                                                                                                                                                                                                                                                                                       |\n|---------------|------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Linux/Windows | 10.1\u003cbr/\u003e\u003cbr/\u003e10.2\u003cbr/\u003e\u003cbr/\u003e11.1\u003cbr/\u003e\u003cbr/\u003eNone | conda install torchcsprng cudatoolkit=10.1 -c pytorch-nightly -c conda-forge\u003cbr/\u003e\u003cbr/\u003econda install torchcsprng cudatoolkit=10.2 -c pytorch-nightly -c conda-forge\u003cbr/\u003e\u003cbr/\u003econda install torchcsprng cudatoolkit=11.1 -c pytorch-nightly -c conda-forge\u003cbr/\u003e\u003cbr/\u003econda install torchcsprng cpuonly -c pytorch-nightly -c conda-forge |\n| macOS         | None                                           | conda install torchcsprng -c pytorch-nightly                                                                                                                                                                                                                                                                                          |\n\npip:\n\n| OS            | CUDA                                           |                                                                                                                                                                                                                                                                                                                                                                                                                                            |\n|---------------|------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Linux/Windows | 10.1\u003cbr/\u003e\u003cbr/\u003e10.2\u003cbr/\u003e\u003cbr/\u003e11.1\u003cbr/\u003e\u003cbr/\u003eNone | pip install --pre torchcsprng -f https://download.pytorch.org/whl/nightly/cu101/torch_nightly.html \u003cbr/\u003e\u003cbr/\u003e pip install --pre torchcsprng -f https://download.pytorch.org/whl/nightly/cu102/torch_nightly.html \u003cbr/\u003e\u003cbr/\u003e pip install --pre torchcsprng -f https://download.pytorch.org/whl/nightly/cu111/torch_nightly.html \u003cbr/\u003e\u003cbr/\u003e pip install --pre torchcsprng -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html |\n| macOS         | None                                           | pip install --pre torchcsprng -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html                                                                                                                                                                                                                                                                                                                                           |\n\n### From Source\n\ntorchcsprng is a Python C++/CUDA extension that depends on PyTorch. In order to build CSPRNG from source it is required to have Python(\u003e=3.7) with PyTorch(\u003e=1.8.0) installed and C++ compiler(gcc/clang for Linux, XCode for macOS, Visual Studio for MS Windows).\nTo build torchcsprng you can run the following:\n```console\npython setup.py install\n```\nBy default, GPU support is built if CUDA is found and torch.cuda.is_available() is True. Additionally, it is possible to force building GPU support by setting the FORCE_CUDA=1 environment variable, which is useful when building a docker image.\n\n## Getting Started\n\nThe torchcsprng API is available in `torchcsprng` module:\n```python\nimport torch\nimport torchcsprng as csprng\n```\nCreate crypto-secure PRNG from /dev/urandom:\n```python\nurandom_gen = csprng.create_random_device_generator('/dev/urandom')\n```\n\nCreate empty boolean tensor on CUDA and initialize it with random values from urandom_gen:\n```python\ntorch.empty(10, dtype=torch.bool, device='cuda').random_(generator=urandom_gen)\n```\n```\ntensor([ True, False, False,  True, False, False, False,  True, False, False],\n       device='cuda:0')\n```\n\nCreate empty int16 tensor on CUDA and initialize it with random values in range [0, 100) from urandom_gen:\n```python\ntorch.empty(10, dtype=torch.int16, device='cuda').random_(100, generator=urandom_gen)\n```\n```\ntensor([59, 20, 68, 51, 18, 37,  7, 54, 74, 85], device='cuda:0',\n       dtype=torch.int16)\n```\n\nCreate non-crypto-secure MT19937 PRNG:\n```python\nmt19937_gen = csprng.create_mt19937_generator()\ntorch.empty(10, dtype=torch.int64, device='cuda').random_(torch.iinfo(torch.int64).min, to=None, generator=mt19937_gen)\n```\n```\ntensor([-7584783661268263470,  2477984957619728163, -3472586837228887516,\n        -5174704429717287072,  4125764479102447192, -4763846282056057972,\n         -182922600982469112,  -498242863868415842,   728545841957750221,\n         7740902737283645074], device='cuda:0')\n```\n\nCreate crypto-secure PRNG from default random device:\n```python\ndefault_device_gen = csprng.create_random_device_generator()\ntorch.randn(10, device='cuda', generator=default_device_gen)\n```\n```\ntensor([ 1.2885,  0.3240, -1.1813,  0.8629,  0.5714,  2.3720, -0.5627, -0.5551,\n        -0.6304,  0.1090], device='cuda:0')\n```\n\nCreate non-crypto-secure MT19937 PRNG with seed:\n```python\nmt19937_gen = csprng.create_mt19937_generator(42)\ntorch.empty(10, device='cuda').geometric_(p=0.2, generator=mt19937_gen)\n```\n```\ntensor([ 7.,  1.,  8.,  1., 11.,  3.,  1.,  1.,  5., 10.], device='cuda:0')\n```\n\nRecreate MT19937 PRNG with the same seed:\n```python\nmt19937_gen = csprng.create_mt19937_generator(42)\ntorch.empty(10, device='cuda').geometric_(p=0.2, generator=mt19937_gen)\n```\n```\ntensor([ 7.,  1.,  8.,  1., 11.,  3.,  1.,  1.,  5., 10.], device='cuda:0')\n```\n\n## Contributing\nWe appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion. If you plan to contribute new features, utility functions or extensions, please first open an issue and discuss the feature with us.\n\n\n\n## License\n\ntorchcsprng is BSD 3-clause licensed. See the license file [here](https://github.com/pytorch/csprng/blob/master/LICENSE)\n\n## [Terms of Use](https://opensource.facebook.com/legal/terms)\n\n## [Privacy Policy](https://opensource.facebook.com/legal/privacy)\n\nCopyright © 2020 Meta Platforms, Inc\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpytorch%2Fcsprng","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpytorch%2Fcsprng","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpytorch%2Fcsprng/lists"}