rag-dl / sample.json
shiowo's picture
Add source-separated licensed PyTorch evidence and benchmark study records
94f7dc4 verified
Raw History Blame Contribute Delete
133 kB
{
"vikp_clean_notebooks_filtered": [],
"monster_pytorch_code_10k": [
{
"record_id": "monster_pytorch_code_10k-d104794ccc6de8c9122f79d3",
"source_id": "monster_pytorch_code_10k",
"source_repo": "Monster-Code/Pytorch-Code-10K",
"source_revision": "99c0ba3cc6b31990a4e4ff1eba13db463a750d35",
"source_path": "data/train_batch_6.parquet",
"source_url": "https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_6.parquet",
"source_group": "f720d77ecc540423a6a6545f9e50c117ad1c08db",
"source_record_id": "f720d77ecc540423a6a6545f9e50c117ad1c08db",
"upstream_track": "frozen",
"authority": "community",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "LinearSE3",
"code": "from typing import Dict\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\nfrom se3_transformer.model.fiber import Fiber\n\nclass LinearSE3(nn.Module):\n \"\"\"\n Graph Linear SE(3)-equivariant layer, equivalent to a 1x1 convolution.\n Maps a fiber to a fiber with the same degrees (channels may be different).\n No interaction between degrees, but interaction between channels.\n\n type-0 features (C_0 channels) ────> Linear(bias=False) ────> type-0 features (C'_0 channels)\n type-1 features (C_1 channels) ────> Linear(bias=False) ────> type-1 features (C'_1 channels)\n :\n type-k features (C_k channels) ────> Linear(bias=False) ────> type-k features (C'_k channels)\n \"\"\"\n\n def __init__(self, fiber_in: Fiber, fiber_out: Fiber):\n super().__init__()\n self.weights = nn.ParameterDict({\n str(degree_out): nn.Parameter(\n torch.randn(channels_out, fiber_in[degree_out]) / np.sqrt(fiber_in[degree_out]))\n for degree_out, channels_out in fiber_out\n })\n\n def forward(self, features: Dict[str, Tensor], *args, **kwargs) -> Dict[str, Tensor]:\n return {\n degree: self.weights[degree] @ features[degree]\n for degree, weight in self.weights.items()\n }",
"code_sha256": "d6c1244513f2439adcb893297b6bdecfe27ed1dc10f9ddcb6413aebe42336475",
"ast_sha256": "5194b07f35aa1d74691cd6a86f3c31a8a566dd4c42aaaa17e27dc486255b844d",
"template_ast_sha256": "5194b07f35aa1d74691cd6a86f3c31a8a566dd4c42aaaa17e27dc486255b844d",
"license_id": "MIT",
"license_evidence": "inline_spdx",
"attribution_notice": "# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES\n# SPDX-License-Identifier: MIT\n\n",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# LinearSE3\nSource: https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_6.parquet#L35-L59\nLicense: MIT. Syntax checked only; may require original state/files.\n\n```python\nfrom typing import Dict\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\nfrom se3_transformer.model.fiber import Fiber\n\nclass LinearSE3(nn.Module):\n \"\"\"\n Graph Linear SE(3)-equivariant layer, equivalent to a 1x1 convolution.\n Maps a fiber to a fiber with the same degrees (channels may be different).\n No interaction between degrees, but interaction between channels.\n\n type-0 features (C_0 channels) ────> Linear(bias=False) ────> type-0 features (C'_0 channels)\n type-1 features (C_1 channels) ────> Linear(bias=False) ────> type-1 features (C'_1 channels)\n :\n type-k features (C_k channels) ────> Linear(bias=False) ────> type-k features (C'_k channels)\n \"\"\"\n\n def __init__(self, fiber_in: Fiber, fiber_out: Fiber):\n super().__init__()\n self.weights = nn.ParameterDict({\n str(degree_out): nn.Parameter(\n torch.randn(channels_out, fiber_in[degree_out]) / np.sqrt(fiber_in[degree_out]))\n for degree_out, channels_out in fiber_out\n })\n\n def forward(self, features: Dict[str, Tensor], *args, **kwargs) -> Dict[str, Tensor]:\n return {\n degree: self.weights[degree] @ features[degree]\n for degree, weight in self.weights.items()\n }\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"numpy",
"se3_transformer",
"torch",
"typing"
],
"unresolved_names": [],
"compatibility_flags": [],
"source_row": 175,
"line_start": 35,
"line_end": 59,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "monster_pytorch_code_10k-27d1d98e1900b3d810faa415",
"source_id": "monster_pytorch_code_10k",
"source_repo": "Monster-Code/Pytorch-Code-10K",
"source_revision": "99c0ba3cc6b31990a4e4ff1eba13db463a750d35",
"source_path": "data/train_batch_61.parquet",
"source_url": "https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_61.parquet",
"source_group": "79391452fb25d74acbad6c0ec3d5b906620a2d52",
"source_record_id": "79391452fb25d74acbad6c0ec3d5b906620a2d52",
"upstream_track": "frozen",
"authority": "community",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "DaliPipeline.__init__",
"code": "import nvidia.dali.ops as ops\nimport nvidia.dali.types as types\nimport numpy as np\nimport torch\nimport math\n\ndef __init__(self, *,\n pipeline_type,\n device_id,\n num_threads,\n batch_size,\n file_root: str,\n sampler,\n sample_rate,\n resample_range: list,\n window_size,\n window_stride,\n nfeatures,\n nfft,\n dither_coeff,\n silence_threshold,\n preemph_coeff,\n max_duration,\n preprocessing_device=\"gpu\"):\n super().__init__(batch_size, num_threads, device_id)\n\n self._dali_init_log(locals())\n\n if torch.distributed.is_initialized():\n shard_id = torch.distributed.get_rank()\n n_shards = torch.distributed.get_world_size()\n else:\n shard_id = 0\n n_shards = 1\n\n self.preprocessing_device = preprocessing_device.lower()\n assert self.preprocessing_device == \"cpu\" or self.preprocessing_device == \"gpu\", \\\n \"Incorrect preprocessing device. Please choose either 'cpu' or 'gpu'\"\n\n self.resample_range = resample_range\n\n train_pipeline = pipeline_type == 'train'\n self.train = train_pipeline\n self.sample_rate = sample_rate\n self.dither_coeff = dither_coeff\n self.nfeatures = nfeatures\n self.max_duration = max_duration\n self.do_remove_silence = True if silence_threshold is not None else False\n\n shuffle = train_pipeline and not sampler.is_sampler_random()\n self.read = ops.FileReader(name=\"Reader\", pad_last_batch=(pipeline_type == 'val'), device=\"cpu\", file_root=file_root, file_list=sampler.get_file_list_path(), shard_id=shard_id,\n num_shards=n_shards, shuffle_after_epoch=shuffle)\n\n # TODO change ExternalSource to Uniform for new DALI release\n if resample_range is not None:\n self.speed_perturbation_coeffs = ops.Uniform(device=\"cpu\", range=resample_range)\n else:\n self.speed_perturbation_coeffs = None\n\n self.decode = ops.AudioDecoder(device=\"cpu\", sample_rate=self.sample_rate if resample_range is None else None,\n dtype=types.FLOAT, downmix=True)\n\n self.normal_distribution = ops.NormalDistribution(device=preprocessing_device)\n\n self.preemph = ops.PreemphasisFilter(device=preprocessing_device, preemph_coeff=preemph_coeff)\n\n self.spectrogram = ops.Spectrogram(device=preprocessing_device, nfft=nfft,\n window_length=window_size * sample_rate,\n window_step=window_stride * sample_rate)\n\n self.mel_fbank = ops.MelFilterBank(device=preprocessing_device, sample_rate=sample_rate, nfilter=self.nfeatures,\n normalize=True)\n\n self.log_features = ops.ToDecibels(device=preprocessing_device, multiplier=np.log(10), reference=1.0,\n cutoff_db=math.log(1e-20))\n\n self.get_shape = ops.Shapes(device=preprocessing_device)\n\n self.normalize = ops.Normalize(device=preprocessing_device, axes=[1])\n\n self.pad = ops.Pad(device=preprocessing_device, fill_value=0)\n\n # Silence trimming\n self.get_nonsilent_region = ops.NonsilentRegion(device=\"cpu\", cutoff_db=silence_threshold)\n self.trim_silence = ops.Slice(device=\"cpu\", normalized_anchor=False, normalized_shape=False, axes=[0])\n self.to_float = ops.Cast(device=\"cpu\", dtype=types.FLOAT)",
"code_sha256": "9d8a610d2ac65ec72a8e5964d0c8e1d66e5fd1228c1a64f171c81a8658782737",
"ast_sha256": "0b3668b99ecdbb60210e0ab0fc0691abcefa567bf92aeb161f415496c94e664f",
"template_ast_sha256": "0b3668b99ecdbb60210e0ab0fc0691abcefa567bf92aeb161f415496c94e664f",
"license_id": "Apache-2.0",
"license_evidence": "inline_apache_notice",
"attribution_notice": "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# DaliPipeline.__init__\nSource: https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_61.parquet#L44-L123\nLicense: Apache-2.0. Syntax checked only; may require original state/files.\nFlags: requires_class_context\n\n```python\nimport nvidia.dali.ops as ops\nimport nvidia.dali.types as types\nimport numpy as np\nimport torch\nimport math\n\ndef __init__(self, *,\n pipeline_type,\n device_id,\n num_threads,\n batch_size,\n file_root: str,\n sampler,\n sample_rate,\n resample_range: list,\n window_size,\n window_stride,\n nfeatures,\n nfft,\n dither_coeff,\n silence_threshold,\n preemph_coeff,\n max_duration,\n preprocessing_device=\"gpu\"):\n super().__init__(batch_size, num_threads, device_id)\n\n self._dali_init_log(locals())\n\n if torch.distributed.is_initialized():\n shard_id = torch.distributed.get_rank()\n n_shards = torch.distributed.get_world_size()\n else:\n shard_id = 0\n n_shards = 1\n\n self.preprocessing_device = preprocessing_device.lower()\n assert self.preprocessing_device == \"cpu\" or self.preprocessing_device == \"gpu\", \\\n \"Incorrect preprocessing device. Please choose either 'cpu' or 'gpu'\"\n\n self.resample_range = resample_range\n\n train_pipeline = pipeline_type == 'train'\n self.train = train_pipeline\n self.sample_rate = sample_rate\n self.dither_coeff = dither_coeff\n self.nfeatures = nfeatures\n self.max_duration = max_duration\n self.do_remove_silence = True if silence_threshold is not None else False\n\n shuffle = train_pipeline and not sampler.is_sampler_random()\n self.read = ops.FileReader(name=\"Reader\", pad_last_batch=(pipeline_type == 'val'), device=\"cpu\", file_root=file_root, file_list=sampler.get_file_list_path(), shard_id=shard_id,\n num_shards=n_shards, shuffle_after_epoch=shuffle)\n\n # TODO change ExternalSource to Uniform for new DALI release\n if resample_range is not None:\n self.speed_perturbation_coeffs = ops.Uniform(device=\"cpu\", range=resample_range)\n else:\n self.speed_perturbation_coeffs = None\n\n self.decode = ops.AudioDecoder(device=\"cpu\", sample_rate=self.sample_rate if resample_range is None else None,\n dtype=types.FLOAT, downmix=True)\n\n self.normal_distribution = ops.NormalDistribution(device=preprocessing_device)\n\n self.preemph = ops.PreemphasisFilter(device=preprocessing_device, preemph_coeff=preemph_coeff)\n\n self.spectrogram = ops.Spectrogram(device=preprocessing_device, nfft=nfft,\n window_length=window_size * sample_rate,\n window_step=window_stride * sample_rate)\n\n self.mel_fbank = ops.MelFilterBank(device=preprocessing_device, sample_rate=sample_rate, nfilter=self.nfeatures,\n normalize=True)\n\n self.log_features = ops.ToDecibels(device=preprocessing_device, multiplier=np.log(10), reference=1.0,\n cutoff_db=math.log(1e-20))\n\n self.get_shape = ops.Shapes(device=preprocessing_device)\n\n self.normalize = ops.Normalize(device=preprocessing_device, axes=[1])\n\n self.pad = ops.Pad(device=preprocessing_device, fill_value=0)\n\n # Silence trimming\n self.get_nonsilent_region = ops.NonsilentRegion(device=\"cpu\", cutoff_db=silence_threshold)\n self.trim_silence = ops.Slice(device=\"cpu\", normalized_anchor=False, normalized_shape=False, axes=[0])\n self.to_float = ops.Cast(device=\"cpu\", dtype=types.FLOAT)\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"math",
"numpy",
"nvidia",
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"requires_class_context"
],
"source_row": 345,
"line_start": 44,
"line_end": 123,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "monster_pytorch_code_10k-f336d0140d62f09f96fc9b70",
"source_id": "monster_pytorch_code_10k",
"source_repo": "Monster-Code/Pytorch-Code-10K",
"source_revision": "99c0ba3cc6b31990a4e4ff1eba13db463a750d35",
"source_path": "data/train_batch_61.parquet",
"source_url": "https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_61.parquet",
"source_group": "79391452fb25d74acbad6c0ec3d5b906620a2d52",
"source_record_id": "79391452fb25d74acbad6c0ec3d5b906620a2d52",
"upstream_track": "frozen",
"authority": "community",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "DaliPipeline._dali_init_log",
"code": "import torch\n\n@staticmethod\ndef _dali_init_log(args: dict):\n if (not torch.distributed.is_initialized() or (\n torch.distributed.is_initialized() and torch.distributed.get_rank() == 0)): # print once\n max_len = max([len(ii) for ii in args.keys()])\n fmt_string = '\\t%' + str(max_len) + 's : %s'\n print('Initializing DALI with parameters:')\n for keyPair in sorted(args.items()):\n print(fmt_string % keyPair)",
"code_sha256": "bf91789f1316df43cf7b6ec9891d09a40a66de190cdcffa4ed8d000a8cb8a4d1",
"ast_sha256": "d4519e56c112a7fabd58840e40da3126ffa321cc6167f4d7fc5df6223d5f517e",
"template_ast_sha256": "d4519e56c112a7fabd58840e40da3126ffa321cc6167f4d7fc5df6223d5f517e",
"license_id": "Apache-2.0",
"license_evidence": "inline_apache_notice",
"attribution_notice": "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# DaliPipeline._dali_init_log\nSource: https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_61.parquet#L169-L176\nLicense: Apache-2.0. Syntax checked only; may require original state/files.\nFlags: requires_class_context\n\n```python\nimport torch\n\n@staticmethod\ndef _dali_init_log(args: dict):\n if (not torch.distributed.is_initialized() or (\n torch.distributed.is_initialized() and torch.distributed.get_rank() == 0)): # print once\n max_len = max([len(ii) for ii in args.keys()])\n fmt_string = '\\t%' + str(max_len) + 's : %s'\n print('Initializing DALI with parameters:')\n for keyPair in sorted(args.items()):\n print(fmt_string % keyPair)\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"requires_class_context"
],
"source_row": 345,
"line_start": 169,
"line_end": 176,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "monster_pytorch_code_10k-b83c90f166c7a75882264b27",
"source_id": "monster_pytorch_code_10k",
"source_repo": "Monster-Code/Pytorch-Code-10K",
"source_revision": "99c0ba3cc6b31990a4e4ff1eba13db463a750d35",
"source_path": "data/train_batch_61.parquet",
"source_url": "https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_61.parquet",
"source_group": "793adde358f7abce99b0e2b29705fcb9b693e34e",
"source_record_id": "793adde358f7abce99b0e2b29705fcb9b693e34e",
"upstream_track": "frozen",
"authority": "community",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "TransformerDecoder.__init__",
"code": "from typing import Callable, Dict, NamedTuple, Optional, Tuple, Union\nimport torch\nfrom torch import nn\nfrom texar.core import layers\nfrom texar.hyperparams import HParams\nfrom texar.modules.decoders.decoder_base import DecoderBase, _make_output_layer\nfrom texar.modules.encoders.multihead_attention import (\n Cache, MultiheadAttentionEncoder)\nfrom texar.modules.networks.networks import FeedForwardNetwork\n\ndef __init__(self,\n vocab_size: Optional[int] = None,\n output_layer: Optional[Union[nn.Module, torch.Tensor]] = None,\n hparams: Optional[HParams] = None):\n super().__init__(0, vocab_size, # dummy value for input_size\n input_time_major=False,\n output_time_major=False, hparams=hparams)\n self._input_size = self._hparams.dim\n\n self._output_layer, self._vocab_size = _make_output_layer(\n output_layer, vocab_size, self._input_size,\n self._hparams.output_layer_bias)\n\n self.self_attns = nn.ModuleList()\n self.self_attn_layer_norm = nn.ModuleList()\n self.enc_dec_attns = nn.ModuleList()\n self.end_dec_attn_layer_norm = nn.ModuleList()\n self.poswise_networks = nn.ModuleList()\n self.poswise_layer_norm = nn.ModuleList()\n\n if self._hparams.use_gpt_config:\n eps = 1e-5\n else:\n eps = 1e-12\n\n for _ in range(self._hparams.num_blocks):\n attn_module = MultiheadAttentionEncoder(\n self._input_size, self._hparams.multihead_attention)\n if self._hparams.dim != attn_module.output_size:\n raise ValueError(\"The output dimension of \"\n \"MultiheadEncoder should be equal \"\n \"to the dim of TransformerDecoder\")\n self.self_attns.append(attn_module)\n self.self_attn_layer_norm.append(\n nn.LayerNorm(self._input_size, eps=eps))\n\n attn_module = MultiheadAttentionEncoder(\n self._input_size, self._hparams.multihead_attention)\n if self._hparams.dim != attn_module.output_size:\n raise ValueError(\"The output dimension of \"\n \"MultiheadEncoder should be equal \"\n \"to the dim of TransformerDecoder\")\n self.enc_dec_attns.append(attn_module)\n self.end_dec_attn_layer_norm.append(\n nn.LayerNorm(self._input_size, eps=eps))\n\n poswise_network = FeedForwardNetwork(\n hparams=self._hparams.poswise_feedforward)\n if (poswise_network.hparams.layers[-1]['kwargs']['out_features']\n != self._hparams.dim):\n raise ValueError(\"The output dimension of \"\n \"FeedForwardNetwork should be equal \"\n \"to the dim of TransformerDecoder\")\n self.poswise_networks.append(poswise_network)\n self.poswise_layer_norm.append(\n nn.LayerNorm(self._input_size, eps=eps))\n\n self.final_layer_norm = nn.LayerNorm(self._input_size, eps=eps)\n self.embed_dropout = nn.Dropout(self._hparams.embedding_dropout)\n self.residual_dropout = nn.Dropout(self._hparams.residual_dropout)\n\n if self._hparams.initializer:\n # TODO: This might be different to what TensorFlow does\n initialize = layers.get_initializer(self._hparams.initializer)\n assert initialize is not None\n # Do not re-initialize LayerNorm modules.\n for name, param in self.named_parameters():\n if name.split(\".\")[-1] == \"weight\" and \"layer_norm\" not in name:\n initialize(param)",
"code_sha256": "e02a07e67d72534deda18548084532a5252738a8a4f935776b829fd48518c730",
"ast_sha256": "64eaf8fd7399b0146681d2306503c1ffc65629b9d11e6cabf1a65c8b1905a2d1",
"template_ast_sha256": "64eaf8fd7399b0146681d2306503c1ffc65629b9d11e6cabf1a65c8b1905a2d1",
"license_id": "Apache-2.0",
"license_evidence": "inline_apache_notice",
"attribution_notice": "# Copyright 2019 The Texar Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nTransformer decoder.\n\"\"\"\n",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# TransformerDecoder.__init__\nSource: https://huggingface.co/datasets/Monster-Code/Pytorch-Code-10K/blob/99c0ba3cc6b31990a4e4ff1eba13db463a750d35/data/train_batch_61.parquet#L92-L160\nLicense: Apache-2.0. Syntax checked only; may require original state/files.\nFlags: requires_class_context\n\n```python\nfrom typing import Callable, Dict, NamedTuple, Optional, Tuple, Union\nimport torch\nfrom torch import nn\nfrom texar.core import layers\nfrom texar.hyperparams import HParams\nfrom texar.modules.decoders.decoder_base import DecoderBase, _make_output_layer\nfrom texar.modules.encoders.multihead_attention import (\n Cache, MultiheadAttentionEncoder)\nfrom texar.modules.networks.networks import FeedForwardNetwork\n\ndef __init__(self,\n vocab_size: Optional[int] = None,\n output_layer: Optional[Union[nn.Module, torch.Tensor]] = None,\n hparams: Optional[HParams] = None):\n super().__init__(0, vocab_size, # dummy value for input_size\n input_time_major=False,\n output_time_major=False, hparams=hparams)\n self._input_size = self._hparams.dim\n\n self._output_layer, self._vocab_size = _make_output_layer(\n output_layer, vocab_size, self._input_size,\n self._hparams.output_layer_bias)\n\n self.self_attns = nn.ModuleList()\n self.self_attn_layer_norm = nn.ModuleList()\n self.enc_dec_attns = nn.ModuleList()\n self.end_dec_attn_layer_norm = nn.ModuleList()\n self.poswise_networks = nn.ModuleList()\n self.poswise_layer_norm = nn.ModuleList()\n\n if self._hparams.use_gpt_config:\n eps = 1e-5\n else:\n eps = 1e-12\n\n for _ in range(self._hparams.num_blocks):\n attn_module = MultiheadAttentionEncoder(\n self._input_size, self._hparams.multihead_attention)\n if self._hparams.dim != attn_module.output_size:\n raise ValueError(\"The output dimension of \"\n \"MultiheadEncoder should be equal \"\n \"to the dim of TransformerDecoder\")\n self.self_attns.append(attn_module)\n self.self_attn_layer_norm.append(\n nn.LayerNorm(self._input_size, eps=eps))\n\n attn_module = MultiheadAttentionEncoder(\n self._input_size, self._hparams.multihead_attention)\n if self._hparams.dim != attn_module.output_size:\n raise ValueError(\"The output dimension of \"\n \"MultiheadEncoder should be equal \"\n \"to the dim of TransformerDecoder\")\n self.enc_dec_attns.append(attn_module)\n self.end_dec_attn_layer_norm.append(\n nn.LayerNorm(self._input_size, eps=eps))\n\n poswise_network = FeedForwardNetwork(\n hparams=self._hparams.poswise_feedforward)\n if (poswise_network.hparams.layers[-1]['kwargs']['out_features']\n != self._hparams.dim):\n raise ValueError(\"The output dimension of \"\n \"FeedForwardNetwork should be equal \"\n \"to the dim of TransformerDecoder\")\n self.poswise_networks.append(poswise_network)\n self.poswise_layer_norm.append(\n nn.LayerNorm(self._input_size, eps=eps))\n\n self.final_layer_norm = nn.LayerNorm(self._input_size, eps=eps)\n self.embed_dropout = nn.Dropout(self._hparams.embedding_dropout)\n self.residual_dropout = nn.Dropout(self._hparams.residual_dropout)\n\n if self._hparams.initializer:\n # TODO: This might be different to what TensorFlow does\n initialize = layers.get_initializer(self._hparams.initializer)\n assert initialize is not None\n # Do not re-initialize LayerNorm modules.\n for name, param in self.named_parameters():\n if name.split(\".\")[-1] == \"weight\" and \"layer_norm\" not in name:\n initialize(param)\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"texar",
"torch",
"typing"
],
"unresolved_names": [],
"compatibility_flags": [
"requires_class_context"
],
"source_row": 369,
"line_start": 92,
"line_end": 160,
"external_data_required": false,
"benchmark_content": false
}
],
"pytorch_examples": [
{
"record_id": "pytorch_examples-4d787d33266f408d71b5e47b",
"source_id": "pytorch_examples",
"source_repo": "pytorch/examples",
"source_revision": "acc295dc7b90714f1bf47f06004fc19a7fe235c4",
"source_path": "mnist/main.py",
"source_url": "https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/mnist/main.py",
"source_group": "mnist",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "Net",
"code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout(0.25)\n self.dropout2 = nn.Dropout(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output",
"code_sha256": "6ce81808dc570dc4d75a32f5ebc0e33edf88ac7350e8bf191309d1284b712d2b",
"ast_sha256": "f2087cb9715b3041f0374430e5f61cce36272b43b9d63b72a16ef7504e764fec",
"template_ast_sha256": "f2087cb9715b3041f0374430e5f61cce36272b43b9d63b72a16ef7504e764fec",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Net\nSource: https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/mnist/main.py#L10-L33\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: main_snapshot_not_runtime_verified\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout(0.25)\n self.dropout2 = nn.Dropout(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n```\n",
"metadata_json": "{}",
"topics": [
"cnn_from_scratch_candidate",
"computer_vision",
"pytorch",
"tensor_shapes"
],
"packages": [
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 10,
"line_end": 33,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "pytorch_examples-95179a32a6f6fcb78da5e403",
"source_id": "pytorch_examples",
"source_repo": "pytorch/examples",
"source_revision": "acc295dc7b90714f1bf47f06004fc19a7fe235c4",
"source_path": "mnist/main.py",
"source_url": "https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/mnist/main.py",
"source_group": "mnist",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "train",
"code": "import torch.nn.functional as F\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n if args.dry_run:\n break",
"code_sha256": "60164f5ab73364d7ab18e8f2977472487d63634c655bcc0950b6fe61bd97a003",
"ast_sha256": "1c725d1a58d78eba2e90287772892b49b15864f00dfc31995095f7758ce02642",
"template_ast_sha256": "1c725d1a58d78eba2e90287772892b49b15864f00dfc31995095f7758ce02642",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# train\nSource: https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/mnist/main.py#L36-L50\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: main_snapshot_not_runtime_verified\n\n```python\nimport torch.nn.functional as F\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n if args.dry_run:\n break\n```\n",
"metadata_json": "{}",
"topics": [
"loss_functions",
"pytorch",
"training_loop"
],
"packages": [
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 36,
"line_end": 50,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "pytorch_examples-306e8be57d2e5d20ccf85ddf",
"source_id": "pytorch_examples",
"source_repo": "pytorch/examples",
"source_revision": "acc295dc7b90714f1bf47f06004fc19a7fe235c4",
"source_path": "mnist/main.py",
"source_url": "https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/mnist/main.py",
"source_group": "mnist",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "test",
"code": "import torch\nimport torch.nn.functional as F\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))",
"code_sha256": "0cd332c0591175aad7c611dbed6d516882607e2d5ae69a9e3f01d345e34a76f7",
"ast_sha256": "dd92cbea81fc6b6d83cd92e71d5b540daf01036c7a767c831d129666487c611b",
"template_ast_sha256": "dd92cbea81fc6b6d83cd92e71d5b540daf01036c7a767c831d129666487c611b",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# test\nSource: https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/mnist/main.py#L53-L69\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: main_snapshot_not_runtime_verified\n\n```python\nimport torch\nimport torch.nn.functional as F\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n```\n",
"metadata_json": "{}",
"topics": [
"evaluation",
"loss_functions",
"pytorch"
],
"packages": [
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 53,
"line_end": 69,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "pytorch_examples-ca1d663ae02a19b272270547",
"source_id": "pytorch_examples",
"source_repo": "pytorch/examples",
"source_revision": "acc295dc7b90714f1bf47f06004fc19a7fe235c4",
"source_path": "cpp/dcgan/display_samples.py",
"source_url": "https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/cpp/dcgan/display_samples.py",
"source_group": "cpp",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "train",
"symbol": "top_level_statements",
"code": "from __future__ import print_function\nfrom __future__ import unicode_literals\nimport argparse\nimport matplotlib.pyplot as plt\nimport torch\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--sample-file\", required=True)\nparser.add_argument(\"-o\", \"--out-file\", default=\"out.png\")\nparser.add_argument(\"-d\", \"--dimension\", type=int, default=3)\noptions = parser.parse_args()\n\nmodule = torch.jit.load(options.sample_file)\nimages = list(module.parameters())[0]\n\nfor index in range(options.dimension * options.dimension):\n image = images[index].detach().cpu().reshape(28, 28).mul(255).to(torch.uint8)\n array = image.numpy()\n axis = plt.subplot(options.dimension, options.dimension, 1 + index)\n plt.imshow(array, cmap=\"gray\")\n axis.get_xaxis().set_visible(False)\n axis.get_yaxis().set_visible(False)\n\nplt.savefig(options.out_file)\nprint(\"Saved \", options.out_file)",
"code_sha256": "1fec1f788a3d2594bc80e2d764551a0ae505d38c1c0f6c7045d555546da3803b",
"ast_sha256": "6171e367d16cb4ef587e8f56259de4f46d5586ef3538a59c1d9a9e203b3be9c7",
"template_ast_sha256": "6171e367d16cb4ef587e8f56259de4f46d5586ef3538a59c1d9a9e203b3be9c7",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# top_level_statements\nSource: https://github.com/pytorch/examples/blob/acc295dc7b90714f1bf47f06004fc19a7fe235c4/cpp/dcgan/display_samples.py#L10-L28\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: private_or_project_module, main_snapshot_not_runtime_verified\n\n```python\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport argparse\nimport matplotlib.pyplot as plt\nimport torch\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--sample-file\", required=True)\nparser.add_argument(\"-o\", \"--out-file\", default=\"out.png\")\nparser.add_argument(\"-d\", \"--dimension\", type=int, default=3)\noptions = parser.parse_args()\n\nmodule = torch.jit.load(options.sample_file)\nimages = list(module.parameters())[0]\n\nfor index in range(options.dimension * options.dimension):\n image = images[index].detach().cpu().reshape(28, 28).mul(255).to(torch.uint8)\n array = image.numpy()\n axis = plt.subplot(options.dimension, options.dimension, 1 + index)\n plt.imshow(array, cmap=\"gray\")\n axis.get_xaxis().set_visible(False)\n axis.get_yaxis().set_visible(False)\n\nplt.savefig(options.out_file)\nprint(\"Saved \", options.out_file)\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch",
"tensor_shapes"
],
"packages": [
"__future__",
"argparse",
"matplotlib",
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"private_or_project_module",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 10,
"line_end": 28,
"external_data_required": false,
"benchmark_content": false
}
],
"pytorch_tutorials": [
{
"record_id": "pytorch_tutorials-8f96b0d99df955d2da3477a6",
"source_id": "pytorch_tutorials",
"source_repo": "pytorch/tutorials",
"source_revision": "c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6",
"source_path": "advanced_source/coding_ddpg.py",
"source_url": "https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py",
"source_group": "advanced_source/coding_ddpg.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "top_level_statements",
"code": "import warnings\nfrom torch import multiprocessing\nimport torch\n\nwarnings.filterwarnings(\"ignore\")\nfrom torch import multiprocessing\n\n# TorchRL prefers spawn method, that restricts creation of ``~torchrl.envs.ParallelEnv`` inside\n# `__main__` method call, but for the easy of reading the code switch to fork\n# which is also a default spawn method in Google's Colaboratory\ntry:\n multiprocessing.set_start_method(\"fork\")\nexcept RuntimeError:\n pass\n\n# sphinx_gallery_end_ignore\n\n\nimport torch\nimport tqdm\n\n\n###############################################################################\n# We will execute the policy on CUDA if available\nis_fork = multiprocessing.get_start_method() == \"fork\"\ndevice = (\n torch.device(0)\n if torch.cuda.is_available() and not is_fork\n else torch.device(\"cpu\")\n)\ncollector_device = torch.device(\"cpu\") # Change the device to ``cuda`` to use CUDA",
"code_sha256": "f1c193a6be52f50c9168680ecba66297a72801914b4d842d48ea453abc0962b8",
"ast_sha256": "2b9e256c474b2304d69e1247997990f5f2036863bb84e1ff27f0d9d957ab5503",
"template_ast_sha256": "2b9e256c474b2304d69e1247997990f5f2036863bb84e1ff27f0d9d957ab5503",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "# -*- coding: utf-8 -*-\n\"\"\"\nTorchRL objectives: Coding a DDPG loss\n======================================\n**Author**: `Vincent Moens <https://github.com/vmoens>`_\n\n\"\"\"\n\n##############################################################################\n# Overview\n# --------\n#\n# TorchRL separates the training of RL algorithms in various pieces that will be\n# assembled in your training script: the environment, the data collection and\n# storage, the model and finally the loss function.\n#\n# TorchRL losses (or \"objectives\") are stateful objects that contain the\n# trainable parameters (policy and value models).\n# This tutorial will guide you through the steps to code a loss from the ground up\n# using TorchRL.\n#\n# To this aim, we will be focusing on DDPG, which is a relatively straightforward\n# algorithm to code.\n# `Deep Deterministic Policy Gradient <https://arxiv.org/abs/1509.02971>`_ (DDPG)\n# is a simple continuous control algorithm. It consists in learning a\n# parametric value function for an action-observation pair, and\n# then learning a policy that outputs actions that maximize this value\n# function given a certain observation.\n#\n# What you will learn:\n#\n# - how to write a loss module and customize its value estimator;\n# - how to build an environment in TorchRL, including transforms\n# (for example, data normalization) and parallel execution;\n# - how to design a policy and value network;\n# - how to collect data from your environment efficiently and store them\n# in a replay buffer;\n# - how to store trajectories (and not transitions) in your replay buffer);\n# - how to evaluate your model.\n#\n# Prerequisites\n# ~~~~~~~~~~~~~\n#\n# This tutorial assumes that you have completed the\n# `PPO tutorial <reinforcement_ppo.html>`_ which gives\n# an overview of the TorchRL components and dependencies, such as\n# :class:`tensordict.TensorDict` and :class:`tensordict.nn.TensorDictModules`,\n# although it should be\n# sufficiently transparent to be understood without a deep understanding of\n# these classes.\n#\n# .. note::\n# We do not aim at giving a SOTA implementation of the algorithm, but rather\n# to provide a high-level illustration of TorchRL's loss implementations\n# and the library features that are to be used in the context of\n# this algorithm.\n#\n# Imports and setup\n# -----------------\n#\n# .. code-block:: bash\n#\n# %%bash\n# pip3 install torchrl mujoco glfw\n\n# sphinx_gallery_start_ignore",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# top_level_statements\nSource: https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py#L69-L95\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: suppresses_warnings, main_snapshot_not_runtime_verified\n\n```python\nimport warnings\nfrom torch import multiprocessing\nimport torch\n\nwarnings.filterwarnings(\"ignore\")\nfrom torch import multiprocessing\n\n# TorchRL prefers spawn method, that restricts creation of ``~torchrl.envs.ParallelEnv`` inside\n# `__main__` method call, but for the easy of reading the code switch to fork\n# which is also a default spawn method in Google's Colaboratory\ntry:\n multiprocessing.set_start_method(\"fork\")\nexcept RuntimeError:\n pass\n\n# sphinx_gallery_end_ignore\n\n\nimport torch\nimport tqdm\n\n\n###############################################################################\n# We will execute the policy on CUDA if available\nis_fork = multiprocessing.get_start_method() == \"fork\"\ndevice = (\n torch.device(0)\n if torch.cuda.is_available() and not is_fork\n else torch.device(\"cpu\")\n)\ncollector_device = torch.device(\"cpu\") # Change the device to ``cuda`` to use CUDA\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"torch",
"tqdm",
"warnings"
],
"unresolved_names": [],
"compatibility_flags": [
"suppresses_warnings",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 69,
"line_end": 95,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "pytorch_tutorials-b3a58448b1c735ab967fd107",
"source_id": "pytorch_tutorials",
"source_repo": "pytorch/tutorials",
"source_revision": "c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6",
"source_path": "advanced_source/coding_ddpg.py",
"source_url": "https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py",
"source_group": "advanced_source/coding_ddpg.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "top_level_statements",
"code": "import torch\nfrom tensordict.nn import TensorDictModule, TensorDictSequential\nfrom torchrl.modules import (\n ActorCriticWrapper,\n DdpgMlpActor,\n DdpgMlpQNet,\n OrnsteinUhlenbeckProcessModule,\n ProbabilisticActor,\n TanhDelta,\n ValueOperator,\n)\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.envs import ExplorationType\n\nactor, qnet = make_ddpg_actor(\n transform_state_dict=transform_state_dict,\n device=device,\n)\n\n###############################################################################\n# Exploration\n# ~~~~~~~~~~~\n#\n# The policy is passed into a :class:`~torchrl.modules.OrnsteinUhlenbeckProcessModule`\n# exploration module, as suggested in the original paper.\n# Let's define the number of frames before OU noise reaches its minimum value\nannealing_frames = 1_000_000\n\nactor_model_explore = TensorDictSequential(\n actor,\n OrnsteinUhlenbeckProcessModule(\n spec=actor.spec.clone(),\n annealing_num_steps=annealing_frames,\n ).to(device),\n)\nif device == torch.device(\"cpu\"):\n actor_model_explore.share_memory()\n\n\n###############################################################################\n# Data collector\n# --------------\n#\n# TorchRL provides specialized classes to help you collect data by executing\n# the policy in the environment. These \"data collectors\" iteratively compute\n# the action to be executed at a given time, then execute a step in the\n# environment and reset it when required.\n# Data collectors are designed to help developers have a tight control\n# on the number of frames per batch of data, on the (a)sync nature of this\n# collection and on the resources allocated to the data collection (for example\n# GPU, number of workers, and so on).\n#\n# Here we will use\n# :class:`~torchrl.collectors.SyncDataCollector`, a simple, single-process\n# data collector. TorchRL offers other collectors, such as\n# :class:`~torchrl.collectors.MultiaSyncDataCollector`, which executed the\n# rollouts in an asynchronous manner (for example, data will be collected while\n# the policy is being optimized, thereby decoupling the training and\n# data collection).\n#\n# The parameters to specify are:\n#\n# - an environment factory or an environment,\n# - the policy,\n# - the total number of frames before the collector is considered empty,\n# - the maximum number of frames per trajectory (useful for non-terminating\n# environments, like ``dm_control`` ones).\n#\n# .. note::\n#\n# The ``max_frames_per_traj`` passed to the collector will have the effect\n# of registering a new :class:`~torchrl.envs.StepCounter` transform\n# with the environment used for inference. We can achieve the same result\n# manually, as we do in this script.\n#\n# One should also pass:\n#\n# - the number of frames in each batch collected,\n# - the number of random steps executed independently from the policy,\n# - the devices used for policy execution\n# - the devices used to store data before the data is passed to the main\n# process.\n#\n# The total frames we will use during training should be around 1M.\ntotal_frames = 10_000 # 1_000_000\n\n###############################################################################\n# The number of frames returned by the collector at each iteration of the outer\n# loop is equal to the length of each sub-trajectories times the number of\n# environments run in parallel in each collector.\n#\n# In other words, we expect batches from the collector to have a shape\n# ``[env_per_collector, traj_len]`` where\n# ``traj_len=frames_per_batch/env_per_collector``:\n#\ntraj_len = 200\nframes_per_batch = env_per_collector * traj_len\ninit_random_frames = 5000\nnum_collectors = 2\n\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.envs import ExplorationType\n\ncollector = SyncDataCollector(\n parallel_env,\n policy=actor_model_explore,\n total_frames=total_frames,\n frames_per_batch=frames_per_batch,\n init_random_frames=init_random_frames,\n reset_at_each_iter=False,\n split_trajs=False,\n device=collector_device,\n exploration_type=ExplorationType.RANDOM,\n)",
"code_sha256": "954f0452f9e5d938f567a769baffbb26491aa0cd37ed576d03866f4b4975e1bc",
"ast_sha256": "ea554bc310418a2b0a722cbc8d6664d66a55ff890fb7f7211f3582b8eef7e936",
"template_ast_sha256": "ea554bc310418a2b0a722cbc8d6664d66a55ff890fb7f7211f3582b8eef7e936",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "# -*- coding: utf-8 -*-\n\"\"\"\nTorchRL objectives: Coding a DDPG loss\n======================================\n**Author**: `Vincent Moens <https://github.com/vmoens>`_\n\n\"\"\"\n\n##############################################################################\n# Overview\n# --------\n#\n# TorchRL separates the training of RL algorithms in various pieces that will be\n# assembled in your training script: the environment, the data collection and\n# storage, the model and finally the loss function.\n#\n# TorchRL losses (or \"objectives\") are stateful objects that contain the\n# trainable parameters (policy and value models).\n# This tutorial will guide you through the steps to code a loss from the ground up\n# using TorchRL.\n#\n# To this aim, we will be focusing on DDPG, which is a relatively straightforward\n# algorithm to code.\n# `Deep Deterministic Policy Gradient <https://arxiv.org/abs/1509.02971>`_ (DDPG)\n# is a simple continuous control algorithm. It consists in learning a\n# parametric value function for an action-observation pair, and\n# then learning a policy that outputs actions that maximize this value\n# function given a certain observation.\n#\n# What you will learn:\n#\n# - how to write a loss module and customize its value estimator;\n# - how to build an environment in TorchRL, including transforms\n# (for example, data normalization) and parallel execution;\n# - how to design a policy and value network;\n# - how to collect data from your environment efficiently and store them\n# in a replay buffer;\n# - how to store trajectories (and not transitions) in your replay buffer);\n# - how to evaluate your model.\n#\n# Prerequisites\n# ~~~~~~~~~~~~~\n#\n# This tutorial assumes that you have completed the\n# `PPO tutorial <reinforcement_ppo.html>`_ which gives\n# an overview of the TorchRL components and dependencies, such as\n# :class:`tensordict.TensorDict` and :class:`tensordict.nn.TensorDictModules`,\n# although it should be\n# sufficiently transparent to be understood without a deep understanding of\n# these classes.\n#\n# .. note::\n# We do not aim at giving a SOTA implementation of the algorithm, but rather\n# to provide a high-level illustration of TorchRL's loss implementations\n# and the library features that are to be used in the context of\n# this algorithm.\n#\n# Imports and setup\n# -----------------\n#\n# .. code-block:: bash\n#\n# %%bash\n# pip3 install torchrl mujoco glfw\n\n# sphinx_gallery_start_ignore",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# top_level_statements\nSource: https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py#L769-L868\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: requires_prior_state_or_project_modules, main_snapshot_not_runtime_verified\n\n```python\nimport torch\nfrom tensordict.nn import TensorDictModule, TensorDictSequential\nfrom torchrl.modules import (\n ActorCriticWrapper,\n DdpgMlpActor,\n DdpgMlpQNet,\n OrnsteinUhlenbeckProcessModule,\n ProbabilisticActor,\n TanhDelta,\n ValueOperator,\n)\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.envs import ExplorationType\n\nactor, qnet = make_ddpg_actor(\n transform_state_dict=transform_state_dict,\n device=device,\n)\n\n###############################################################################\n# Exploration\n# ~~~~~~~~~~~\n#\n# The policy is passed into a :class:`~torchrl.modules.OrnsteinUhlenbeckProcessModule`\n# exploration module, as suggested in the original paper.\n# Let's define the number of frames before OU noise reaches its minimum value\nannealing_frames = 1_000_000\n\nactor_model_explore = TensorDictSequential(\n actor,\n OrnsteinUhlenbeckProcessModule(\n spec=actor.spec.clone(),\n annealing_num_steps=annealing_frames,\n ).to(device),\n)\nif device == torch.device(\"cpu\"):\n actor_model_explore.share_memory()\n\n\n###############################################################################\n# Data collector\n# --------------\n#\n# TorchRL provides specialized classes to help you collect data by executing\n# the policy in the environment. These \"data collectors\" iteratively compute\n# the action to be executed at a given time, then execute a step in the\n# environment and reset it when required.\n# Data collectors are designed to help developers have a tight control\n# on the number of frames per batch of data, on the (a)sync nature of this\n# collection and on the resources allocated to the data collection (for example\n# GPU, number of workers, and so on).\n#\n# Here we will use\n# :class:`~torchrl.collectors.SyncDataCollector`, a simple, single-process\n# data collector. TorchRL offers other collectors, such as\n# :class:`~torchrl.collectors.MultiaSyncDataCollector`, which executed the\n# rollouts in an asynchronous manner (for example, data will be collected while\n# the policy is being optimized, thereby decoupling the training and\n# data collection).\n#\n# The parameters to specify are:\n#\n# - an environment factory or an environment,\n# - the policy,\n# - the total number of frames before the collector is considered empty,\n# - the maximum number of frames per trajectory (useful for non-terminating\n# environments, like ``dm_control`` ones).\n#\n# .. note::\n#\n# The ``max_frames_per_traj`` passed to the collector will have the effect\n# of registering a new :class:`~torchrl.envs.StepCounter` transform\n# with the environment used for inference. We can achieve the same result\n# manually, as we do in this script.\n#\n# One should also pass:\n#\n# - the number of frames in each batch collected,\n# - the number of random steps executed independently from the policy,\n# - the devices used for policy execution\n# - the devices used to store data before the data is passed to the main\n# process.\n#\n# The total frames we will use during training should be around 1M.\ntotal_frames = 10_000 # 1_000_000\n\n###############################################################################\n# The number of frames returned by the collector at each iteration of the outer\n# loop is equal to the length of each sub-trajectories times the number of\n# environments run in parallel in each collector.\n#\n# In other words, we expect batches from the collector to have a shape\n# ``[env_per_collector, traj_len]`` where\n# ``traj_len=frames_per_batch/env_per_collector``:\n#\ntraj_len = 200\nframes_per_batch = env_per_collector * traj_len\ninit_random_frames = 5000\nnum_collectors = 2\n\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.envs import ExplorationType\n\ncollector = SyncDataCollector(\n parallel_env,\n policy=actor_model_explore,\n total_frames=total_frames,\n frames_per_batch=frames_per_batch,\n init_random_frames=init_random_frames,\n reset_at_each_iter=False,\n split_trajs=False,\n device=collector_device,\n exploration_type=ExplorationType.RANDOM,\n)\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"tensordict",
"torch",
"torchrl"
],
"unresolved_names": [
"collector_device",
"device",
"env_per_collector",
"make_ddpg_actor",
"parallel_env",
"transform_state_dict"
],
"compatibility_flags": [
"requires_prior_state_or_project_modules",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 769,
"line_end": 868,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "pytorch_tutorials-96e3132017ac15d1279ac16d",
"source_id": "pytorch_tutorials",
"source_repo": "pytorch/tutorials",
"source_revision": "c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6",
"source_path": "advanced_source/coding_ddpg.py",
"source_url": "https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py",
"source_group": "advanced_source/coding_ddpg.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "top_level_statements",
"code": "import tqdm\nfrom torchrl.objectives.utils import ValueEstimators\nfrom torchrl.objectives.utils import SoftUpdate\nfrom torch import optim\n\nbuffer_size = 1_000_000\nbuffer_size = ceil_div(buffer_size, traj_len)\n\n###############################################################################\n# Prioritized replay buffer is disabled by default\nprb = False\n\n###############################################################################\n# We also need to define how many updates we'll be doing per batch of data\n# collected. This is known as the update-to-data or ``UTD`` ratio:\nupdate_to_data = 64\n\n###############################################################################\n# We'll be feeding the loss with trajectories of length 25:\nrandom_crop_len = 25\n\n###############################################################################\n# In the original paper, the authors perform one update with a batch of 64\n# elements for each frame collected. Here, we reproduce the same ratio\n# but while realizing several updates at each batch collection. We\n# adapt our batch-size to achieve the same number of update-per-frame ratio:\n\nbatch_size = ceil_div(64 * frames_per_batch, update_to_data * random_crop_len)\n\nreplay_buffer = make_replay_buffer(\n buffer_size=buffer_size,\n batch_size=batch_size,\n random_crop_len=random_crop_len,\n prefetch=3,\n prb=prb,\n)\n\n###############################################################################\n# Loss module construction\n# ------------------------\n#\n# We build our loss module with the actor and ``qnet`` we've just created.\n# Because we have target parameters to update, we _must_ create a target network\n# updater.\n#\n\ngamma = 0.99\nlmbda = 0.9\ntau = 0.001 # Decay factor for the target network\n\nloss_module = DDPGLoss(actor, qnet)\n\n###############################################################################\n# let's use the TD(lambda) estimator!\nloss_module.make_value_estimator(ValueEstimators.TDLambda, gamma=gamma, lmbda=lmbda, device=device)\n\n###############################################################################\n# .. note::\n# Off-policy usually dictates a TD(0) estimator. Here, we use a TD(:math:`\\lambda`)\n# estimator, which will introduce some bias as the trajectory that follows\n# a certain state has been collected with an outdated policy.\n# This trick, as the multi-step trick that can be used during data collection,\n# are alternative versions of \"hacks\" that we usually find to work well in\n# practice despite the fact that they introduce some bias in the return\n# estimates.\n#\n# Target network updater\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# Target networks are a crucial part of off-policy RL algorithms.\n# Updating the target network parameters is made easy thanks to the\n# :class:`~torchrl.objectives.HardUpdate` and :class:`~torchrl.objectives.SoftUpdate`\n# classes. They're built with the loss module as argument, and the update is\n# achieved via a call to `updater.step()` at the appropriate location in the\n# training loop.\n\nfrom torchrl.objectives.utils import SoftUpdate\n\ntarget_net_updater = SoftUpdate(loss_module, eps=1 - tau)\n\n###############################################################################\n# Optimizer\n# ~~~~~~~~~\n#\n# Finally, we will use the Adam optimizer for the policy and value network:\n\nfrom torch import optim\n\noptimizer_actor = optim.Adam(\n loss_module.actor_network_params.values(True, True), lr=1e-4, weight_decay=0.0\n)\noptimizer_value = optim.Adam(\n loss_module.value_network_params.values(True, True), lr=1e-3, weight_decay=1e-2\n)\ntotal_collection_steps = total_frames // frames_per_batch\n\n###############################################################################\n# Time to train the policy\n# ------------------------\n#\n# The training loop is pretty straightforward now that we have built all the\n# modules we need.\n#\n\nrewards = []\nrewards_eval = []\n\n# Main loop\n\ncollected_frames = 0\npbar = tqdm.tqdm(total=total_frames)\nr0 = None",
"code_sha256": "e8a26181aba25604a269daaba8a108af1b70e407c591f59d2c1062288c562b80",
"ast_sha256": "a9ea00d5910bbb1dbba3e04eafb21781401a59dd7c3f605df87eaeb59ad5b090",
"template_ast_sha256": "a9ea00d5910bbb1dbba3e04eafb21781401a59dd7c3f605df87eaeb59ad5b090",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "# -*- coding: utf-8 -*-\n\"\"\"\nTorchRL objectives: Coding a DDPG loss\n======================================\n**Author**: `Vincent Moens <https://github.com/vmoens>`_\n\n\"\"\"\n\n##############################################################################\n# Overview\n# --------\n#\n# TorchRL separates the training of RL algorithms in various pieces that will be\n# assembled in your training script: the environment, the data collection and\n# storage, the model and finally the loss function.\n#\n# TorchRL losses (or \"objectives\") are stateful objects that contain the\n# trainable parameters (policy and value models).\n# This tutorial will guide you through the steps to code a loss from the ground up\n# using TorchRL.\n#\n# To this aim, we will be focusing on DDPG, which is a relatively straightforward\n# algorithm to code.\n# `Deep Deterministic Policy Gradient <https://arxiv.org/abs/1509.02971>`_ (DDPG)\n# is a simple continuous control algorithm. It consists in learning a\n# parametric value function for an action-observation pair, and\n# then learning a policy that outputs actions that maximize this value\n# function given a certain observation.\n#\n# What you will learn:\n#\n# - how to write a loss module and customize its value estimator;\n# - how to build an environment in TorchRL, including transforms\n# (for example, data normalization) and parallel execution;\n# - how to design a policy and value network;\n# - how to collect data from your environment efficiently and store them\n# in a replay buffer;\n# - how to store trajectories (and not transitions) in your replay buffer);\n# - how to evaluate your model.\n#\n# Prerequisites\n# ~~~~~~~~~~~~~\n#\n# This tutorial assumes that you have completed the\n# `PPO tutorial <reinforcement_ppo.html>`_ which gives\n# an overview of the TorchRL components and dependencies, such as\n# :class:`tensordict.TensorDict` and :class:`tensordict.nn.TensorDictModules`,\n# although it should be\n# sufficiently transparent to be understood without a deep understanding of\n# these classes.\n#\n# .. note::\n# We do not aim at giving a SOTA implementation of the algorithm, but rather\n# to provide a high-level illustration of TorchRL's loss implementations\n# and the library features that are to be used in the context of\n# this algorithm.\n#\n# Imports and setup\n# -----------------\n#\n# .. code-block:: bash\n#\n# %%bash\n# pip3 install torchrl mujoco glfw\n\n# sphinx_gallery_start_ignore",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# top_level_statements\nSource: https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py#L994-L1100\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: requires_prior_state_or_project_modules, main_snapshot_not_runtime_verified\n\n```python\nimport tqdm\nfrom torchrl.objectives.utils import ValueEstimators\nfrom torchrl.objectives.utils import SoftUpdate\nfrom torch import optim\n\nbuffer_size = 1_000_000\nbuffer_size = ceil_div(buffer_size, traj_len)\n\n###############################################################################\n# Prioritized replay buffer is disabled by default\nprb = False\n\n###############################################################################\n# We also need to define how many updates we'll be doing per batch of data\n# collected. This is known as the update-to-data or ``UTD`` ratio:\nupdate_to_data = 64\n\n###############################################################################\n# We'll be feeding the loss with trajectories of length 25:\nrandom_crop_len = 25\n\n###############################################################################\n# In the original paper, the authors perform one update with a batch of 64\n# elements for each frame collected. Here, we reproduce the same ratio\n# but while realizing several updates at each batch collection. We\n# adapt our batch-size to achieve the same number of update-per-frame ratio:\n\nbatch_size = ceil_div(64 * frames_per_batch, update_to_data * random_crop_len)\n\nreplay_buffer = make_replay_buffer(\n buffer_size=buffer_size,\n batch_size=batch_size,\n random_crop_len=random_crop_len,\n prefetch=3,\n prb=prb,\n)\n\n###############################################################################\n# Loss module construction\n# ------------------------\n#\n# We build our loss module with the actor and ``qnet`` we've just created.\n# Because we have target parameters to update, we _must_ create a target network\n# updater.\n#\n\ngamma = 0.99\nlmbda = 0.9\ntau = 0.001 # Decay factor for the target network\n\nloss_module = DDPGLoss(actor, qnet)\n\n###############################################################################\n# let's use the TD(lambda) estimator!\nloss_module.make_value_estimator(ValueEstimators.TDLambda, gamma=gamma, lmbda=lmbda, device=device)\n\n###############################################################################\n# .. note::\n# Off-policy usually dictates a TD(0) estimator. Here, we use a TD(:math:`\\lambda`)\n# estimator, which will introduce some bias as the trajectory that follows\n# a certain state has been collected with an outdated policy.\n# This trick, as the multi-step trick that can be used during data collection,\n# are alternative versions of \"hacks\" that we usually find to work well in\n# practice despite the fact that they introduce some bias in the return\n# estimates.\n#\n# Target network updater\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# Target networks are a crucial part of off-policy RL algorithms.\n# Updating the target network parameters is made easy thanks to the\n# :class:`~torchrl.objectives.HardUpdate` and :class:`~torchrl.objectives.SoftUpdate`\n# classes. They're built with the loss module as argument, and the update is\n# achieved via a call to `updater.step()` at the appropriate location in the\n# training loop.\n\nfrom torchrl.objectives.utils import SoftUpdate\n\ntarget_net_updater = SoftUpdate(loss_module, eps=1 - tau)\n\n###############################################################################\n# Optimizer\n# ~~~~~~~~~\n#\n# Finally, we will use the Adam optimizer for the policy and value network:\n\nfrom torch import optim\n\noptimizer_actor = optim.Adam(\n loss_module.actor_network_params.values(True, True), lr=1e-4, weight_decay=0.0\n)\noptimizer_value = optim.Adam(\n loss_module.value_network_params.values(True, True), lr=1e-3, weight_decay=1e-2\n)\ntotal_collection_steps = total_frames // frames_per_batch\n\n###############################################################################\n# Time to train the policy\n# ------------------------\n#\n# The training loop is pretty straightforward now that we have built all the\n# modules we need.\n#\n\nrewards = []\nrewards_eval = []\n\n# Main loop\n\ncollected_frames = 0\npbar = tqdm.tqdm(total=total_frames)\nr0 = None\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"torch",
"torchrl",
"tqdm"
],
"unresolved_names": [
"DDPGLoss",
"actor",
"ceil_div",
"device",
"frames_per_batch",
"make_replay_buffer",
"qnet",
"total_frames",
"traj_len"
],
"compatibility_flags": [
"requires_prior_state_or_project_modules",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 994,
"line_end": 1100,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "pytorch_tutorials-0214dfbbcc5efecd64c27d9c",
"source_id": "pytorch_tutorials",
"source_repo": "pytorch/tutorials",
"source_revision": "c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6",
"source_path": "advanced_source/coding_ddpg.py",
"source_url": "https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py",
"source_group": "advanced_source/coding_ddpg.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "top_level_statements",
"code": "import torch\n\nfor i, tensordict in enumerate(collector):\n\n # update weights of the inference policy\n collector.update_policy_weights_()\n\n if r0 is None:\n r0 = tensordict[\"next\", \"reward\"].mean().item()\n pbar.update(tensordict.numel())\n\n # extend the replay buffer with the new data\n current_frames = tensordict.numel()\n collected_frames += current_frames\n replay_buffer.extend(tensordict.cpu())\n\n # optimization steps\n if collected_frames >= init_random_frames:\n for _ in range(update_to_data):\n # sample from replay buffer\n sampled_tensordict = replay_buffer.sample().to(device)\n\n # Compute loss\n loss_dict = loss_module(sampled_tensordict)\n\n # optimize\n loss_dict[\"loss_actor\"].backward()\n gn1 = torch.nn.utils.clip_grad_norm_(\n loss_module.actor_network_params.values(True, True), 10.0\n )\n optimizer_actor.step()\n optimizer_actor.zero_grad()\n\n loss_dict[\"loss_value\"].backward()\n gn2 = torch.nn.utils.clip_grad_norm_(\n loss_module.value_network_params.values(True, True), 10.0\n )\n optimizer_value.step()\n optimizer_value.zero_grad()\n\n gn = (gn1**2 + gn2**2) ** 0.5\n\n # update priority\n if prb:\n replay_buffer.update_tensordict_priority(sampled_tensordict)\n # update target network\n target_net_updater.step()\n\n rewards.append(\n (\n i,\n tensordict[\"next\", \"reward\"].mean().item(),\n )\n )\n td_record = recorder(None)\n if td_record is not None:\n rewards_eval.append((i, td_record[\"r_evaluation\"].item()))\n if len(rewards_eval) and collected_frames >= init_random_frames:\n target_value = loss_dict[\"target_value\"].item()\n loss_value = loss_dict[\"loss_value\"].item()\n loss_actor = loss_dict[\"loss_actor\"].item()\n rn = sampled_tensordict[\"next\", \"reward\"].mean().item()\n rs = sampled_tensordict[\"next\", \"reward\"].std().item()\n pbar.set_description(\n f\"reward: {rewards[-1][1]: 4.2f} (r0 = {r0: 4.2f}), \"\n f\"reward eval: reward: {rewards_eval[-1][1]: 4.2f}, \"\n f\"reward normalized={rn :4.2f}/{rs :4.2f}, \"\n f\"grad norm={gn: 4.2f}, \"\n f\"loss_value={loss_value: 4.2f}, \"\n f\"loss_actor={loss_actor: 4.2f}, \"\n f\"target value: {target_value: 4.2f}\"\n )\n\n # update the exploration strategy\n actor_model_explore[1].step(current_frames)",
"code_sha256": "01adeef74fa1b2b447a247e00c6a5eaba02c5d8b22e602a2fea838869ed0f5fb",
"ast_sha256": "e1c668e3c1f56daebe440f65a7ccd7d64582766f8ae888c23c8d8349f3c02dc5",
"template_ast_sha256": "e1c668e3c1f56daebe440f65a7ccd7d64582766f8ae888c23c8d8349f3c02dc5",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "# -*- coding: utf-8 -*-\n\"\"\"\nTorchRL objectives: Coding a DDPG loss\n======================================\n**Author**: `Vincent Moens <https://github.com/vmoens>`_\n\n\"\"\"\n\n##############################################################################\n# Overview\n# --------\n#\n# TorchRL separates the training of RL algorithms in various pieces that will be\n# assembled in your training script: the environment, the data collection and\n# storage, the model and finally the loss function.\n#\n# TorchRL losses (or \"objectives\") are stateful objects that contain the\n# trainable parameters (policy and value models).\n# This tutorial will guide you through the steps to code a loss from the ground up\n# using TorchRL.\n#\n# To this aim, we will be focusing on DDPG, which is a relatively straightforward\n# algorithm to code.\n# `Deep Deterministic Policy Gradient <https://arxiv.org/abs/1509.02971>`_ (DDPG)\n# is a simple continuous control algorithm. It consists in learning a\n# parametric value function for an action-observation pair, and\n# then learning a policy that outputs actions that maximize this value\n# function given a certain observation.\n#\n# What you will learn:\n#\n# - how to write a loss module and customize its value estimator;\n# - how to build an environment in TorchRL, including transforms\n# (for example, data normalization) and parallel execution;\n# - how to design a policy and value network;\n# - how to collect data from your environment efficiently and store them\n# in a replay buffer;\n# - how to store trajectories (and not transitions) in your replay buffer);\n# - how to evaluate your model.\n#\n# Prerequisites\n# ~~~~~~~~~~~~~\n#\n# This tutorial assumes that you have completed the\n# `PPO tutorial <reinforcement_ppo.html>`_ which gives\n# an overview of the TorchRL components and dependencies, such as\n# :class:`tensordict.TensorDict` and :class:`tensordict.nn.TensorDictModules`,\n# although it should be\n# sufficiently transparent to be understood without a deep understanding of\n# these classes.\n#\n# .. note::\n# We do not aim at giving a SOTA implementation of the algorithm, but rather\n# to provide a high-level illustration of TorchRL's loss implementations\n# and the library features that are to be used in the context of\n# this algorithm.\n#\n# Imports and setup\n# -----------------\n#\n# .. code-block:: bash\n#\n# %%bash\n# pip3 install torchrl mujoco glfw\n\n# sphinx_gallery_start_ignore",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# top_level_statements\nSource: https://github.com/pytorch/tutorials/blob/c8ccbbf7fcb8cb71adda1b957bd6bab50e29c2e6/advanced_source/coding_ddpg.py#L1101-L1173\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: requires_prior_state_or_project_modules, main_snapshot_not_runtime_verified\n\n```python\nimport torch\n\nfor i, tensordict in enumerate(collector):\n\n # update weights of the inference policy\n collector.update_policy_weights_()\n\n if r0 is None:\n r0 = tensordict[\"next\", \"reward\"].mean().item()\n pbar.update(tensordict.numel())\n\n # extend the replay buffer with the new data\n current_frames = tensordict.numel()\n collected_frames += current_frames\n replay_buffer.extend(tensordict.cpu())\n\n # optimization steps\n if collected_frames >= init_random_frames:\n for _ in range(update_to_data):\n # sample from replay buffer\n sampled_tensordict = replay_buffer.sample().to(device)\n\n # Compute loss\n loss_dict = loss_module(sampled_tensordict)\n\n # optimize\n loss_dict[\"loss_actor\"].backward()\n gn1 = torch.nn.utils.clip_grad_norm_(\n loss_module.actor_network_params.values(True, True), 10.0\n )\n optimizer_actor.step()\n optimizer_actor.zero_grad()\n\n loss_dict[\"loss_value\"].backward()\n gn2 = torch.nn.utils.clip_grad_norm_(\n loss_module.value_network_params.values(True, True), 10.0\n )\n optimizer_value.step()\n optimizer_value.zero_grad()\n\n gn = (gn1**2 + gn2**2) ** 0.5\n\n # update priority\n if prb:\n replay_buffer.update_tensordict_priority(sampled_tensordict)\n # update target network\n target_net_updater.step()\n\n rewards.append(\n (\n i,\n tensordict[\"next\", \"reward\"].mean().item(),\n )\n )\n td_record = recorder(None)\n if td_record is not None:\n rewards_eval.append((i, td_record[\"r_evaluation\"].item()))\n if len(rewards_eval) and collected_frames >= init_random_frames:\n target_value = loss_dict[\"target_value\"].item()\n loss_value = loss_dict[\"loss_value\"].item()\n loss_actor = loss_dict[\"loss_actor\"].item()\n rn = sampled_tensordict[\"next\", \"reward\"].mean().item()\n rs = sampled_tensordict[\"next\", \"reward\"].std().item()\n pbar.set_description(\n f\"reward: {rewards[-1][1]: 4.2f} (r0 = {r0: 4.2f}), \"\n f\"reward eval: reward: {rewards_eval[-1][1]: 4.2f}, \"\n f\"reward normalized={rn :4.2f}/{rs :4.2f}, \"\n f\"grad norm={gn: 4.2f}, \"\n f\"loss_value={loss_value: 4.2f}, \"\n f\"loss_actor={loss_actor: 4.2f}, \"\n f\"target value: {target_value: 4.2f}\"\n )\n\n # update the exploration strategy\n actor_model_explore[1].step(current_frames)\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch",
"training_loop"
],
"packages": [
"torch"
],
"unresolved_names": [
"actor_model_explore",
"collector",
"device",
"init_random_frames",
"loss_module",
"optimizer_actor",
"optimizer_value",
"pbar",
"prb",
"recorder",
"replay_buffer",
"rewards",
"rewards_eval",
"target_net_updater",
"update_to_data"
],
"compatibility_flags": [
"requires_prior_state_or_project_modules",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 1101,
"line_end": 1173,
"external_data_required": false,
"benchmark_content": false
}
],
"torchvision_training_references": [
{
"record_id": "torchvision_training_references-799642eb1583ef8581894372",
"source_id": "torchvision_training_references",
"source_repo": "pytorch/vision",
"source_revision": "a034671605659e24ff1de1142079bf318ac3b123",
"source_path": "references/classification/utils.py",
"source_url": "https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py",
"source_group": "references/classification/utils.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "SmoothedValue",
"code": "from collections import defaultdict, deque, OrderedDict\nimport torch\n\nclass SmoothedValue:\n \"\"\"Track a series of values and provide access to smoothed values over a\n window or the global series average.\n \"\"\"\n\n def __init__(self, window_size=20, fmt=None):\n if fmt is None:\n fmt = \"{median:.4f} ({global_avg:.4f})\"\n self.deque = deque(maxlen=window_size)\n self.total = 0.0\n self.count = 0\n self.fmt = fmt\n\n def update(self, value, n=1):\n self.deque.append(value)\n self.count += n\n self.total += value * n\n\n def synchronize_between_processes(self):\n \"\"\"\n Warning: does not synchronize the deque!\n \"\"\"\n t = reduce_across_processes([self.count, self.total])\n t = t.tolist()\n self.count = int(t[0])\n self.total = t[1]\n\n @property\n def median(self):\n d = torch.tensor(list(self.deque))\n return d.median().item()\n\n @property\n def avg(self):\n d = torch.tensor(list(self.deque), dtype=torch.float32)\n return d.mean().item()\n\n @property\n def global_avg(self):\n return self.total / self.count\n\n @property\n def max(self):\n return max(self.deque)\n\n @property\n def value(self):\n return self.deque[-1]\n\n def __str__(self):\n return self.fmt.format(\n median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value\n )",
"code_sha256": "317bfad188139178f478b87fe45f0d54df0b31d271d1a6b35b5d02af22c0852a",
"ast_sha256": "fde6b8025cdbc473ae2172322d1af7eb7bf5e4b743baa8849da5883016b0c032",
"template_ast_sha256": "fde6b8025cdbc473ae2172322d1af7eb7bf5e4b743baa8849da5883016b0c032",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# SmoothedValue\nSource: https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py#L14-L66\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: requires_prior_state_or_project_modules, main_snapshot_not_runtime_verified\n\n```python\nfrom collections import defaultdict, deque, OrderedDict\nimport torch\n\nclass SmoothedValue:\n \"\"\"Track a series of values and provide access to smoothed values over a\n window or the global series average.\n \"\"\"\n\n def __init__(self, window_size=20, fmt=None):\n if fmt is None:\n fmt = \"{median:.4f} ({global_avg:.4f})\"\n self.deque = deque(maxlen=window_size)\n self.total = 0.0\n self.count = 0\n self.fmt = fmt\n\n def update(self, value, n=1):\n self.deque.append(value)\n self.count += n\n self.total += value * n\n\n def synchronize_between_processes(self):\n \"\"\"\n Warning: does not synchronize the deque!\n \"\"\"\n t = reduce_across_processes([self.count, self.total])\n t = t.tolist()\n self.count = int(t[0])\n self.total = t[1]\n\n @property\n def median(self):\n d = torch.tensor(list(self.deque))\n return d.median().item()\n\n @property\n def avg(self):\n d = torch.tensor(list(self.deque), dtype=torch.float32)\n return d.mean().item()\n\n @property\n def global_avg(self):\n return self.total / self.count\n\n @property\n def max(self):\n return max(self.deque)\n\n @property\n def value(self):\n return self.deque[-1]\n\n def __str__(self):\n return self.fmt.format(\n median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value\n )\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"collections",
"torch"
],
"unresolved_names": [
"reduce_across_processes"
],
"compatibility_flags": [
"requires_prior_state_or_project_modules",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 14,
"line_end": 66,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "torchvision_training_references-599e37610f6ac906005336e1",
"source_id": "torchvision_training_references",
"source_repo": "pytorch/vision",
"source_revision": "a034671605659e24ff1de1142079bf318ac3b123",
"source_path": "references/classification/utils.py",
"source_url": "https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py",
"source_group": "references/classification/utils.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "MetricLogger",
"code": "import datetime\nimport time\nfrom collections import defaultdict, deque, OrderedDict\nimport torch\n\nclass MetricLogger:\n def __init__(self, delimiter=\"\\t\"):\n self.meters = defaultdict(SmoothedValue)\n self.delimiter = delimiter\n\n def update(self, **kwargs):\n for k, v in kwargs.items():\n if isinstance(v, torch.Tensor):\n v = v.item()\n assert isinstance(v, (float, int))\n self.meters[k].update(v)\n\n def __getattr__(self, attr):\n if attr in self.meters:\n return self.meters[attr]\n if attr in self.__dict__:\n return self.__dict__[attr]\n raise AttributeError(f\"'{type(self).__name__}' object has no attribute '{attr}'\")\n\n def __str__(self):\n loss_str = []\n for name, meter in self.meters.items():\n loss_str.append(f\"{name}: {str(meter)}\")\n return self.delimiter.join(loss_str)\n\n def synchronize_between_processes(self):\n for meter in self.meters.values():\n meter.synchronize_between_processes()\n\n def add_meter(self, name, meter):\n self.meters[name] = meter\n\n def log_every(self, iterable, print_freq, header=None):\n i = 0\n if not header:\n header = \"\"\n start_time = time.time()\n end = time.time()\n iter_time = SmoothedValue(fmt=\"{avg:.4f}\")\n data_time = SmoothedValue(fmt=\"{avg:.4f}\")\n space_fmt = \":\" + str(len(str(len(iterable)))) + \"d\"\n if torch.cuda.is_available():\n log_msg = self.delimiter.join(\n [\n header,\n \"[{0\" + space_fmt + \"}/{1}]\",\n \"eta: {eta}\",\n \"{meters}\",\n \"time: {time}\",\n \"data: {data}\",\n \"max mem: {memory:.0f}\",\n ]\n )\n else:\n log_msg = self.delimiter.join(\n [header, \"[{0\" + space_fmt + \"}/{1}]\", \"eta: {eta}\", \"{meters}\", \"time: {time}\", \"data: {data}\"]\n )\n MB = 1024.0 * 1024.0\n for obj in iterable:\n data_time.update(time.time() - end)\n yield obj\n iter_time.update(time.time() - end)\n if i % print_freq == 0:\n eta_seconds = iter_time.global_avg * (len(iterable) - i)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n if torch.cuda.is_available():\n print(\n log_msg.format(\n i,\n len(iterable),\n eta=eta_string,\n meters=str(self),\n time=str(iter_time),\n data=str(data_time),\n memory=torch.cuda.max_memory_allocated() / MB,\n )\n )\n else:\n print(\n log_msg.format(\n i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)\n )\n )\n i += 1\n end = time.time()\n total_time = time.time() - start_time\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n print(f\"{header} Total time: {total_time_str}\")",
"code_sha256": "537ed251de72998d9c4616eedf19770948a1994f483869c6f12017c2aaf10d05",
"ast_sha256": "0c9f2b4b0e3b73128be8ef94597040166c6d1066956f312ee77d6dde217358fc",
"template_ast_sha256": "0c9f2b4b0e3b73128be8ef94597040166c6d1066956f312ee77d6dde217358fc",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# MetricLogger\nSource: https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py#L69-L156\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: requires_prior_state_or_project_modules, main_snapshot_not_runtime_verified\n\n```python\nimport datetime\nimport time\nfrom collections import defaultdict, deque, OrderedDict\nimport torch\n\nclass MetricLogger:\n def __init__(self, delimiter=\"\\t\"):\n self.meters = defaultdict(SmoothedValue)\n self.delimiter = delimiter\n\n def update(self, **kwargs):\n for k, v in kwargs.items():\n if isinstance(v, torch.Tensor):\n v = v.item()\n assert isinstance(v, (float, int))\n self.meters[k].update(v)\n\n def __getattr__(self, attr):\n if attr in self.meters:\n return self.meters[attr]\n if attr in self.__dict__:\n return self.__dict__[attr]\n raise AttributeError(f\"'{type(self).__name__}' object has no attribute '{attr}'\")\n\n def __str__(self):\n loss_str = []\n for name, meter in self.meters.items():\n loss_str.append(f\"{name}: {str(meter)}\")\n return self.delimiter.join(loss_str)\n\n def synchronize_between_processes(self):\n for meter in self.meters.values():\n meter.synchronize_between_processes()\n\n def add_meter(self, name, meter):\n self.meters[name] = meter\n\n def log_every(self, iterable, print_freq, header=None):\n i = 0\n if not header:\n header = \"\"\n start_time = time.time()\n end = time.time()\n iter_time = SmoothedValue(fmt=\"{avg:.4f}\")\n data_time = SmoothedValue(fmt=\"{avg:.4f}\")\n space_fmt = \":\" + str(len(str(len(iterable)))) + \"d\"\n if torch.cuda.is_available():\n log_msg = self.delimiter.join(\n [\n header,\n \"[{0\" + space_fmt + \"}/{1}]\",\n \"eta: {eta}\",\n \"{meters}\",\n \"time: {time}\",\n \"data: {data}\",\n \"max mem: {memory:.0f}\",\n ]\n )\n else:\n log_msg = self.delimiter.join(\n [header, \"[{0\" + space_fmt + \"}/{1}]\", \"eta: {eta}\", \"{meters}\", \"time: {time}\", \"data: {data}\"]\n )\n MB = 1024.0 * 1024.0\n for obj in iterable:\n data_time.update(time.time() - end)\n yield obj\n iter_time.update(time.time() - end)\n if i % print_freq == 0:\n eta_seconds = iter_time.global_avg * (len(iterable) - i)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n if torch.cuda.is_available():\n print(\n log_msg.format(\n i,\n len(iterable),\n eta=eta_string,\n meters=str(self),\n time=str(iter_time),\n data=str(data_time),\n memory=torch.cuda.max_memory_allocated() / MB,\n )\n )\n else:\n print(\n log_msg.format(\n i, len(iterable), eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time)\n )\n )\n i += 1\n end = time.time()\n total_time = time.time() - start_time\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n print(f\"{header} Total time: {total_time_str}\")\n```\n",
"metadata_json": "{}",
"topics": [
"data_analysis",
"pytorch"
],
"packages": [
"collections",
"datetime",
"time",
"torch"
],
"unresolved_names": [
"SmoothedValue"
],
"compatibility_flags": [
"requires_prior_state_or_project_modules",
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 69,
"line_end": 156,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "torchvision_training_references-3fb46125cc1d398228a2f13b",
"source_id": "torchvision_training_references",
"source_repo": "pytorch/vision",
"source_revision": "a034671605659e24ff1de1142079bf318ac3b123",
"source_path": "references/classification/utils.py",
"source_url": "https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py",
"source_group": "references/classification/utils.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "accuracy",
"code": "import torch\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.inference_mode():\n maxk = max(topk)\n batch_size = target.size(0)\n if target.ndim == 2:\n target = target.max(dim=1)[1]\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target[None])\n\n res = []\n for k in topk:\n correct_k = correct[:k].flatten().sum(dtype=torch.float32)\n res.append(correct_k * (100.0 / batch_size))\n return res",
"code_sha256": "5e2f553ca3892628627c4b74d4d942d5cdc76538f786e7deb3427dbdfbdca025",
"ast_sha256": "30f8589ed052863d20f8f73f9c7618f2c68f5dfdd4c511a8c3a2a2fda1ed8360",
"template_ast_sha256": "30f8589ed052863d20f8f73f9c7618f2c68f5dfdd4c511a8c3a2a2fda1ed8360",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# accuracy\nSource: https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py#L173-L189\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: main_snapshot_not_runtime_verified\n\n```python\nimport torch\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.inference_mode():\n maxk = max(topk)\n batch_size = target.size(0)\n if target.ndim == 2:\n target = target.max(dim=1)[1]\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target[None])\n\n res = []\n for k in topk:\n correct_k = correct[:k].flatten().sum(dtype=torch.float32)\n res.append(correct_k * (100.0 / batch_size))\n return res\n```\n",
"metadata_json": "{}",
"topics": [
"evaluation",
"pytorch",
"tensor_shapes"
],
"packages": [
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 173,
"line_end": 189,
"external_data_required": false,
"benchmark_content": false
},
{
"record_id": "torchvision_training_references-44fa5fbf1e2c30d488277dbe",
"source_id": "torchvision_training_references",
"source_repo": "pytorch/vision",
"source_revision": "a034671605659e24ff1de1142079bf318ac3b123",
"source_path": "references/classification/utils.py",
"source_url": "https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py",
"source_group": "references/classification/utils.py",
"source_record_id": "",
"upstream_track": "main",
"authority": "official",
"record_type": "python_code",
"intended_use": "rag",
"split": "test",
"symbol": "is_dist_avail_and_initialized",
"code": "import torch.distributed as dist\n\ndef is_dist_avail_and_initialized():\n if not dist.is_available():\n return False\n if not dist.is_initialized():\n return False\n return True",
"code_sha256": "d6550b86a7a6c0dee709c0ca0398abf4765e57d5170f0c3ac5f229183a710195",
"ast_sha256": "a4f6c86eaca9222f46e99dd01cdfc7e219ab4eed2b2f7186d719f010fda61f06",
"template_ast_sha256": "a4f6c86eaca9222f46e99dd01cdfc7e219ab4eed2b2f7186d719f010fda61f06",
"license_id": "BSD-3-Clause",
"license_evidence": "upstream_repository_license",
"attribution_notice": "",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# is_dist_avail_and_initialized\nSource: https://github.com/pytorch/vision/blob/a034671605659e24ff1de1142079bf318ac3b123/references/classification/utils.py#L216-L221\nLicense: BSD-3-Clause. Syntax checked only; may require original state/files.\nFlags: main_snapshot_not_runtime_verified\n\n```python\nimport torch.distributed as dist\n\ndef is_dist_avail_and_initialized():\n if not dist.is_available():\n return False\n if not dist.is_initialized():\n return False\n return True\n```\n",
"metadata_json": "{}",
"topics": [
"pytorch"
],
"packages": [
"torch"
],
"unresolved_names": [],
"compatibility_flags": [
"main_snapshot_not_runtime_verified"
],
"source_row": -1,
"line_start": 216,
"line_end": 221,
"external_data_required": false,
"benchmark_content": false
}
],
"aifaultbench": [
{
"record_id": "aifaultbench-case-8636c5e9db7252f64e99e48f",
"source_id": "aifaultbench",
"source_repo": "mehilshah/AIFaultBench",
"source_revision": "62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff",
"source_path": "bugs/028/repro.py",
"source_url": "https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/028/repro.py",
"source_group": "028",
"source_record_id": "028",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_task",
"intended_use": "evaluation",
"split": "test",
"symbol": "028",
"code": "",
"code_sha256": "",
"ast_sha256": "",
"template_ast_sha256": "",
"license_id": "CC-BY-4.0",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "metadata_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nCase metadata: {\"bug_id\": \"028\", \"library\": \"examples\", \"repository\": \"pytorch/examples\", \"domain\": \"DL\", \"issue_url\": \"https://github.com/pytorch/examples/issues/1175\", \"commit\": \"6fc19c76b9f5550d8d3cb38284845ac7ed14223c\", \"reproducible\": true, \"blocking_reason\": \"\"}\nUpstream reproduction evidence: ['python3 repro.py prints num_classes_default=16 from codebase/vision_transformer/main.py', 'stderr reports: BUG: expected default num_classes=10 for CIFAR10, but code sets 16.', 'run_repro.sh exits with code 1']\n\nSource: https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/028/repro.py\nLicense: CC-BY-4.0",
"metadata_json": "{\"benchmark_facts\": {\"blocking_reason\": \"\", \"bug_id\": \"028\", \"commit\": \"6fc19c76b9f5550d8d3cb38284845ac7ed14223c\", \"domain\": \"DL\", \"issue_url\": \"https://github.com/pytorch/examples/issues/1175\", \"library\": \"examples\", \"repository\": \"pytorch/examples\", \"reproducible\": true}, \"code_status\": \"intentionally_failing_or_case_specific\"}",
"topics": [
"benchmark",
"debugging"
],
"packages": [],
"unresolved_names": [],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 0,
"line_end": 0,
"external_data_required": true,
"benchmark_content": true
},
{
"record_id": "aifaultbench-case-72fc555df85b56a0224198f6",
"source_id": "aifaultbench",
"source_repo": "mehilshah/AIFaultBench",
"source_revision": "62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff",
"source_path": "bugs/029/repro.py",
"source_url": "https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/029/repro.py",
"source_group": "029",
"source_record_id": "029",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_task",
"intended_use": "evaluation",
"split": "test",
"symbol": "029",
"code": "",
"code_sha256": "",
"ast_sha256": "",
"template_ast_sha256": "",
"license_id": "CC-BY-4.0",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "metadata_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nCase metadata: {\"bug_id\": \"029\", \"library\": \"examples\", \"repository\": \"pytorch/examples\", \"domain\": \"DL\", \"issue_url\": \"https://github.com/pytorch/examples/issues/1134\", \"commit\": \"54f4572509891883a947411fd7239237dd2a39c3\", \"reproducible\": true, \"blocking_reason\": \"\"}\nUpstream reproduction evidence: [\"Running `bash run_repro.sh` printed `=> creating model 'resnet18'` and then failed with `AttributeError: module 'torch.backends' has no attribute 'mps'`.\", 'The traceback points to `codebase/imagenet/main.py:171` at `elif torch.backends.mps.is_available():`.']\n\nSource: https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/029/repro.py\nLicense: CC-BY-4.0",
"metadata_json": "{\"benchmark_facts\": {\"blocking_reason\": \"\", \"bug_id\": \"029\", \"commit\": \"54f4572509891883a947411fd7239237dd2a39c3\", \"domain\": \"DL\", \"issue_url\": \"https://github.com/pytorch/examples/issues/1134\", \"library\": \"examples\", \"repository\": \"pytorch/examples\", \"reproducible\": true}, \"code_status\": \"intentionally_failing_or_case_specific\"}",
"topics": [
"benchmark",
"debugging"
],
"packages": [],
"unresolved_names": [],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 0,
"line_end": 0,
"external_data_required": true,
"benchmark_content": true
},
{
"record_id": "aifaultbench-case-1fbd577b4cc2b4a1b17194c2",
"source_id": "aifaultbench",
"source_repo": "mehilshah/AIFaultBench",
"source_revision": "62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff",
"source_path": "bugs/108/repro.py",
"source_url": "https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/108/repro.py",
"source_group": "108",
"source_record_id": "108",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_task",
"intended_use": "evaluation",
"split": "test",
"symbol": "108",
"code": "",
"code_sha256": "",
"ast_sha256": "",
"template_ast_sha256": "",
"license_id": "CC-BY-4.0",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "metadata_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nCase metadata: {\"bug_id\": \"108\", \"library\": \"transformers\", \"repository\": \"huggingface/transformers\", \"domain\": \"LLM\", \"issue_url\": \"https://github.com/huggingface/transformers/issues/42502\", \"commit\": \"cac0a28c83cf87b7a05495de3177099c635ba852\", \"reproducible\": true, \"blocking_reason\": \"\"}\nUpstream reproduction evidence: ['Running DataCollatorWithFlattening on features whose labels are torch.Tensor objects raises TypeError(\\'can only concatenate list (not \"Tensor\") to list\\').', 'The same collator succeeds when labels are provided as Python lists, producing flattened input_ids, labels, and position_ids.']\n\nSource: https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/108/repro.py\nLicense: CC-BY-4.0",
"metadata_json": "{\"benchmark_facts\": {\"blocking_reason\": \"\", \"bug_id\": \"108\", \"commit\": \"cac0a28c83cf87b7a05495de3177099c635ba852\", \"domain\": \"LLM\", \"issue_url\": \"https://github.com/huggingface/transformers/issues/42502\", \"library\": \"transformers\", \"repository\": \"huggingface/transformers\", \"reproducible\": true}, \"code_status\": \"intentionally_failing_or_case_specific\"}",
"topics": [
"benchmark",
"debugging"
],
"packages": [],
"unresolved_names": [],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 0,
"line_end": 0,
"external_data_required": true,
"benchmark_content": true
},
{
"record_id": "aifaultbench-case-f25385a71c237761461b20d2",
"source_id": "aifaultbench",
"source_repo": "mehilshah/AIFaultBench",
"source_revision": "62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff",
"source_path": "bugs/108/repro.py",
"source_url": "https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/108/repro.py",
"source_group": "108",
"source_record_id": "108",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_reproducer",
"intended_use": "evaluation",
"split": "test",
"symbol": "108-main",
"code": "from __future__ import annotations\nimport json\nimport torch\nimport transformers\nfrom transformers import DataCollatorWithFlattening\n\ndef main() -> int:\n print(f\"transformers_version={transformers.__version__}\")\n print(f\"torch_version={torch.__version__}\")\n\n collator = DataCollatorWithFlattening(return_tensors=\"pt\")\n\n tensor_features = [\n {\"input_ids\": torch.tensor([1, 2, 3, 4]), \"labels\": torch.tensor([10, 11, 12, 13])},\n {\"input_ids\": torch.tensor([5, 6, 7]), \"labels\": torch.tensor([14, 15, 16])},\n ]\n\n print(\"tensor_labels_case=\")\n try:\n batch = collator(tensor_features)\n except Exception as exc: # noqa: BLE001 - we want the exact runtime failure in the log\n print(f\"tensor_labels_status=error\")\n print(f\"tensor_labels_error={type(exc).__name__}: {exc}\")\n else:\n print(\"tensor_labels_status=unexpected_success\")\n print(json.dumps(batch_to_jsonable(batch), indent=2, sort_keys=True))\n\n list_features = [\n {\"input_ids\": torch.tensor([1, 2, 3, 4]), \"labels\": [10, 11, 12, 13]},\n {\"input_ids\": torch.tensor([5, 6, 7]), \"labels\": [14, 15, 16]},\n ]\n\n print(\"list_labels_case=\")\n batch = collator(list_features)\n print(json.dumps(batch_to_jsonable(batch), indent=2, sort_keys=True))\n return 0",
"code_sha256": "da27ba58cc38ca278e16f3c33a3fee643ee06227a1c90a01074afe0d086ef057",
"ast_sha256": "9375a22cbbc68594b78da33f4813de4a9c62212783fe4bed422478649a6a9c15",
"template_ast_sha256": "9375a22cbbc68594b78da33f4813de4a9c62212783fe4bed422478649a6a9c15",
"license_id": "CC-BY-4.0",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nCase metadata: {\"bug_id\": \"108\", \"library\": \"transformers\", \"repository\": \"huggingface/transformers\", \"domain\": \"LLM\", \"issue_url\": \"https://github.com/huggingface/transformers/issues/42502\", \"commit\": \"cac0a28c83cf87b7a05495de3177099c635ba852\", \"reproducible\": true, \"blocking_reason\": \"\"}\nUpstream reproduction evidence: ['Running DataCollatorWithFlattening on features whose labels are torch.Tensor objects raises TypeError(\\'can only concatenate list (not \"Tensor\") to list\\').', 'The same collator succeeds when labels are provided as Python lists, producing flattened input_ids, labels, and position_ids.']\n\nSource: https://huggingface.co/datasets/mehilshah/AIFaultBench/blob/62e11d6dfe4b1637f38a45d8fbc1c2b9c3c971ff/bugs/108/repro.py\nLicense: CC-BY-4.0\n\n```python\nfrom __future__ import annotations\nimport json\nimport torch\nimport transformers\nfrom transformers import DataCollatorWithFlattening\n\ndef main() -> int:\n print(f\"transformers_version={transformers.__version__}\")\n print(f\"torch_version={torch.__version__}\")\n\n collator = DataCollatorWithFlattening(return_tensors=\"pt\")\n\n tensor_features = [\n {\"input_ids\": torch.tensor([1, 2, 3, 4]), \"labels\": torch.tensor([10, 11, 12, 13])},\n {\"input_ids\": torch.tensor([5, 6, 7]), \"labels\": torch.tensor([14, 15, 16])},\n ]\n\n print(\"tensor_labels_case=\")\n try:\n batch = collator(tensor_features)\n except Exception as exc: # noqa: BLE001 - we want the exact runtime failure in the log\n print(f\"tensor_labels_status=error\")\n print(f\"tensor_labels_error={type(exc).__name__}: {exc}\")\n else:\n print(\"tensor_labels_status=unexpected_success\")\n print(json.dumps(batch_to_jsonable(batch), indent=2, sort_keys=True))\n\n list_features = [\n {\"input_ids\": torch.tensor([1, 2, 3, 4]), \"labels\": [10, 11, 12, 13]},\n {\"input_ids\": torch.tensor([5, 6, 7]), \"labels\": [14, 15, 16]},\n ]\n\n print(\"list_labels_case=\")\n batch = collator(list_features)\n print(json.dumps(batch_to_jsonable(batch), indent=2, sort_keys=True))\n return 0\n```\n",
"metadata_json": "{\"benchmark_facts\": {\"blocking_reason\": \"\", \"bug_id\": \"108\", \"commit\": \"cac0a28c83cf87b7a05495de3177099c635ba852\", \"domain\": \"LLM\", \"issue_url\": \"https://github.com/huggingface/transformers/issues/42502\", \"library\": \"transformers\", \"repository\": \"huggingface/transformers\", \"reproducible\": true}, \"code_status\": \"intentionally_failing_or_case_specific\", \"metadata_license\": \"CC-BY-4.0\"}",
"topics": [
"benchmark",
"debugging",
"pytorch"
],
"packages": [
"__future__",
"json",
"torch",
"transformers"
],
"unresolved_names": [
"batch_to_jsonable"
],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 1,
"line_end": 36,
"external_data_required": true,
"benchmark_content": true
}
],
"ml_dev_bench": [
{
"record_id": "ml_dev_bench-case-300a464b4705c1ac86849370",
"source_id": "ml_dev_bench",
"source_repo": "ml-dev-bench/ml-dev-bench",
"source_revision": "c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4",
"source_path": "ml_dev_bench/cases/dataset/dataset_not_available_download/task/task.txt",
"source_url": "https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/dataset/dataset_not_available_download/task/task.txt",
"source_group": "ml_dev_bench/cases/dataset/dataset_not_available_download/task",
"source_record_id": "",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_task",
"intended_use": "evaluation",
"split": "test",
"symbol": "ml_dev_bench/cases/dataset/dataset_not_available_download/task",
"code": "",
"code_sha256": "",
"ast_sha256": "",
"template_ast_sha256": "",
"license_id": "MIT",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "metadata_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nYour task is to download and prepare a dataset for training a machine learning model.\n\n1. Download the dataset from: https://github.com/ml-dev-bench/cdh-dataset-download. In case of any issues, create a dataset_not_available.txt file in the workspace directory with the issue description.\n\n2. The dataset should be downloaded and extracted to a directory structure\n\n3. If successful, create a dataset_info.json file in the workspace directory with the dataset path\n\n\nSource: https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/dataset/dataset_not_available_download/task/task.txt\nLicense: MIT",
"metadata_json": "{\"task_instructions_are_historical\": true}",
"topics": [
"benchmark",
"debugging"
],
"packages": [],
"unresolved_names": [],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 0,
"line_end": 0,
"external_data_required": true,
"benchmark_content": true
},
{
"record_id": "ml_dev_bench-case-18add84c0530c14401c81d8d",
"source_id": "ml_dev_bench",
"source_repo": "ml-dev-bench/ml-dev-bench",
"source_revision": "c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4",
"source_path": "ml_dev_bench/cases/dataset/dataset_preprocess/task/task.txt",
"source_url": "https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/dataset/dataset_preprocess/task/task.txt",
"source_group": "ml_dev_bench/cases/dataset/dataset_preprocess/task",
"source_record_id": "",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_task",
"intended_use": "evaluation",
"split": "test",
"symbol": "ml_dev_bench/cases/dataset/dataset_preprocess/task",
"code": "",
"code_sha256": "",
"ast_sha256": "",
"template_ast_sha256": "",
"license_id": "MIT",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "metadata_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nYour task is to load and preprocess the CIFAR10 dataset for training a machine learning model. Follow these steps:\n\n1. Use torchvision to load the CIFAR10 dataset\n2. Apply the following preprocessing steps to the first 10 images only:\n - Convert images to tensors\n - Normalize the images using mean=(0.5, 0.5, 0.5) and std=(0.5, 0.5, 0.5)\n - Apply transforms such as random rotation, horizontal flip and color jitter\n - Save preprocessed images as .npy files in a 'preprocessed' directory\n - Save three augmented versions in an 'augmented' directory with format '{base_name}_v{N}.npy'\n\n3. Create a preprocessing_info.json file in the workspace directory with the following information for the first 10 images only:\n {\n \"dataset\": \"CIFAR10\",\n \"preprocessing\": {\n \"normalization\": {\n \"mean\": [0.5, 0.5, 0.5],\n \"std\": [0.5, 0.5, 0.5]\n },\n \"expected_shape\": [3, 32, 32],\n \"value_range\": [-1, 1]\n },\n \"preprocessed_data_path\": \"path/to/preprocessed/directory\",\n \"augmented_data_path\": \"path/to/augmented/directory\"\n }\n\nThe preprocessing_info.json file will be used to validate your implementation. Make sure to save all data as numpy arrays (.npy files)\n\n\nSource: https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/dataset/dataset_preprocess/task/task.txt\nLicense: MIT",
"metadata_json": "{\"task_instructions_are_historical\": true}",
"topics": [
"benchmark",
"debugging"
],
"packages": [],
"unresolved_names": [],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 0,
"line_end": 0,
"external_data_required": true,
"benchmark_content": true
},
{
"record_id": "ml_dev_bench-case-3ea3755fe61a2e936c11ee91",
"source_id": "ml_dev_bench",
"source_repo": "ml-dev-bench/ml-dev-bench",
"source_revision": "c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4",
"source_path": "ml_dev_bench/cases/dataset/noisy_dataset_download/task.txt",
"source_url": "https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/dataset/noisy_dataset_download/task.txt",
"source_group": "ml_dev_bench/cases/dataset/noisy_dataset_download",
"source_record_id": "",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_task",
"intended_use": "evaluation",
"split": "test",
"symbol": "ml_dev_bench/cases/dataset/noisy_dataset_download",
"code": "",
"code_sha256": "",
"ast_sha256": "",
"template_ast_sha256": "",
"license_id": "MIT",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "metadata_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\n- Download the noisy_imagenette dataset 160px version from the official source https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-160.tgz\n- Extract/uncompress the downloaded dataset\n- Save the path to the uncompressed dataset directory in a JSON file named 'dataset_info.json' with the key 'dataset_path'\n\n- The dataset comes with a CSV file which has 1%, 5%, 25%, and 50% noisy labels\n- We will only use the 50% noisy labels for this task\n- Extract and save the labels from that CSV file into 'all_noisy_labels_50.csv', with two columns (path, label) one for the image path and its corresponding noisy label;\n- Generate the class counts (number of images) for each class in the train and validation splits and save it in 'train_class_counts.csv' and 'validation_class_counts.csv'\n- The train_class_counts.csv file should have two columns ('class', 'count') one for the class and its corresponding count in the train split\n- Follow similar structure for the validation_class_counts.csv file\n\n\nSource: https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/dataset/noisy_dataset_download/task.txt\nLicense: MIT",
"metadata_json": "{\"task_instructions_are_historical\": true}",
"topics": [
"benchmark",
"debugging"
],
"packages": [],
"unresolved_names": [],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 0,
"line_end": 0,
"external_data_required": true,
"benchmark_content": true
},
{
"record_id": "ml_dev_bench-case-02402f1539bb91edf4b2e507",
"source_id": "ml_dev_bench",
"source_repo": "ml-dev-bench/ml-dev-bench",
"source_revision": "c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4",
"source_path": "ml_dev_bench/cases/debugging/bert_eval_debug/setup_workspace/train.py",
"source_url": "https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/debugging/bert_eval_debug/setup_workspace/train.py",
"source_group": "ml_dev_bench/cases/debugging/bert_eval_debug/setup_workspace",
"source_record_id": "",
"upstream_track": "frozen",
"authority": "benchmark",
"record_type": "benchmark_reproducer",
"intended_use": "evaluation",
"split": "test",
"symbol": "ml_dev_bench/cases/debugging/bert_eval_debug/setup_workspace-compute_metrics",
"code": "import numpy as np\nfrom sklearn.metrics import accuracy_score, f1_score\n\ndef compute_metrics(eval_pred):\n logits, labels = eval_pred\n predictions = np.argmax(logits, axis=-1)\n acc = accuracy_score(labels, predictions)\n f1 = f1_score(labels, predictions)\n logger.info(f'Evaluation metrics - Accuracy: {acc:.4f}, F1: {f1:.4f}')\n return {'accuracy': acc, 'f1': f1}",
"code_sha256": "5c6c83709a9b182506106691ba9a859352ecfe9ef4def4196967170cfda0210e",
"ast_sha256": "f167b5ddd3ed4e1c443c9b7ae124af2d53952bd26c72032b907d7682379de4dc",
"template_ast_sha256": "f167b5ddd3ed4e1c443c9b7ae124af2d53952bd26c72032b907d7682379de4dc",
"license_id": "MIT",
"license_evidence": "upstream_benchmark_packaging_license",
"attribution_notice": "See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.",
"validated_here": "syntax_only_not_executed",
"curation_version": "multi-source-v1",
"text": "# Benchmark study/evaluation evidence — not a working recipe\nOriginal ML-Dev-Bench debugging workspace fixture. It may intentionally contain a bug; not a reference solution.\n\nSource: https://github.com/ml-dev-bench/ml-dev-bench/blob/c2bd0c239f960368b11b2fd83d76f2ccfb69b7c4/ml_dev_bench/cases/debugging/bert_eval_debug/setup_workspace/train.py\nLicense: MIT\n\n```python\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, f1_score\n\ndef compute_metrics(eval_pred):\n logits, labels = eval_pred\n predictions = np.argmax(logits, axis=-1)\n acc = accuracy_score(labels, predictions)\n f1 = f1_score(labels, predictions)\n logger.info(f'Evaluation metrics - Accuracy: {acc:.4f}, F1: {f1:.4f}')\n return {'accuracy': acc, 'f1': f1}\n```\n",
"metadata_json": "{\"task_instructions_are_historical\": true}",
"topics": [
"benchmark",
"debugging",
"sklearn",
"validation"
],
"packages": [
"numpy",
"sklearn"
],
"unresolved_names": [
"logger"
],
"compatibility_flags": [
"intentionally_failing_or_task_specific",
"requires_original_benchmark_environment"
],
"source_row": -1,
"line_start": 1,
"line_end": 10,
"external_data_required": true,
"benchmark_content": true
}
]
}