Datasets:
content stringlengths 200 198k | repo stringlengths 4 186 | path stringclasses 1
value | license stringclasses 101
values | size int64 200 198k | sha stringlengths 40 40 | lang stringclasses 1
value | ext stringclasses 1
value |
|---|---|---|---|---|---|---|---|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension
import numpy
############# If showing struct declaration conflict... | setup.py | MIT | 3,271 | feba15dbeefed859c173eacaeb8d58b938acbc5f | Python | py | |
from __future__ import print_function, division
import collections
import copy
import ctypes
import importlib
import os
import queue
import random
import signal
import sys
import time
import warnings
from typing import Optional
import numpy as np
import torch
import torch.multiprocessing as mp
from setproctitle impor... | rl_multi_agent/main.py | MIT | 13,080 | d79370b13d1e654912139f03bf2d6d2bb9a5f87d | Python | py | |
import numpy as np
import pandas as pd
import torch
import pickle
import torch.nn.functional as F
def preprocess_csv():
'''
train_id_index: dict, {'patient ID': 0, ...}
train_feats: torch_tensor, L2 normalization
train_labels_dict: dict, {'preCST': torch.tensor(...), ...}
test_id_index: dict, {'pa... | src/utils/preprocess_csv.py | MIT | 4,514 | feba1f2f5f1579237879eca0ab53f8fad22fed90 | Python | py | |
import torch
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as dsets
import numpy as np
from torch.optim.optimizer import Optimizer, required
import torch.nn.functional as F
import time
hhh = {}
class SGD(Optimizer):
def __init__(self, params, lr=requi... | lr.py | Apache-2.0 | 4,433 | feba202272d2e3232f0967518fa4235dfdea76a1 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import prob
import superp
import plot3d
############################################
# This file will plot 2-D or 3-D barrier
############################################
#... | plot.py | BSD-3-Clause | 8,785 | 5e91326a796982523b4e4977c2a9b0a915888c2f | Python | py | |
#-------------------------------------------------------------------------------#
# Copyright (C) 2020-2021 ETH Zurich, Switzerland, University of Bologna, Italy.#
# All rights reserved. #
# ... | pulp-dronet-v2/testing.py | Apache-2.0 | 7,973 | 52fbcab201cd449fc9ce5a6a0bf7817ac18396d5 | Python | py | |
import matplotlib.pyplot as plt
import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmseg.datasets.pipelines import Compose
from mmseg.models import build_segmentor
def init_segmentor(config, checkpoint=None, device='cuda:0'):
"""Initialize a segmentor... | mmseg/apis/inference.py | Apache-2.0 | 3,978 | 7cebac986d9c79d3c3d7027f37aec3256d24112e | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""E2E-TTS training / decoding functions."""
import copy
import json
import logging
import math
import os
import time
import chainer
import kaldiio
import nu... | espnet/tts/pytorch_backend/tts.py | Apache-2.0 | 26,692 | e65f710bda7a923f4336ef8a49770d0b113354e8 | Python | py | |
import torch
from torch.autograd import Variable
import torchvision
from torchvision import transforms
from PIL import Image
import numpy as np
from const import PAD
class Data_loader(object):
def __init__(self, path, imgs, labels, max_len, batch_size, is_cuda, img_size=299, evaluation=False):
self._pa... | Image-Cap/data_loader.py | MIT | 2,542 | feba7da5565bf378f29b225f3c06aa6914057fe6 | Python | py | |
import math
import torch
from ._abstract_recurrent_cell import AbstractRecurrentCell
from ..abstract import ExtendedTorchModule
from ..functional import mnac, Regualizer, RegualizerNMUZ, sparsity_error
class ReRegualizedLinearMNACLayer(ExtendedTorchModule):
"""Implements the NAC (Neural Accumulator)
Argume... | stable_nalu/layer/re_regualized_linear_mnac.py | MIT | 3,399 | 345b121d43f0e2efb0e14e9f8a84020dd44aeec5 | Python | py | |
import torch
from .Module import Module
class Replicate(Module):
def __init__(self, nf, dim=0):
super(Replicate, self).__init__()
self.nfeatures = nf
self.dim = dim
assert self.dim >= 0
def updateOutput(self, input):
assert self.dim < input.dim()
size = list(... | torch/legacy/nn/Replicate.py | MIT | 906 | 10f4d80884b976410627409a3841499ace5911b3 | Python | py | |
"""
Project: stock_prediction
File: run_attention_rnn.py
Created by: louise
On: 08/02/18
At: 12:53 PM
"""
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch import optim
from torch.optim import lr_scheduler
from tensorboardX... | src/run_attention_rnn.py | MIT | 5,677 | 45d6eed2293984c1ae9de67e6a24bf0cc4ed6c1d | Python | py | |
# --------------------------------------------------------
# DaSiamRPN
# Licensed under The MIT License
# Written by Qiang Wang (wangqiang2015 at ia.ac.cn)
# --------------------------------------------------------
import torch.nn as nn
import torch.nn.functional as F
class SiamRPN(nn.Module):
def __init__(self, ... | code/net.py | MIT | 3,166 | ff8bb24b0ca30dc4bb99c5a1117e47c97ce61845 | Python | py | |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... | Pyrado/tests/algorithms/test_meta.py | DOC,Zlib,BSD-3-Clause | 38,166 | febad66a24aa66b86e1ff96549c6f770cad5f237 | Python | py | |
__author__ = ["Francisco Clavero"]
__email__ = ["fcoclavero32@gmail.com"]
__status__ = "Prototype"
""" Custom Ignite metrics for GANs. """
from abc import ABC
import torch
from ignite.exceptions import NotComputableError
from ignite.metrics import Metric
from ignite.metrics.metric import reinit__is_reduced
from i... | vscvs/metrics/gan.py | MIT | 7,094 | febafed73826230a0ba299cbe128ecc7bb99b4de | Python | py | |
from motionAE.src.motionTrainer import motionTrainer
import os
from tqdm import tqdm
import shutil
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable
from util.arg_parser import ArgParser
from motionAE.src.models import lstmAE_wo_Norm, lstmDecoder, Discriminator_frame, Dis... | motionAE/src/motionGANTrainer.py | MIT | 11,633 | 7c267a5ceeb7fa327ccbd7920b6bce154e34eefc | Python | py | |
import torch
import random
import numpy as np
from PIL import Image, ImageOps, ImageFilter
class Normalize(object):
"""Normalize a tensor image with mean and standard deviation.
Args:
mean (tuple): means for each channel.
std (tuple): standard deviations for each channel.
"""
def __ini... | dataloaders/custom_transforms.py | MIT | 5,083 | febb4012dcbc8ae6036db4bd2885c5ea1c3793ee | Python | py | |
"""
Implementation of BaseModel taken and modified from here
https://github.com/kwotsin/mimicry/blob/master/torch_mimicry/nets/basemodel/basemodel.py
"""
import os
from abc import ABC, abstractmethod
import torch
import torch.nn as nn
class BaseModel(nn.Module, ABC):
r"""
BaseModel with basic functionalities... | lib/model/BaseModelClass.py | BSD-2-Clause | 1,413 | 24ff0248403d89fbabb34046f6d8b4452572f6af | Python | py | |
from typing import List
import torch
from torch.utils.hooks import RemovableHandle
from models.networks.assisting_layers.L0_Layers import L0Linear, L0Conv2d
class FLOPCounter:
"""
Estimates current FLOPS usage of one sample or cumulatively
Loosely based on implementation from:
Rethinking the Value ... | models/statistics/Flops.py | MIT | 5,977 | a941131177489c9cb5996c1dc4648491fc30d7ee | Python | py | |
import os
import numpy as np
from PIL import Image
from scipy.ndimage import rotate
from copy import deepcopy
from sklearn.metrics import auc
from skimage import morphology, graph
import torch
import torch.nn as nn
import scipy as sp
from random import randint
def load_DRIVE(patch_size):
safe_size = int(np.ceil... | code/utils.py | MIT | 11,185 | f978d0e87fd53b936cde048e3a99a3ab0ddfd47d | Python | py |
⚠️ Pytorch-Code-50K — BETA
Status: BETA. This is an early, unpolished release. The data is real but unaudited: it has not been manually reviewed, re-verified against upstream, or checked for toxic/low-quality content beyond the filters listed below. The sample may change between releases. Use at your own risk and do not treat it as a benchmark.
Overview
Pytorch-Code-50K is a collection of ~50,000 Python source files that use the PyTorch ecosystem, extracted from BigCode's The Stack (Python subset).
It is intended as a lightweight, easy-to-consume corpus for:
- fine-tuning and pre-training small code models on PyTorch idioms,
- studying how PyTorch APIs are actually used in the wild,
- retrieval / RAG over real PyTorch examples,
- quick prototyping where a full 3 TB dataset is overkill.
Source
| Upstream | bigcode/the-stack (data/python) |
| Curated by | Monster-Code |
| Language | Python |
| Domain | PyTorch / deep learning code |
| Size | ~50,000 files |
| Format | Parquet (one row per file) |
| Release | BETA v0.1 |
The Stack is a collection of source code from repositories with various licenses. Any use of all or part of the code in this dataset must abide by the terms of the original licenses, including attribution clauses when relevant. Provenance (
repo,path,license,sha) is preserved so you can attribute and filter correctly.
Selection criteria
A file is included when all of the following hold:
It comes from the Python subset of The Stack.
Its source contains a top-level import from the PyTorch ecosystem, matched with this regex:
^[ \t]*(?:import|from)[ \t]+( torch(vision|audio|text|arrow|metrics|_geometric|_scatter|_sparse| _cluster|_spline_conv|_xla|_cpp|_jit|_onnx|_fx)? | pytorch_lightning | lightning(\.pytorch)? | skorch )\bIts length is between 200 and 200,000 characters.
Its content hash is unique within the sample (exact duplicates removed).
Sampling
The Stack stores files grouped by repository, so a naive "first 50K" pass would
be dominated by whichever repositories sort first. Instead, update.py
reservoir-samples over a randomly shuffled subset of the source shards, so
the sample is approximately uniform over the scanned shards rather than biased
toward any one repository. Pass --seed to reproduce or vary the sample.
Dataset schema
| Column | Type | Description |
|---|---|---|
content |
string |
The full source code of the file. |
repo |
string |
Repository identifier (owner/name) when available. |
path |
string |
File path within the repository, when available. |
license |
string |
Detected license(s), comma-separated if multiple. |
size |
int64 |
File size in bytes. |
sha |
string |
Content hash from the source dataset. |
lang |
string |
Language tag (always python here). |
ext |
string |
File extension (.py). |
Source column names vary between The Stack releases;
update.pymaps them defensively. Columns that are missing upstream are emitted as empty strings.
Usage
from datasets import load_dataset
ds = load_dataset("Monster-Code/Pytorch-Code-50K", split="train")
print(ds)
# Dataset({
# features: ['content', 'repo', 'path', 'license', 'size', 'sha', 'lang', 'ext'],
# num_rows: 50000
# })
# Only permissively licensed files
ds = ds.filter(lambda x: "mit" in x["license"].lower())
# A single training example
print(ds[0]["content"][:500])
Stream it instead of downloading everything:
ds = load_dataset("Monster-Code/Pytorch-Code-50K", split="train", streaming=True)
for row in ds:
...
How it was built
pip install huggingface_hub pyarrow
# accept the terms of the source dataset once:
# https://huggingface.co/datasets/bigcode/the-stack
python update.py # full 50K build
python update.py --dry-run # scan and report, push nothing
update.py:
- lists the Python parquet shards of
bigcode/the-stack, - shuffles them with a seed and downloads them through the HF cache (re-runs are incremental),
- filters by the PyTorch import regex and length bounds,
- reservoir-samples 50,000 unique files,
- writes local parquet shards and pushes them plus this card to the Hub.
The script is idempotent and resumable: source shards are cached under cache/
and already-downloaded shards are skipped.
Known limitations (BETA)
- Not exhaustively filtered. Files may contain security-sensitive code, secrets committed to version control, or license-incompatible snippets. No manual review has been performed.
- Import-based selection. Files that use PyTorch only through a wrapper
(e.g.
transformerswithout importingtorch) are not included. Files that mentionimport torchin a docstring/comment may be included. - Sampling bias. The sample is uniform over a random subset of shards, not over all PyTorch files on GitHub. Repositories whose code is heavily duplicated may still be over-represented.
- Duplicates. The Stack is not deduplicated, so the same file can appear more than once (across repositories) and very similar files are common.
- License metadata is noisy.
licensecomes from upstream detection and may be missing, wrong, or list several licenses. - Beta may change. Rows and schema may change in future releases; pin a revision if you need reproducibility.
Terms of use
This dataset is distributed for research purposes. You are responsible for complying with the licenses of the original repositories. By using this dataset you agree to the Terms of Use of The Stack.
Citation
If you use this dataset, please cite The Stack and this release:
@misc{pytorch-code-50k,
title = {Pytorch-Code-50K (BETA)},
author = {Monster-Code},
year = {2026},
howpublished = {\url{https://huggingface.co/datasets/Monster-Code/Pytorch-Code-50K}}
}
@article{BigCodeTheStack,
title = {The Stack: 3 TB of permissively licensed source code},
author = {BigCode Project},
journal = {arXiv preprint arXiv:2211.15533},
year = {2022}
}
Contact
Questions, takedown requests, or complaints about specific files: open a discussion on the dataset repo or contact the Monster-Code maintainers.
This is a BETA release. Expect rough edges. Please report issues on the dataset's Hugging Face page.
- Downloads last month
- 10