python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import dataclasses from typing import Dict, List, NamedTuple, Tuple import unittest from co3d.dataset import data_types as...
co3d-main
tests/test_types.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import unittest import numpy as np import tempfile import torch from pytorch3d.renderer.cameras imp...
co3d-main
tests/test_challenge_evaluate.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import json from joblib import Parallel, delayed from collections import defaultdict from tabulate i...
co3d-main
examples/print_co3d_stats.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import logging import os import torch import math import sys import json import random from tqdm import tqdm ...
co3d-main
examples/show_co3d_dataset.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import logging import os import torch import warnings from tqdm import tqdm from omegaconf import DictConfig ...
co3d-main
examples/example_co3d_challenge_submission.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os from dataset.download_dataset_impl import build_arg_parser, download_dataset DEFAULT_LINK_LIST_FILE = os.path....
co3d-main
co3d/download_dataset.py
co3d-main
co3d/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree.
co3d-main
co3d/dataset/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import sys import dataclasses import gzip import json from dataclasses import dataclass, Field, MISSING from ty...
co3d-main
co3d/dataset/data_types.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch import copy from pytorch3d.implicitron.dataset.dataset_base import FrameData from co3d.challenge....
co3d-main
co3d/dataset/utils.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import shutil import requests import functools import json import warnings from argparse import ArgumentParser f...
co3d-main
co3d/dataset/download_dataset_impl.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import glob import argparse import hashlib import json from typing import Optional from multiprocessing import P...
co3d-main
co3d/dataset/check_checksum.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. """ Evaluation of Implicitron models on CO3Dv2 challenge. """ import logging import os import torch import js...
co3d-main
co3d/utils/evaluate_implicitron_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import dataclasses import torch from typing import Tuple from pytorch3d.renderer.cameras import CamerasBase fr...
co3d-main
co3d/utils/dbir_utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import shutil import logging import errno import pickle import glob import hashlib import time from ...
co3d-main
co3d/challenge/co3d_submission.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import json import logging import numpy as np import dbm import functools import h5py from io impor...
co3d-main
co3d/challenge/io.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree.
co3d-main
co3d/challenge/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import math import numpy as np import logging import time from typing import Optional from typing import Tuple ...
co3d-main
co3d/challenge/metric_utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from enum import Enum import numpy as np from dataclasses import dataclass from typing import Optional @data...
co3d-main
co3d/challenge/data_types.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import zipfile import glob import logging import multiprocessing import numpy as np import time from...
co3d-main
co3d/challenge/utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from io import StringIO import os import csv from typing import List, Any from .data_types import CO3DTask, C...
co3d-main
co3d/challenge/blank_predictions_results.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from pathlib import Path from setuptools import setup # type: ignore setup( name="cc_net", version="1.0.0", pa...
cc_net-main
setup.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # """ Main script to download a CC dump, remove duplicates, split by language and filter the documents. The pipeline parameters are described...
cc_net-main
cc_net/mine.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # """ Creates mono-lingual corpus from Wikipedia. """ import functools import re import subprocess import urllib.request from pathlib import ...
cc_net-main
cc_net/get_wiki_cirrus.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # """ Manipulate files containing one json per line. """ import argparse import collections import contextlib import functools import glob imp...
cc_net-main
cc_net/jsonql.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import functools import itertools import logging import os import sys import time import warnings from pathlib import Path from typing impor...
cc_net-main
cc_net/execution.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import sys import time import warnings from typing import Iterable, Iterator, Sequence, Sized, Tuple, Type import numpy as np HASH_TYPE: T...
cc_net-main
cc_net/flat_hash_set.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import base64 import hashlib import itertools import urllib.parse from pathlib import Path from typing import Dict, Iterable, List, Optional...
cc_net-main
cc_net/minify.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import re import unicodedata UNICODE_PUNCT = { ",": ",", "。": ".", "、": ",", "„": '"', "”": '"', "“": '"', "«":...
cc_net-main
cc_net/text_normalizer.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import logging import subprocess from pathlib import Path from typing import List import func_argparse import numpy as np from cc_net impo...
cc_net-main
cc_net/regroup.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import argparse import time from pathlib import Path from typing import Dict, List, Optional, Sequence, Tuple, Union import kenlm # type: ...
cc_net-main
cc_net/perplexity.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. #
cc_net-main
cc_net/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import time from typing import Dict, Optional import sacremoses # type: ignore from cc_net import jsonql, text_normalizer class RobustT...
cc_net-main
cc_net/tokenizer.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # """ Tools to remove duplicate paragraphs across one or several shards. """ import argparse import gc import hashlib import logging import m...
cc_net-main
cc_net/dedup.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import contextlib import functools import logging import re import tempfile import time import urllib.request from pathlib import Path from ...
cc_net-main
cc_net/process_wet_file.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import func_argparse import cc_net.mine def main(): func_argparse.parse_and_call(cc_net.mine.get_main_parser()) if __name__ == "__...
cc_net-main
cc_net/__main__.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import collections from pathlib import Path from typing import Dict, Optional import fasttext # type: igno...
cc_net-main
cc_net/split_by_lang.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import contextlib import functools import gzip import logging import multiprocessing from collections import defaultdict from pathlib import...
cc_net-main
cc_net/tools/dl_cc_100.py
cc_net-main
cc_net/tools/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # """ This code is used to train a fastText classifier to label document with DMOZ categories. The data, distributed under the cc-by 3.0 lice...
cc_net-main
cc_net/tools/make_dmoz_corpus.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # """ Tools to search sentences in CC similar to sentences in another corpus. """ import functools import logging import math import subproce...
cc_net-main
cc_net/tools/expand_corpus.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import json from pathlib import Path from typing import Iterable, Sequence from cc_net import dedup, jsonql from cc_net.dedup import str_ha...
cc_net-main
tests/test_dedup.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import cc_net.text_normalizer as txt def test_unicode_punct(): weird = ",。、„”“«»1」「《》´∶:?!();–—.~’…━〈〉【】%" replaced = ',.,""""""""...
cc_net-main
tests/test_normalizer.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # from pathlib import Path from cc_net import process_wet_file def test_parsing(): sample = Path(__file__).parent / "data" / "sample.wa...
cc_net-main
tests/test_parse_wet_file.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import numpy as np import pytest from cc_net.flat_hash_set import HASH_TYPE, FlatHashSet, NaiveHashSet def as_dict(flat_hash_set) -> dict...
cc_net-main
tests/test_flat_hash_set.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import pytest def _request_is_disabled(self, *args, **kwargs): raise Exception( f"Your code tried to call 'request' with: {arg...
cc_net-main
tests/conftest.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # #
cc_net-main
tests/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import time from cc_net import jsonql, regroup def check_regroup(tmp_path, regroup_fn, check_blocks_boundaries=False): n_shards = 4 ...
cc_net-main
tests/test_regroup.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import io from pathlib import Path from typing import Sequence import numpy as np import pytest from cc_net import jsonql def bar(small_...
cc_net-main
tests/test_jsonql.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import json from pathlib import Path import pytest import cc_net import cc_net.minify as minify from cc_net import jsonql, process_wet_fil...
cc_net-main
tests/test_minify.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import inspect import pickle from pathlib import Path import pytest from cc_net import dedup, jsonql, perplexity, split_by_lang, tokenizer...
cc_net-main
tests/test_transformer.py
# Adapted from https://github.com/NVIDIA/apex/blob/master/setup.py import torch from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME from setuptools import setup, find_packages import subprocess import sys import warnings import os # ninja build does not work unless include_dir...
m2-main
csrc/flashmm/setup.py
import torch import torch.nn.functional as F from einops import rearrange import math torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True from flashmm import mm_block_fwd, hyena_filter_fwd, exp_mod_in_place_fwd def ref_mm_block( u, linear, out_linear, x1_s, x2_s, v_s, ...
m2-main
csrc/flashmm/test_flash_mm.py
import math import re import numpy as np # N = 8192 N = 16384 # The case of 0 / N is special, we want to simplify it to 0 / 2 instead of 0 / 1 numerator = np.arange(1, N // 8 + 1) gcd = np.gcd(numerator, N) num = numerator // gcd denom = N // gcd lut_vals = ['T_2_0'] + [f'T_{d}_{n}' for n, d in zip(num, denom)] lut_...
m2-main
csrc/flashmm/lut_code_gen.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 import os import sys from typing import Optional, cast # Add folder root to path to allow us to use relative imports regardless of what directory the script is run from sys.path.append(os.path.dirname(os.path.realpath(__file__))) import...
m2-main
bert/benchmark_fwd.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 import os import sys # Add folder root to path to allow us to use relative imports regardless of what directory the script is run from sys.path.append(os.path.dirname(os.path.realpath(__file__))) try: import torch # yapf: disabl...
m2-main
bert/__init__.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 import copy import gc import multiprocessing as mp import os import sys import time from collections import defaultdict from concurrent.futures import ProcessPoolExecutor as Pool from multiprocessing.managers import DictProxy, SyncManager...
m2-main
bert/glue.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 import os import sys from typing import Optional, cast # Add folder root to path to allow us to use relative imports regardless of what directory the script is run from sys.path.append(os.path.dirname(os.path.realpath(__file__))) import...
m2-main
bert/main.py
from transformers import BertConfig class BertConfig(BertConfig): def __init__( self, alibi_starting_size: int = 512, attention_probs_dropout_prob: float = 0.0, # mlp use_glu_mlp: bool = True, use_monarch_mlp: bool = False, monarch_mlp_nblocks: int = 4, ...
m2-main
bert/src/configuration_bert.py
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2022, Tri Dao. # Copyright (c) 2023, MosaicML. # Copyright (c) 2023, Dan Fu and Simran Arora. import copy import logging import math import os import ...
m2-main
bert/src/bert_layers.py
# Adapted from https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/bert_padding.py # Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py """ Functions for FlashAttention padding and unpadding """ from typing import Tup...
m2-main
bert/src/bert_padding.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 """Implements a Hugging Face BERT wrapped inside a :class:`.ComposerModel`.""" from __future__ import annotations from typing import Optional from composer.metrics.nlp import (BinaryF1Score, LanguageCrossEntropy, ...
m2-main
bert/src/hf_bert.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 import os import sys import torch # Add src folder root to path to allow us to use relative imports regardless of what directory the script is run from sys.path.append(os.path.dirname(os.path.realpath(__file__))) # yapf: disable from b...
m2-main
bert/src/__init__.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 """Triton implementation of Flash Attention. # Copyright (c) 2022, Tri Dao. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of...
m2-main
bert/src/flash_attn_triton.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import os import sys from typing import Optional # Add src folder root to path to allow us to use relative imports regardless of what directory the script is run from sys.path.append(os.path.dirname(os...
m2-main
bert/src/create_bert.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 """Build a StreamingTextDataset dataset and dataloader for training.""" import os from itertools import islice from typing import Any, Callable, Dict, List, Optional, Sequence, Union import numpy as np import torch import transformers f...
m2-main
bert/src/text_data.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 """Streaming dataset conversion scripts for C4 and The Pile.""" import os import platform import warnings from argparse import ArgumentParser, Namespace from dataclasses import dataclass from enum import Enum from typing import Dict, Iter...
m2-main
bert/src/convert_dataset.py
# Adapted from https://github.com/HazyResearch/hippo/blob/datasets/benchmark/utils.py """ Useful functions for writing test code. """ import torch import torch.utils.benchmark as benchmark def benchmark_forward(fn, *inputs, repeats = 10, desc='', verbose=True, amp=False, amp_dtype=torch.float16...
m2-main
bert/src/benchmark/benchmark.py
m2-main
bert/src/benchmark/__init__.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 # """Contains GLUE job objects for the simple_glue_trainer.""" import atexit import copy import gc import multiprocessing as mp import os import sys from multiprocessing import managers from typing import Any, Dict, List, Optional, Union,...
m2-main
bert/src/glue/finetuning_jobs.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0
m2-main
bert/src/glue/__init__.py
# Copyright 2022 MosaicML Examples authors # SPDX-License-Identifier: Apache-2.0 import logging from composer.utils import MissingConditionalImportError, dist _task_column_names = { 'cola': ('sentence', None), 'mnli': ('premise', 'hypothesis'), 'mrpc': ('sentence1', 'sentence2'), 'qnli': ('question',...
m2-main
bert/src/glue/data.py
def create_param_groups(cfg, model): '''Create sets of parameter groups based on whether parameter has `_optim` attribute.''' if not any(hasattr(p, '_optim') for p in model.parameters()): return model.parameters() special_params = set() other_params = set() param_dict = {pn: p for pn, p...
m2-main
bert/src/optim/create_param_groups.py
m2-main
bert/src/optim/__init__.py
import json import math from tqdm import tqdm from collections import defaultdict directory = # Enter path to your data directory here new_directory = # Enter output path here val_pct = 0.0005 # Percentage of data to use for validation index = f"{directory}/train/index.json" with open(index, "r") as f: index = js...
m2-main
bert/src/utils/create_val_split.py
m2-main
bert/src/utils/__init__.py
""" Utils for the training loop. Copied from https://github.com/HazyResearch/transformers/blob/master/src/utils/utils.py """ import torch.nn as nn class OptimModule(nn.Module): """ Interface for Module that allows registering buffers/parameters with configurable optimizer hyperparameters """ def register(self...
m2-main
bert/src/utils/train.py
# Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers import math import torch import torch.nn as nn from einops import rearrange from src.mm.structured_linear import StructuredLinear from src.mm.blockdiag_multiply import blockdiag_multiply class BlockdiagLinear(StructuredLinear): de...
m2-main
bert/src/mm/blockdiag_linear.py
# Copyright (c) 2023, Dan Fu and Simran Arora. # Adapted from https://github.com/HazyResearch/safari/blob/main/src/models/sequence/hyena.py import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange import opt_einsum as oe contract = oe.contract from src.utils.train ...
m2-main
bert/src/mm/hyena_utils.py
# Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers import math import numpy as np import torch from torch.nn import functional as F from einops import rearrange def blockdiag_butterfly_multiply_reference(x, w1_bfly, w2_bfly, version=2): """ This implementation is slow but more...
m2-main
bert/src/mm/blockdiag_butterfly_multiply.py
# Copyright (c) 2023, Dan Fu and Simran Arora. # Adapted from https://github.com/HazyResearch/safari/blob/main/src/models/sequence/hyena.py import torch.nn as nn from einops import rearrange import opt_einsum as oe contract = oe.contract from src.mm.hyena_utils import HyenaFilter class MonarchMixerSequenceMixing(nn...
m2-main
bert/src/mm/monarch_mixer_sequence_mixer.py
# Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers import numpy as np import torch from torch.nn import functional as F from einops import rearrange def blockdiag_weight_to_dense_weight(weight): """ Argumments: weight: (nblocks, out / nblocks, in / blocks) Return: ...
m2-main
bert/src/mm/blockdiag_multiply.py
m2-main
bert/src/mm/__init__.py
# Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init class StructuredLinear(nn.Module): def __init__(self, in_features, out_features, bias=True, devi...
m2-main
bert/src/mm/structured_linear.py
# Copyright (c) 2023, Dan Fu and Simran Arora. import torch import torch.nn as nn import math from einops import rearrange import opt_einsum as oe contract = oe.contract from flashmm import mm_block_fwd, hyena_filter_fwd, exp_mod_in_place_fwd from src.utils.train import OptimModule def fast_mm_block( u, line...
m2-main
bert/src/mm/flash_mm.py
import torch from einops import rearrange def low_rank_project(M, rank): """Supports batches of matrices as well. """ U, S, Vt = torch.linalg.svd(M) S_sqrt = S[..., :rank].sqrt() U = U[..., :rank] * rearrange(S_sqrt, '... rank -> ... 1 rank') Vt = rearrange(S_sqrt, '... rank -> ... rank 1') *...
m2-main
bert/src/ops/low_rank.py
import math import torch from einops import rearrange def butterfly_factor_to_matrix(twiddle: torch.Tensor, factor_index: int) -> torch.Tensor: """ Let b be the base (most commonly 2). Parameters: twiddle: (n // b, b, b) factor_index: an int from 0 to log_b(n) - 1 """ n_div_b, b, ...
m2-main
bert/src/ops/butterfly_factor.py
import torch import torch.nn as nn import torch.nn.functional as F import flash_attn_cuda def _get_block_size(device, head_dim, is_dropout): assert head_dim % 8 == 0 and head_dim <= 128 return 256 if head_dim <= 64 else 128 def _flash_attn_forward(q, k, v, out, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max...
m2-main
bert/src/ops/bert_flashattention.py
# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py import torch import torch.nn.functional as F from einops import rearrange, repeat class IndexFirstAxis(torch.autograd.Function): @staticmethod def forward(ctx, input, indice...
m2-main
bert/src/ops/bert_padding.py
import numpy as np import torch from torch.nn import functional as F from einops import rearrange from src.ops.low_rank import low_rank_project def blockdiag_weight_to_dense_weight(weight): """ Argumments: weight: (nblocks, out / nblocks, in / blocks) Return: dense_weight: (out / in) ...
m2-main
bert/src/ops/blockdiag_multiply.py
import math import torch import torch.nn as nn from einops import rearrange from src.models.layers.blockdiag_butterfly_multiply import blockdiag_butterfly_multiply # from src.ops.low_rank import low_rank_project # Copied here so it's more self-contained def low_rank_project(M, rank): """Supports batches of mat...
m2-main
bert/src/ops/blockdiag_butterfly_projection.py
import torch @torch.jit.script def jit_dropout_add(x, residual, prob): # type: (Tensor, Tensor, float) -> Tensor return torch.nn.functional.dropout(x, p=prob, training=True) + residual def fused_dropout_add(x, residual, prob, is_training) : # type: (Tensor, Tensor, float, bool) -> Tensor if is_train...
m2-main
bert/src/ops/fused_dropout_add.py
# Adapted from https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py # On the backward pass, we don't use the fused kernel from cublasLt since that's a bit slower. # Instead we use the regular backward from F.linear. # We also make it work with pytorch amp. # TD [2022-02-27] The fused backward is a...
m2-main
bert/src/ops/fused_dense.py
import torch from einops import rearrange from src.ops.low_rank import low_rank_project def blockdiag_butterfly_multiply_einsum_simple(x, w1_bfly, w2_bfly): """ Arguments: x: (batch, n) w1_bfly: (k, j, i), where k = n / i w2_bfly: (j, l, k) Outputs: out: (batch, m), where...
m2-main
bert/src/ops/blockdiag_butterfly_einsum.py
import torch from softmaxlib import additive_masked_softmax_dropout_forward from softmaxlib import masked_scale_softmax_backward_recompute from src.ops.triton.softmax_dropout import softmax_dropout class _fused_softmax_dropout(torch.autograd.Function): @staticmethod def forward(ctx, x, p, mask, return_drop...
m2-main
bert/src/ops/fused_softmax_dropout.py
from PIL import Image, ImageEnhance, ImageOps import numpy as np from torchvision import transforms import random norm_stats = { "imagenet": ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), "clevr": ([0.47097, 0.46812, 0.46185, 0], [0.08974, 0.08686, 0.09197, 1]), "cxr": ([0.48865], [0.24621]), "poet": ...
observational-main
transforms.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models import json import os import pickle from emmental.scorer import Scorer from emmental.task import EmmentalTask from emmental.data import EmmentalDataLoader from emmental.utils.utils import pred_to_prob,...
observational-main
emmental_utils.py
import logging import os, sys import argparse import emmental from emmental import Meta from emmental.learner import EmmentalLearner from emmental.model import EmmentalModel from emmental.utils.parse_args import parse_args, parse_args_to_config from emmental_utils import ( fetch_dataloaders, create_tasks, ...
observational-main
train_emmental.py
observational-main
__init__.py
import matplotlib.pyplot as plt import matplotlib.pyplot as plt import cv2 import pydicom def plot_heatmap(source, img_pth, heatmap): figure, axs = plt.subplots(nrows=1, ncols=2) if source == "cxr": ds = pydicom.dcmread(img_pth) img = ds.pixel_array else: img = plt.imread(img_pth...
observational-main
viz_utils.py