index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,815 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/pretrained.py | 41,42 | 1,99 | _parse_remote_files | 42,59 | 42,59 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Loading pretrained models.
"""
import logging
from pathlib import Path
import typing as tp
from dora.log import fatal... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Loading pretrained models.
"""
import logging
from pathlib import Path
import typing as tp
from dora.log import fatal... | root: str = ''
models: tp.Dict[str, str] = {}
for line in remote_file_list.read_text().split('\n'):
line = line.strip()
if line.startswith('#'):
continue
elif len(line) == 0:
continue
elif line.startswith('root:'):
root = line.split(':', 1)... | root: str = ''
models: tp.Dict[str, str] = {}
for line in remote_file_list.read_text().split('\n'):
line = line.strip()
if line.startswith('#'):
continue
elif len(line) == 0:
continue
elif line.startswith('root:'):
root = line.split(':', 1)... | 49 | 902 | 172 | 1,074 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Loading pretrained models.
"""
import logging
from pathlib import Path
import typing as tp
from dora.log import fatal... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Loading pretrained models.
"""
import logging
from pathlib import Path
import typing as tp
from dora.log import fatal... | |
13,816 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/repo.py | 29,30 | 1,167 | check_checksum | 30,43 | 30,43 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | sha = sha256()
with open(path, 'rb') as file:
while True:
buf = file.read(2**20)
if not buf:
break
sha.update(buf)
actual_checksum = sha.hexdigest()[:len(checksum)]
if actual_checksum != checksum:
raise ModelLoadingError(f'Invalid check... | sha = sha256()
with open(path, 'rb') as file:
while True:
buf = file.read(2**20)
if not buf:
break
sha.update(buf)
actual_checksum = sha.hexdigest()[:len(checksum)]
if actual_checksum != checksum:
raise ModelLoadingError(f'Invalid check... | 37 | 1,555 | 144 | 1,699 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | |
13,817 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/repo.py | 156,157 | 148,167 | get_model | AnyModelRepo | 157,162 | 157,162 | class AnyModelRepo:
def __init__(self, model_repo: ModelOnlyRepo, bag_repo: BagOnlyRepo):
self.model_repo = model_repo
self.bag_repo = bag_repo
def has_model(self, name_or_sig: str) -> bool:
return self.model_repo.has_model(name_or_sig) or self.bag_repo.has_model(name_or_sig)
def g... | class AnyModelRepo:
def __init__(self, model_repo: ModelOnlyRepo, bag_repo: BagOnlyRepo):
self.model_repo = model_repo
self.bag_repo = bag_repo
def has_model(self, name_or_sig: str) -> bool:
return self.model_repo.has_model(name_or_sig) or self.bag_repo.has_model(name_or_sig)
def g... | if self.model_repo.has_model(name_or_sig):
return self.model_repo.get_model(name_or_sig)
else:
return self.bag_repo.get_model(name_or_sig)
| if self.model_repo.has_model(name_or_sig):
return self.model_repo.get_model(name_or_sig)
else:
return self.bag_repo.get_model(name_or_sig)
| 7 | 221 | 67 | 288 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... |
13,818 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/repo.py | 131,132 | 113,148 | get_model | BagOnlyRepo | 132,144 | 132,144 | class BagOnlyRepo:
"""Handles only YAML files containing bag of models, leaving the actual
model loading to some Repo.
"""
def __init__(self, root: Path, model_repo: ModelOnlyRepo):
self.root = root
self.model_repo = model_repo
self.scan()
def scan(self):
self._bags ... | class BagOnlyRepo:
"""Handles only YAML files containing bag of models, leaving the actual
model loading to some Repo.
"""
def __init__(self, root: Path, model_repo: ModelOnlyRepo):
self.root = root
self.model_repo = model_repo
self.scan()
def scan(self):
self._bags ... | try:
yaml_file = self._bags[name]
except KeyError:
raise ModelLoadingError(f'{name} is neither a single pre-trained model or '
'a bag of models.')
bag = yaml.safe_load(open(yaml_file))
signatures = bag['models']
models =... | try:
yaml_file = self._bags[name]
except KeyError:
raise ModelLoadingError(f'{name} is neither a single pre-trained model or '
'a bag of models.')
bag = yaml.safe_load(open(yaml_file))
signatures = bag['models']
models =... | 43 | 232 | 152 | 384 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... |
13,819 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/repo.py | 81,82 | 76,113 | scan | LocalRepo | 82,97 | 82,97 | class LocalRepo(ModelOnlyRepo):
def __init__(self, root: Path):
self.root = root
self.scan()
def scan(self):
FILL_FUNC_BODY def has_model(self, sig: str) -> bool:
return sig in self._models
def get_model(self, sig: str) -> Model:
try:
file = self._models[sig]... | class LocalRepo(ModelOnlyRepo):
def __init__(self, root: Path):
self.root = root
self.scan()
def scan(self):
FILL_FUNC_BODY def has_model(self, sig: str) -> bool:
return sig in self._models
def get_model(self, sig: str) -> Model:
try:
file = self._models[sig]... | self._models = {}
self._checksums = {}
for file in self.root.iterdir():
if file.suffix == '.th':
if '-' in file.stem:
xp_sig, checksum = file.stem.split('-')
self._checksums[xp_sig] = checksum
else:
... | self._models = {}
self._checksums = {}
for file in self.root.iterdir():
if file.suffix == '.th':
if '-' in file.stem:
xp_sig, checksum = file.stem.split('-')
self._checksums[xp_sig] = checksum
else:
... | 51 | 217 | 179 | 396 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... |
13,820 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/repo.py | 49,50 | 43,56 | get_model | ModelOnlyRepo | 50,52 | 50,52 | class ModelOnlyRepo:
"""Base class for all model only repos.
"""
def has_model(self, sig: str) -> bool:
raise NotImplementedError()
def get_model(self, sig: str) -> Model:
FILL_FUNC_BODY def list_model(self) -> tp.Dict[str, tp.Union[str, Path]]:
raise NotImplementedError()
| class ModelOnlyRepo:
"""Base class for all model only repos.
"""
def has_model(self, sig: str) -> bool:
raise NotImplementedError()
def get_model(self, sig: str) -> Model:
FILL_FUNC_BODY def list_model(self) -> tp.Dict[str, tp.Union[str, Path]]:
raise NotImplementedError()
| raise NotImplementedError()
| raise NotImplementedError()
| 2 | 117 | 12 | 129 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... |
13,821 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/repo.py | 63,64 | 56,76 | get_model | RemoteRepo | 64,72 | 64,72 | class RemoteRepo(ModelOnlyRepo):
def __init__(self, models: tp.Dict[str, str]):
self._models = models
def has_model(self, sig: str) -> bool:
return sig in self._models
def get_model(self, sig: str) -> Model:
FILL_FUNC_BODY def list_model(self) -> tp.Dict[str, tp.Union[str, Path]]:
... | class RemoteRepo(ModelOnlyRepo):
def __init__(self, models: tp.Dict[str, str]):
self._models = models
def has_model(self, sig: str) -> bool:
return sig in self._models
def get_model(self, sig: str) -> Model:
FILL_FUNC_BODY def list_model(self) -> tp.Dict[str, tp.Union[str, Path]]:
... | try:
url = self._models[sig]
except KeyError:
raise ModelLoadingError(f'Could not find a pre-trained model with signature {sig}.')
pkg = torch.hub.load_state_dict_from_url(
url, map_location='cpu', check_hash=True) # type: ignore
return load_model(pkg... | try:
url = self._models[sig]
except KeyError:
raise ModelLoadingError(f'Could not find a pre-trained model with signature {sig}.')
pkg = torch.hub.load_state_dict_from_url(
url, map_location='cpu', check_hash=True) # type: ignore
return load_model(pkg... | 27 | 136 | 105 | 241 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote re... |
13,822 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/demucs/states.py | 121,122 | 1,164 | serialize_model | 122,135 | 122,135 | # Copyright (c) Meta Platforms, Inc. and 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.
"""
Utilities to save and load models.
"""
from contextlib import contextmanager
import functools
import hashlib
import i... | # Copyright (c) Meta Platforms, Inc. and 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.
"""
Utilities to save and load models.
"""
from contextlib import contextmanager
import functools
import hashlib
import i... | args, kwargs = model._init_args_kwargs
klass = model.__class__
state = get_state(model, quantizer, half)
return {
'klass': klass,
'args': args,
'kwargs': kwargs,
'state': state,
'training_args': OmegaConf.to_container(training_args, resolve=True),
}
| args, kwargs = model._init_args_kwargs
klass = model.__class__
state = get_state(model, quantizer, half)
return {
'klass': klass,
'args': args,
'kwargs': kwargs,
'state': state,
'training_args': OmegaConf.to_container(training_args, resolve=True),
}
| 26 | 1,378 | 117 | 1,495 | # Copyright (c) Meta Platforms, Inc. and 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.
"""
Utilities to save and load models.
"""
from contextlib import contextmanager
import functools
import hashlib
import i... | # Copyright (c) Meta Platforms, Inc. and 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.
"""
Utilities to save and load models.
"""
from contextlib import contextmanager
import functools
import hashlib
import i... | |
13,823 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/tools/export.py | 25,26 | 1,72 | main | 26,70 | 26,70 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Export a trained model from the full checkpoint (with optimizer etc.) to
a final checkpoint, with only the model itsel... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Export a trained model from the full checkpoint (with optimizer etc.) to
a final checkpoint, with only the model itsel... | logging.basicConfig(level=logging.INFO, stream=sys.stderr)
parser = ArgumentParser("tools.export", description="Export trained models from XP sigs.")
parser.add_argument('signatures', nargs='*', help='XP signatures.')
parser.add_argument('-o', '--out', type=Path, default=Path("release_models"),
... | logging.basicConfig(level=logging.INFO, stream=sys.stderr)
parser = ArgumentParser("tools.export", description="Export trained models from XP sigs.")
parser.add_argument('signatures', nargs='*', help='XP signatures.')
parser.add_argument('-o', '--out', type=Path, default=Path("release_models"),
... | 138 | 231 | 640 | 871 | # Copyright (c) Meta Platforms, Inc. and 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.
"""Export a trained model from the full checkpoint (with optimizer etc.) to
a final checkpoint, with only the model itsel... | # Copyright (c) Meta Platforms, Inc. and 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.
"""Export a trained model from the full checkpoint (with optimizer etc.) to
a final checkpoint, with only the model itsel... | |
13,824 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_demucs/demucs/tools/test_pretrained.py | 18,19 | 1,44 | main | 19,42 | 19,42 | # Copyright (c) Meta Platforms, Inc. and 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.
# Script to evaluate pretrained models.
from argparse import ArgumentParser
import logging
import sys
import torch
fro... | # Copyright (c) Meta Platforms, Inc. and 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.
# Script to evaluate pretrained models.
from argparse import ArgumentParser
import logging
import sys
import torch
fro... | torch.set_num_threads(1)
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
parser = ArgumentParser("tools.test_pretrained",
description="Evaluate pre-trained models or bags of models "
"on MusDB.")
pretrained.add_model_flags(pa... | torch.set_num_threads(1)
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
parser = ArgumentParser("tools.test_pretrained",
description="Evaluate pre-trained models or bags of models "
"on MusDB.")
pretrained.add_model_flags(pa... | 48 | 127 | 289 | 416 | # Copyright (c) Meta Platforms, Inc. and 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.
# Script to evaluate pretrained models.
from argparse import ArgumentParser
import logging
import sys
import torch
fro... | # Copyright (c) Meta Platforms, Inc. and 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.
# Script to evaluate pretrained models.
from argparse import ArgumentParser
import logging
import sys
import torch
fro... | |
13,827 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/config/paths_catalog.py | 226,228 | 185,244 | get_c2_detectron_12_2017_baselines | ModelCatalog | 228,244 | 228,244 | class ModelCatalog(object):
S3_C2_DETECTRON_URL = "https://dl.fbaipublicfiles.com/detectron"
C2_IMAGENET_MODELS = {
"MSRA/R-50": "ImageNetPretrained/MSRA/R-50.pkl",
"MSRA/R-50-GN": "ImageNetPretrained/47261647/R-50-GN.pkl",
"MSRA/R-101": "ImageNetPretrained/MSRA/R-101.pkl",
"MSRA... | class ModelCatalog(object):
S3_C2_DETECTRON_URL = "https://dl.fbaipublicfiles.com/detectron"
C2_IMAGENET_MODELS = {
"MSRA/R-50": "ImageNetPretrained/MSRA/R-50.pkl",
"MSRA/R-50-GN": "ImageNetPretrained/47261647/R-50-GN.pkl",
"MSRA/R-101": "ImageNetPretrained/MSRA/R-101.pkl",
"MSRA... | # Detectron C2 models are stored following the structure
# prefix/<model_id>/2012_2017_baselines/<model_name>.yaml.<signature>/suffix
# we use as identifiers in the catalog Caffe2Detectron/COCO/<model_id>/<model_name>
prefix = ModelCatalog.S3_C2_DETECTRON_URL
dataset_tag = "keypo... | # Detectron C2 models are stored following the structure
# prefix/<model_id>/2012_2017_baselines/<model_name>.yaml.<signature>/suffix
# we use as identifiers in the catalog Caffe2Detectron/COCO/<model_id>/<model_name>
prefix = ModelCatalog.S3_C2_DETECTRON_URL
dataset_tag = "keypo... | 85 | 1,136 | 343 | 1,479 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
from copy import deepcopy
class DatasetCatalog(object):
DATA_DIR = "datasets"
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/a... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
from copy import deepcopy
class DatasetCatalog(object):
DATA_DIR = "datasets"
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/a... |
13,828 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/data/datasets/evaluation/coco/coco_eval_wrapper.py | 13,22 | 1,50 | do_coco_evaluation | 22,50 | 22,50 | # COCO style evaluation for custom datasets derived from AbstractDataset
# by botcs@github
import logging
import os
import json
from maskrcnn_benchmark.data.datasets.coco import COCODataset
from .coco_eval import do_coco_evaluation as orig_evaluation
from .abs_to_coco import convert_abstract_to_coco
def do_coco_eva... | # COCO style evaluation for custom datasets derived from AbstractDataset
# by botcs@github
import logging
import os
import json
from maskrcnn_benchmark.data.datasets.coco import COCODataset
from .coco_eval import do_coco_evaluation as orig_evaluation
from .abs_to_coco import convert_abstract_to_coco
def do_coco_eva... |
logger = logging.getLogger("maskrcnn_benchmark.inference")
logger.info("Converting annotations to COCO format...")
coco_annotation_dict = convert_abstract_to_coco(dataset)
dataset_name = dataset.__class__.__name__
coco_annotation_path = os.path.join(output_folder, dataset_name + ".json")
logge... |
logger = logging.getLogger("maskrcnn_benchmark.inference")
logger.info("Converting annotations to COCO format...")
coco_annotation_dict = convert_abstract_to_coco(dataset)
dataset_name = dataset.__class__.__name__
coco_annotation_path = os.path.join(output_folder, dataset_name + ".json")
logge... | 65 | 161 | 350 | 511 | # COCO style evaluation for custom datasets derived from AbstractDataset
# by botcs@github
import logging
import os
import json
from maskrcnn_benchmark.data.datasets.coco import COCODataset
from .coco_eval import do_coco_evaluation as orig_evaluation
from .abs_to_coco import convert_abstract_to_coco
def do_coco_eva... | # COCO style evaluation for custom datasets derived from AbstractDataset
# by botcs@github
import logging
import os
import json
from maskrcnn_benchmark.data.datasets.coco import COCODataset
from .coco_eval import do_coco_evaluation as orig_evaluation
from .abs_to_coco import convert_abstract_to_coco
def do_coco_eva... | |
13,830 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/data/transforms/build.py | 5,6 | 1,47 | build_transforms | 6,47 | 6,47 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from . import transforms as T
def build_transforms(cfg, is_train=True):
FILL_FUNC_BODY | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from . import transforms as T
def build_transforms(cfg, is_train=True):
FILL_FUNC_BODY | if is_train:
min_size = cfg.INPUT.MIN_SIZE_TRAIN
max_size = cfg.INPUT.MAX_SIZE_TRAIN
flip_horizontal_prob = cfg.INPUT.HORIZONTAL_FLIP_PROB_TRAIN
flip_vertical_prob = cfg.INPUT.VERTICAL_FLIP_PROB_TRAIN
brightness = cfg.INPUT.BRIGHTNESS
contrast = cfg.INPUT.CONTRAST
... | if is_train:
min_size = cfg.INPUT.MIN_SIZE_TRAIN
max_size = cfg.INPUT.MAX_SIZE_TRAIN
flip_horizontal_prob = cfg.INPUT.HORIZONTAL_FLIP_PROB_TRAIN
flip_vertical_prob = cfg.INPUT.VERTICAL_FLIP_PROB_TRAIN
brightness = cfg.INPUT.BRIGHTNESS
contrast = cfg.INPUT.CONTRAST
... | 84 | 55 | 505 | 560 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from . import transforms as T
def build_transforms(cfg, is_train=True):
FILL_FUNC_BODY | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from . import transforms as T
def build_transforms(cfg, is_train=True):
FILL_FUNC_BODY | |
13,832 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/modeling/detector/detectors.py | 8,9 | 1,11 | build_detection_model | 9,11 | 9,11 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .generalized_rcnn import GeneralizedRCNN
_DETECTION_META_ARCHITECTURES = {"GeneralizedRCNN": GeneralizedRCNN}
def build_detection_model(cfg):
FILL_FUNC_BODY | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .generalized_rcnn import GeneralizedRCNN
_DETECTION_META_ARCHITECTURES = {"GeneralizedRCNN": GeneralizedRCNN}
def build_detection_model(cfg):
FILL_FUNC_BODY | meta_arch = _DETECTION_META_ARCHITECTURES[cfg.MODEL.META_ARCHITECTURE]
return meta_arch(cfg)
| meta_arch = _DETECTION_META_ARCHITECTURES[cfg.MODEL.META_ARCHITECTURE]
return meta_arch(cfg)
| 5 | 85 | 45 | 130 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .generalized_rcnn import GeneralizedRCNN
_DETECTION_META_ARCHITECTURES = {"GeneralizedRCNN": GeneralizedRCNN}
def build_detection_model(cfg):
FILL_FUNC_BODY | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .generalized_rcnn import GeneralizedRCNN
_DETECTION_META_ARCHITECTURES = {"GeneralizedRCNN": GeneralizedRCNN}
def build_detection_model(cfg):
FILL_FUNC_BODY | |
13,833 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/env.py | 20,21 | 1,38 | setup_custom_environment | 24,37 | 21,37 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from maskrcnn_benchmark.utils.imports import import_file
def setup_environment():
"""Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file that performs
... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from maskrcnn_benchmark.utils.imports import import_file
def setup_environment():
"""Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file that performs
... | module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_module_path)
assert hasattr(module, "setup_environment") and callable(
module.setup_environment
), (
"Custom environment module defined in {} does not have the "
"required callable attribute 'setup_environment'... | """Load custom environment setup from a Python source file and run the setup
function.
"""
module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_module_path)
assert hasattr(module, "setup_environment") and callable(
module.setup_environment
), (
"Custom enviro... | 40 | 224 | 132 | 356 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from maskrcnn_benchmark.utils.imports import import_file
def setup_environment():
"""Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file that performs
... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from maskrcnn_benchmark.utils.imports import import_file
def setup_environment():
"""Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file that performs
... | |
13,834 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/logger.py | 7,8 | 1,26 | setup_logger | 8,26 | 8,26 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import sys
def setup_logger(name, save_dir, distributed_rank, filename="log.txt"):
FILL_FUNC_BODY | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import sys
def setup_logger(name, save_dir, distributed_rank, filename="log.txt"):
FILL_FUNC_BODY | logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# don't log results for the non-master process
if distributed_rank > 0:
return logger
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)s %(levelna... | logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# don't log results for the non-master process
if distributed_rank > 0:
return logger
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)s %(levelna... | 41 | 65 | 217 | 282 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import sys
def setup_logger(name, save_dir, distributed_rank, filename="log.txt"):
FILL_FUNC_BODY | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import sys
def setup_logger(name, save_dir, distributed_rank, filename="log.txt"):
FILL_FUNC_BODY | |
13,835 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/miscellaneous.py | 9,10 | 1,40 | mkdir | 10,17 | 10,17 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import errno
import json
import logging
import os
from .comm import is_main_process
def mkdir(path):
FILL_FUNC_BODYdef save_labels(dataset_list, output_dir):
if is_main_process():
logger = logging.getLogger(__name__)
ids_to_l... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import errno
import json
import logging
import os
from .comm import is_main_process
def mkdir(path):
FILL_FUNC_BODYdef save_labels(dataset_list, output_dir):
if is_main_process():
logger = logging.getLogger(__name__)
ids_to_l... | try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
| try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
| 11 | 316 | 51 | 367 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import errno
import json
import logging
import os
from .comm import is_main_process
def mkdir(path):
FILL_FUNC_BODYdef save_labels(dataset_list, output_dir):
if is_main_process():
logger = logging.getLogger(__name__)
ids_to_l... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import errno
import json
import logging
import os
from .comm import is_main_process
def mkdir(path):
FILL_FUNC_BODYdef save_labels(dataset_list, output_dir):
if is_main_process():
logger = logging.getLogger(__name__)
ids_to_l... | |
13,836 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/model_zoo.py | 20,21 | 1,62 | cache_url | 21,62 | 21,62 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import sys
try:
from torch.hub import _download_url_to_file
from torch.hub import urlparse
from torch.hub import HASH_REGEX
except ImportError:
from torch.utils.model_zoo import _download_url_to_file
from torch.utils.... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import sys
try:
from torch.hub import _download_url_to_file
from torch.hub import urlparse
from torch.hub import HASH_REGEX
except ImportError:
from torch.utils.model_zoo import _download_url_to_file
from torch.utils.... | r"""Loads the Torch serialized object at the given URL.
If the object is already present in `model_dir`, it's deserialized and
returned. The filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
digits of the SHA256 hash ... | r"""Loads the Torch serialized object at the given URL.
If the object is already present in `model_dir`, it's deserialized and
returned. The filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
digits of the SHA256 hash ... | 260 | 238 | 757 | 995 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import sys
try:
from torch.hub import _download_url_to_file
from torch.hub import urlparse
from torch.hub import HASH_REGEX
except ImportError:
from torch.utils.model_zoo import _download_url_to_file
from torch.utils.... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import sys
try:
from torch.hub import _download_url_to_file
from torch.hub import urlparse
from torch.hub import HASH_REGEX
except ImportError:
from torch.utils.model_zoo import _download_url_to_file
from torch.utils.... | |
13,837 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/registry.py | 4,5 | 1,46 | _register_generic | 5,9 | 5,9 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
FILL_FUNC_BODYclass Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
and provides a register functions.
Eg. creeting a registry:... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
FILL_FUNC_BODYclass Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
and provides a register functions.
Eg. creeting a registry:... | assert module_name not in module_dict
module_dict[module_name] = module
| assert module_name not in module_dict
module_dict[module_name] = module
| 8 | 368 | 29 | 397 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
FILL_FUNC_BODYclass Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
and provides a register functions.
Eg. creeting a registry:... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
FILL_FUNC_BODYclass Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
and provides a register functions.
Eg. creeting a registry:... | |
13,838 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/registry.py | 34,35 | 9,46 | register | Registry | 35,46 | 35,46 | class Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
and provides a register functions.
Eg. creeting a registry:
some_registry = Registry({"default": default_module})
There're two ways of registering new modules:
1): normal way is just call... | class Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
and provides a register functions.
Eg. creeting a registry:
some_registry = Registry({"default": default_module})
There're two ways of registering new modules:
1): normal way is just call... | # used as function call
if module is not None:
_register_generic(self, module_name, module)
return
# used as decorator
def register_fn(fn):
_register_generic(self, module_name, fn)
return fn
return register_fn
| # used as function call
if module is not None:
_register_generic(self, module_name, module)
return
# used as decorator
def register_fn(fn):
_register_generic(self, module_name, fn)
return fn
return register_fn
| 27 | 253 | 87 | 340 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
assert module_name not in module_dict
module_dict[module_name] = module
class Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
assert module_name not in module_dict
module_dict[module_name] = module
class Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
... |
13,839 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/timer.py | 44,45 | 1,47 | get_time_str | 45,47 | 45,47 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... | time_str = str(datetime.timedelta(seconds=time_diff))
return time_str
| time_str = str(datetime.timedelta(seconds=time_diff))
return time_str
| 5 | 346 | 28 | 374 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... | |
13,840 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_maskrcnn-benchmark/maskrcnn-benchmark/maskrcnn_benchmark/utils/timer.py | 33,34 | 8,44 | reset | Timer | 34,39 | 34,39 | class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
... | class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
... | self.total_time = 0.0
self.calls = 0
self.start_time = 0.0
self.diff = 0.0
| self.total_time = 0.0
self.calls = 0
self.start_time = 0.0
self.diff = 0.0
| 12 | 264 | 45 | 309 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... |
16,235 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/common/confidence_test.py | 25,26 | 23,47 | test_pae_json | ConfidenceTest | 26,32 | 26,32 | class ConfidenceTest(absltest.TestCase):
def test_pae_json(self):
FILL_FUNC_BODY def test_confidence_json(self):
plddt = np.array([42, 42.42])
confidence_json = confidence.confidence_json(plddt=plddt)
print(confidence_json)
self.assertEqual(
confidence_json,
('{"residueNumber":[1,... | class ConfidenceTest(absltest.TestCase):
def test_pae_json(self):
FILL_FUNC_BODY def test_confidence_json(self):
plddt = np.array([42, 42.42])
confidence_json = confidence.confidence_json(plddt=plddt)
print(confidence_json)
self.assertEqual(
confidence_json,
('{"residueNumber":[1,... | pae = np.array([[0.01, 13.12345], [20.0987, 0.0]])
pae_json = confidence.pae_json(pae=pae, max_pae=31.75)
self.assertEqual(
pae_json, '[{"predicted_aligned_error":[[0.0,13.1],[20.1,0.0]],'
'"max_predicted_aligned_error":31.75}]')
| pae = np.array([[0.01, 13.12345], [20.0987, 0.0]])
pae_json = confidence.pae_json(pae=pae, max_pae=31.75)
self.assertEqual(
pae_json, '[{"predicted_aligned_error":[[0.0,13.1],[20.1,0.0]],'
'"max_predicted_aligned_error":31.75}]')
| 14 | 166 | 142 | 308 | # Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,238 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/common/protein_test.py | 139,140 | 29,152 | test_too_many_chains | ProteinTest | 140,152 | 140,152 | class ProteinTest(parameterized.TestCase):
def _check_shapes(self, prot, num_res):
"""Check that the processed shapes are correct."""
num_atoms = residue_constants.atom_type_num
self.assertEqual((num_res, num_atoms, 3), prot.atom_positions.shape)
self.assertEqual((num_res,), prot.aatype.shape)
se... | class ProteinTest(parameterized.TestCase):
def _check_shapes(self, prot, num_res):
"""Check that the processed shapes are correct."""
num_atoms = residue_constants.atom_type_num
self.assertEqual((num_res, num_atoms, 3), prot.atom_positions.shape)
self.assertEqual((num_res,), prot.aatype.shape)
se... | num_res = protein.PDB_MAX_CHAINS + 1
num_atom_type = residue_constants.atom_type_num
with self.assertRaises(ValueError):
_ = protein.Protein(
atom_positions=np.random.random([num_res, num_atom_type, 3]),
aatype=np.random.randint(0, 21, [num_res]),
atom_mask=np.random.rand... | num_res = protein.PDB_MAX_CHAINS + 1
num_atom_type = residue_constants.atom_type_num
with self.assertRaises(ValueError):
_ = protein.Protein(
atom_positions=np.random.random([num_res, num_atom_type, 3]),
aatype=np.random.randint(0, 21, [num_res]),
atom_mask=np.random.rand... | 28 | 1,669 | 217 | 1,886 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,242 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/msa_identifiers.py | 54,55 | 1,91 | _parse_sequence_identifier | 68,75 | 55,75 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | matches = re.search(_UNIPROT_PATTERN, msa_sequence_identifier.strip())
if matches:
return Identifiers(
species_id=matches.group('SpeciesIdentifier'))
return Identifiers()
| """Gets species from an msa sequence identifier.
The sequence identifier has the format specified by
_UNIPROT_TREMBL_ENTRY_NAME_PATTERN or _UNIPROT_SWISSPROT_ENTRY_NAME_PATTERN.
An example of a sequence identifier: `tr|A0A146SKV9|A0A146SKV9_FUNHE`
Args:
msa_sequence_identifier: a sequence identifier.
... | 11 | 931 | 67 | 998 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,245 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/parsers.py | 49,50 | 29,55 | truncate | Msa | 50,55 | 50,55 | @dataclasses.dataclass(frozen=True)
class Msa:
"""Class representing a parsed MSA file."""
sequences: Sequence[str]
deletion_matrix: DeletionMatrix
descriptions: Sequence[str]
def __post_init__(self):
if not (len(self.sequences) ==
len(self.deletion_matrix) ==
len(self.description... | @dataclasses.dataclass(frozen=True)
class Msa:
"""Class representing a parsed MSA file."""
sequences: Sequence[str]
deletion_matrix: DeletionMatrix
descriptions: Sequence[str]
def __post_init__(self):
if not (len(self.sequences) ==
len(self.deletion_matrix) ==
len(self.description... | return Msa(sequences=self.sequences[:max_seqs],
deletion_matrix=self.deletion_matrix[:max_seqs],
descriptions=self.descriptions[:max_seqs])
| return Msa(sequences=self.sequences[:max_seqs],
deletion_matrix=self.deletion_matrix[:max_seqs],
descriptions=self.descriptions[:max_seqs])
| 4 | 233 | 61 | 294 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,249 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/pipeline_multimer.py | 197,204 | 170,285 | _process_single_chain | DataPipeline | 205,224 | 204,224 | class DataPipeline:
"""Runs the alignment tools and assembles the input features."""
def __init__(self,
monomer_data_pipeline: pipeline.DataPipeline,
jackhmmer_binary_path: str,
uniprot_database_path: str,
max_uniprot_hits: int = 50000,
use... | class DataPipeline:
"""Runs the alignment tools and assembles the input features."""
def __init__(self,
monomer_data_pipeline: pipeline.DataPipeline,
jackhmmer_binary_path: str,
uniprot_database_path: str,
max_uniprot_hits: int = 50000,
use... | chain_fasta_str = f'>chain_{chain_id}\n{sequence}\n'
chain_msa_output_dir = os.path.join(msa_output_dir, chain_id)
if not os.path.exists(chain_msa_output_dir):
os.makedirs(chain_msa_output_dir)
with temp_fasta_file(chain_fasta_str) as chain_fasta_path:
logging.info('Running monomer pipeline ... | """Runs the monomer pipeline on a single chain."""
chain_fasta_str = f'>chain_{chain_id}\n{sequence}\n'
chain_msa_output_dir = os.path.join(msa_output_dir, chain_id)
if not os.path.exists(chain_msa_output_dir):
os.makedirs(chain_msa_output_dir)
with temp_fasta_file(chain_fasta_str) as chain_fa... | 55 | 1,368 | 313 | 1,681 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,251 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/templates.py | 874,878 | 871,933 | get_templates | HhsearchHitFeaturizer | 879,933 | 878,933 | class HhsearchHitFeaturizer(TemplateHitFeaturizer):
"""A class for turning a3m hits from hhsearch to template features."""
def get_templates(
self,
query_sequence: str,
hits: Sequence[parsers.TemplateHit]) -> TemplateSearchResult:
FILL_FUNC_BODY | class HhsearchHitFeaturizer(TemplateHitFeaturizer):
"""A class for turning a3m hits from hhsearch to template features."""
def get_templates(
self,
query_sequence: str,
hits: Sequence[parsers.TemplateHit]) -> TemplateSearchResult:
"""Computes the templates for given query sequence (more detai... | logging.info('Searching for template for: %s', query_sequence)
template_features = {}
for template_feature_name in TEMPLATE_FEATURES:
template_features[template_feature_name] = []
num_hits = 0
errors = []
warnings = []
for hit in sorted(hits, key=lambda x: x.sum_probs, reverse=True)... | """Computes the templates for given query sequence (more details above)."""
logging.info('Searching for template for: %s', query_sequence)
template_features = {}
for template_feature_name in TEMPLATE_FEATURES:
template_features[template_feature_name] = []
num_hits = 0
errors = []
war... | 161 | 103 | 627 | 730 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,252 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/templates.py | 936,940 | 933,1012 | get_templates | HmmsearchHitFeaturizer | 941,1012 | 940,1012 | class HmmsearchHitFeaturizer(TemplateHitFeaturizer):
"""A class for turning a3m hits from hmmsearch to template features."""
def get_templates(
self,
query_sequence: str,
hits: Sequence[parsers.TemplateHit]) -> TemplateSearchResult:
FILL_FUNC_BODY | class HmmsearchHitFeaturizer(TemplateHitFeaturizer):
"""A class for turning a3m hits from hmmsearch to template features."""
def get_templates(
self,
query_sequence: str,
hits: Sequence[parsers.TemplateHit]) -> TemplateSearchResult:
"""Computes the templates for given query sequence (more det... | logging.info('Searching for template for: %s', query_sequence)
template_features = {}
for template_feature_name in TEMPLATE_FEATURES:
template_features[template_feature_name] = []
already_seen = set()
errors = []
warnings = []
if not hits or hits[0].sum_probs is None:
sorted_h... | """Computes the templates for given query sequence (more details above)."""
logging.info('Searching for template for: %s', query_sequence)
template_features = {}
for template_feature_name in TEMPLATE_FEATURES:
template_features[template_feature_name] = []
already_seen = set()
errors = []... | 207 | 103 | 919 | 1,022 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,253 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/hhblits.py | 97,98 | 31,156 | query | HHBlits | 99,156 | 98,156 | class HHBlits:
"""Python wrapper of the HHblits binary."""
def __init__(self,
*,
binary_path: str,
databases: Sequence[str],
n_cpu: int = 4,
n_iter: int = 3,
e_value: float = 0.001,
maxseq: int = 1_000_000,
... | class HHBlits:
"""Python wrapper of the HHblits binary."""
def __init__(self,
*,
binary_path: str,
databases: Sequence[str],
n_cpu: int = 4,
n_iter: int = 3,
e_value: float = 0.001,
maxseq: int = 1_000_000,
... | with utils.tmpdir_manager() as query_tmp_dir:
a3m_path = os.path.join(query_tmp_dir, 'output.a3m')
db_cmd = []
for db_path in self.databases:
db_cmd.append('-d')
db_cmd.append(db_path)
cmd = [
self.binary_path,
'-i', input_fasta_path,
'-cpu', st... | """Queries the database using HHblits."""
with utils.tmpdir_manager() as query_tmp_dir:
a3m_path = os.path.join(query_tmp_dir, 'output.a3m')
db_cmd = []
for db_path in self.databases:
db_cmd.append('-d')
db_cmd.append(db_path)
cmd = [
self.binary_path,
... | 147 | 895 | 762 | 1,657 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,254 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/hhsearch.py | 67,68 | 29,108 | query | HHSearch | 69,102 | 68,102 | class HHSearch:
"""Python wrapper of the HHsearch binary."""
def __init__(self,
*,
binary_path: str,
databases: Sequence[str],
maxseq: int = 1_000_000):
"""Initializes the Python HHsearch wrapper.
Args:
binary_path: The path to the HHsearch... | class HHSearch:
"""Python wrapper of the HHsearch binary."""
def __init__(self,
*,
binary_path: str,
databases: Sequence[str],
maxseq: int = 1_000_000):
"""Initializes the Python HHsearch wrapper.
Args:
binary_path: The path to the HHsearch... | with utils.tmpdir_manager() as query_tmp_dir:
input_path = os.path.join(query_tmp_dir, 'query.a3m')
hhr_path = os.path.join(query_tmp_dir, 'output.hhr')
with open(input_path, 'w') as f:
f.write(a3m)
db_cmd = []
for db_path in self.databases:
db_cmd.append('-d')
... | """Queries the database using HHsearch using a given a3m."""
with utils.tmpdir_manager() as query_tmp_dir:
input_path = os.path.join(query_tmp_dir, 'query.a3m')
hhr_path = os.path.join(query_tmp_dir, 'output.hhr')
with open(input_path, 'w') as f:
f.write(a3m)
db_cmd = []
f... | 90 | 495 | 426 | 921 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,255 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/hmmbuild.py | 82,83 | 26,139 | _build_profile | Hmmbuild | 97,139 | 83,139 | class Hmmbuild(object):
"""Python wrapper of the hmmbuild binary."""
def __init__(self,
*,
binary_path: str,
singlemx: bool = False):
"""Initializes the Python hmmbuild wrapper.
Args:
binary_path: The path to the hmmbuild executable.
singlemx: Wheth... | class Hmmbuild(object):
"""Python wrapper of the hmmbuild binary."""
def __init__(self,
*,
binary_path: str,
singlemx: bool = False):
"""Initializes the Python hmmbuild wrapper.
Args:
binary_path: The path to the hmmbuild executable.
singlemx: Wheth... | if model_construction not in {'hand', 'fast'}:
raise ValueError(f'Invalid model_construction {model_construction} - only'
'hand and fast supported.')
with utils.tmpdir_manager() as query_tmp_dir:
input_query = os.path.join(query_tmp_dir, 'query.msa')
output_hmm_path = o... | """Builds a HMM for the aligned sequences given as an MSA string.
Args:
msa: A string with the aligned sequences, in A3M or STO format.
model_construction: Whether to use reference annotation in the msa to
determine consensus columns ('hand') or default ('fast').
Returns:
A strin... | 105 | 719 | 534 | 1,253 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,256 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/hmmsearch.py | 121,124 | 28,132 | get_template_hits | Hmmsearch | 125,132 | 124,132 | class Hmmsearch(object):
"""Python wrapper of the hmmsearch binary."""
def __init__(self,
*,
binary_path: str,
hmmbuild_binary_path: str,
database_path: str,
flags: Optional[Sequence[str]] = None):
"""Initializes the Python hmmsearch wr... | class Hmmsearch(object):
"""Python wrapper of the hmmsearch binary."""
def __init__(self,
*,
binary_path: str,
hmmbuild_binary_path: str,
database_path: str,
flags: Optional[Sequence[str]] = None):
"""Initializes the Python hmmsearch wr... | a3m_string = parsers.convert_stockholm_to_a3m(output_string,
remove_first_row_gaps=False)
template_hits = parsers.parse_hmmsearch_a3m(
query_sequence=input_sequence,
a3m_string=a3m_string,
skip_first=False)
return template_hits
| """Gets parsed template hits from the raw string output by the tool."""
a3m_string = parsers.convert_stockholm_to_a3m(output_string,
remove_first_row_gaps=False)
template_hits = parsers.parse_hmmsearch_a3m(
query_sequence=input_sequence,
a3m_... | 12 | 1,095 | 109 | 1,204 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,257 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/kalign.py | 26,27 | 1,105 | _to_a3m | 28,36 | 27,36 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | names = ['sequence %d' % i for i in range(1, len(sequences) + 1)]
a3m = []
for sequence, name in zip(sequences, names):
a3m.append(u'>' + name + u'\n')
a3m.append(sequence + u'\n')
return ''.join(a3m)
| """Converts sequences to an a3m file."""
names = ['sequence %d' % i for i in range(1, len(sequences) + 1)]
a3m = []
for sequence, name in zip(sequences, names):
a3m.append(u'>' + name + u'\n')
a3m.append(sequence + u'\n')
return ''.join(a3m)
| 32 | 983 | 101 | 1,084 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,258 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/kalign.py | 50,51 | 36,105 | align | Kalign | 66,105 | 51,105 | class Kalign:
"""Python wrapper of the Kalign binary."""
def __init__(self, *, binary_path: str):
"""Initializes the Python Kalign wrapper.
Args:
binary_path: The path to the Kalign binary.
Raises:
RuntimeError: If Kalign binary not found within the path.
"""
self.binary_path = bi... | class Kalign:
"""Python wrapper of the Kalign binary."""
def __init__(self, *, binary_path: str):
"""Initializes the Python Kalign wrapper.
Args:
binary_path: The path to the Kalign binary.
Raises:
RuntimeError: If Kalign binary not found within the path.
"""
self.binary_path = bi... | logging.info('Aligning %d sequences', len(sequences))
for s in sequences:
if len(s) < 6:
raise ValueError('Kalign requires all sequences to be at least 6 '
'residues long. Got %s (%d residues).' % (s, len(s)))
with utils.tmpdir_manager() as query_tmp_dir:
input... | """Aligns the sequences and returns the alignment in A3M string.
Args:
sequences: A list of query sequence strings. The sequences have to be at
least 6 residues long (Kalign requires this). Note that the order in
which you give the sequences might alter the output slightly as
diff... | 102 | 266 | 511 | 777 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,259 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/data/tools/utils.py | 34,36 | 1,41 | timing | 36,41 | 36,41 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | logging.info('Started %s', msg)
tic = time.time()
yield
toc = time.time()
logging.info('Finished %s in %.3f seconds', msg, toc - tic)
| logging.info('Started %s', msg)
tic = time.time()
yield
toc = time.time()
logging.info('Finished %s in %.3f seconds', msg, toc - tic)
| 19 | 309 | 64 | 373 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,262 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/all_atom_test.py | 26,27 | 1,136 | get_identity_rigid | 28,38 | 27,38 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
ones = np.ones(shape)
zeros = np.zeros(shape)
rot = r3.Rots(ones, zeros, zeros,
zeros, ones, zeros,
zeros, zeros, ones)
trans = r3.Vecs(zeros, zeros, zeros)
return r3.Rigids(rot, trans)
| """Returns identity rigid transform."""
ones = np.ones(shape)
zeros = np.zeros(shape)
rot = r3.Rots(ones, zeros, zeros,
zeros, ones, zeros,
zeros, zeros, ones)
trans = r3.Vecs(zeros, zeros, zeros)
return r3.Rigids(rot, trans)
| 25 | 1,790 | 107 | 1,897 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,263 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/all_atom_test.py | 98,117 | 58,134 | test_frame_aligned_point_error_matches_expected | AllAtomTest | 118,134 | 117,134 | class AllAtomTest(parameterized.TestCase, absltest.TestCase):
@parameterized.named_parameters(
('identity', 0, [0, 0, 0]),
('rot_90', 90, [0, 0, 0]),
('trans_10', 0, [0, 0, 10]),
('rot_174_trans_1', 174, [1, 1, 1]))
def test_frame_aligned_point_error_perfect_on_global_transform(
self,... | class AllAtomTest(parameterized.TestCase, absltest.TestCase):
@parameterized.named_parameters(
('identity', 0, [0, 0, 0]),
('rot_90', 90, [0, 0, 0]),
('trans_10', 0, [0, 0, 10]),
('rot_174_trans_1', 174, [1, 1, 1]))
def test_frame_aligned_point_error_perfect_on_global_transform(
self,... |
target_frames = get_identity_rigid(2)
pred_frames = target_frames
frames_mask = np.ones(2)
target_positions = r3.vecs_from_tensor(np.array(target_positions))
pred_positions = r3.vecs_from_tensor(np.array(pred_positions))
positions_mask = np.ones(target_positions.x.shape[0])
alddt = all_at... | """Tests score matches expected."""
target_frames = get_identity_rigid(2)
pred_frames = target_frames
frames_mask = np.ones(2)
target_positions = r3.vecs_from_tensor(np.array(target_positions))
pred_positions = r3.vecs_from_tensor(np.array(pred_positions))
positions_mask = np.ones(target_p... | 32 | 1,036 | 217 | 1,253 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,264 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/common_modules.py | 29,30 | 1,192 | get_initializer_scale | 31,52 | 30,52 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
if initializer_name == 'zeros':
w_init = hk.initializers.Constant(0.0)
else:
# fan-in scaling
scale = 1.
for channel_dim in input_shape:
scale /= channel_dim
if initializer_name == 'relu':
scale *= 2
noise_scale = scale
stddev = np.sqrt(noise_scale)
# Adjust stddev for... | """Get Initializer for weights and scale to multiply activations by."""
if initializer_name == 'zeros':
w_init = hk.initializers.Constant(0.0)
else:
# fan-in scaling
scale = 1.
for channel_dim in input_shape:
scale /= channel_dim
if initializer_name == 'relu':
scale *= 2
nois... | 50 | 1,740 | 202 | 1,942 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,266 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/data.py | 25,26 | 1,34 | get_model_haiku_params | 27,34 | 26,34 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
path = os.path.join(data_dir, 'params', f'params_{model_name}.npz')
with open(path, 'rb') as f:
params = np.load(io.BytesIO(f.read()), allow_pickle=False)
return utils.flat_params_to_haiku(params)
| """Get the Haiku parameters from a model name."""
path = os.path.join(data_dir, 'params', f'params_{model_name}.npz')
with open(path, 'rb') as f:
params = np.load(io.BytesIO(f.read()), allow_pickle=False)
return utils.flat_params_to_haiku(params)
| 16 | 264 | 94 | 358 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,267 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/geometry/rigid_matrix_vector.py | 74,75 | 30,107 | to_array | Rigid3Array | 75,79 | 75,79 | @struct_of_array.StructOfArray(same_dtype=True)
class Rigid3Array:
"""Rigid Transformation, i.e. element of special euclidean group."""
rotation: rotation_matrix.Rot3Array
translation: vector.Vec3Array
def __matmul__(self, other: Rigid3Array) -> Rigid3Array:
new_rotation = self.rotation @ other.rotation
... | @struct_of_array.StructOfArray(same_dtype=True)
class Rigid3Array:
"""Rigid Transformation, i.e. element of special euclidean group."""
rotation: rotation_matrix.Rot3Array
translation: vector.Vec3Array
def __matmul__(self, other: Rigid3Array) -> Rigid3Array:
new_rotation = self.rotation @ other.rotation
... | rot_array = self.rotation.to_array()
vec_array = self.translation.to_array()
return jnp.concatenate([rot_array, vec_array[..., None]], axis=-1)
| rot_array = self.rotation.to_array()
vec_array = self.translation.to_array()
return jnp.concatenate([rot_array, vec_array[..., None]], axis=-1)
| 11 | 1,077 | 64 | 1,141 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,269 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/geometry/struct_of_array.py | 201,202 | 181,221 | unflatten | StructOfArray | 202,218 | 202,218 | class StructOfArray:
"""Class Decorator for Struct Of Arrays."""
def __init__(self, same_dtype=True):
self.same_dtype = same_dtype
def __call__(self, cls):
cls.__array_ufunc__ = None
cls.replace = replace
cls.same_dtype = self.same_dtype
cls.dtype = get_dtype
cls.shape = get_shape
cl... | class StructOfArray:
"""Class Decorator for Struct Of Arrays."""
def __init__(self, same_dtype=True):
self.same_dtype = same_dtype
def __call__(self, cls):
cls.__array_ufunc__ = None
cls.replace = replace
cls.same_dtype = self.same_dtype
cls.dtype = get_dtype
cls.shape = get_shape
cl... | inner_treedefs, metadata, num_arrays = aux
array_fields = [field.name for field in get_array_fields(new_cls)]
value_dict = {}
array_start = 0
for num_array, inner_treedef, array_field in zip(num_arrays,
inner_treedefs,
... | inner_treedefs, metadata, num_arrays = aux
array_fields = [field.name for field in get_array_fields(new_cls)]
value_dict = {}
array_start = 0
for num_array, inner_treedef, array_field in zip(num_arrays,
inner_treedefs,
... | 49 | 315 | 225 | 540 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,270 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/geometry/test_utils.py | 25,27 | 1,99 | assert_rotation_matrix_equal | 27,33 | 27,33 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | for field in dataclasses.fields(rotation_matrix.Rot3Array):
field = field.name
np.testing.assert_array_equal(
getattr(matrix1, field), getattr(matrix2, field))
| for field in dataclasses.fields(rotation_matrix.Rot3Array):
field = field.name
np.testing.assert_array_equal(
getattr(matrix1, field), getattr(matrix2, field))
| 12 | 1,375 | 66 | 1,441 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,271 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/geometry/utils.py | 21,22 | 1,24 | unstack | 22,24 | 22,24 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | return [jnp.squeeze(v, axis=axis)
for v in jnp.split(value, value.shape[axis], axis=axis)]
| return [jnp.squeeze(v, axis=axis)
for v in jnp.split(value, value.shape[axis], axis=axis)]
| 9 | 223 | 41 | 264 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,273 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/layer_stack.py | 100,101 | 66,167 | getter | _LayerStack | 101,106 | 101,106 | class _LayerStack(hk.Module):
"""Module to compose parameterized functions, implemented as a scan."""
def __init__(self,
count: int,
unroll: int,
name: Optional[str] = None):
"""Iterate a function `f` `count` times, with non-shared parameters."""
super().__init_... | class _LayerStack(hk.Module):
"""Module to compose parameterized functions, implemented as a scan."""
def __init__(self,
count: int,
unroll: int,
name: Optional[str] = None):
"""Iterate a function `f` `count` times, with non-shared parameters."""
super().__init_... | trailing_dims = len(context.original_shape) + 1
sliced_value = jax.lax.index_in_dim(
value, index=0, axis=value.ndim - trailing_dims, keepdims=False)
return next_getter(sliced_value)
| trailing_dims = len(context.original_shape) + 1
sliced_value = jax.lax.index_in_dim(
value, index=0, axis=value.ndim - trailing_dims, keepdims=False)
return next_getter(sliced_value)
| 16 | 1,171 | 84 | 1,255 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,274 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/layer_stack.py | 179,181 | 167,190 | _call_wrapped | _LayerStackNoState | 181,190 | 181,190 | class _LayerStackNoState(_LayerStack):
"""_LayerStack impl with no per-layer state provided to the function."""
def __init__(self,
f: WrappedFn,
count: int,
unroll: int,
name: Optional[str] = None):
super().__init__(count=count, unroll=unroll, name=na... | class _LayerStackNoState(_LayerStack):
"""_LayerStack impl with no per-layer state provided to the function."""
def __init__(self,
f: WrappedFn,
count: int,
unroll: int,
name: Optional[str] = None):
super().__init__(count=count, unroll=unroll, name=na... | del y
ret = self._f(*args)
if len(args) == 1:
# If the function takes a single argument, the wrapped function receives
# a tuple of length 1, and therefore it must return a tuple of length 1.
ret = (ret,)
return ret, None
| del y
ret = self._f(*args)
if len(args) == 1:
# If the function takes a single argument, the wrapped function receives
# a tuple of length 1, and therefore it must return a tuple of length 1.
ret = (ret,)
return ret, None
| 43 | 144 | 85 | 229 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,275 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/layer_stack.py | 201,203 | 190,206 | _call_wrapped | _LayerStackWithState | 203,206 | 203,206 | class _LayerStackWithState(_LayerStack):
"""_LayerStack impl with per-layer state provided to the function."""
def __init__(self,
f: WrappedFn,
count: int,
unroll: int,
name: Optional[str] = None):
super().__init__(count=count, unroll=unroll, name=nam... | class _LayerStackWithState(_LayerStack):
"""_LayerStack impl with per-layer state provided to the function."""
def __init__(self,
f: WrappedFn,
count: int,
unroll: int,
name: Optional[str] = None):
super().__init__(count=count, unroll=unroll, name=nam... | return self._f(x, *args)
| return self._f(x, *args)
| 3 | 132 | 17 | 149 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,276 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/lddt.py | 19,24 | 1,89 | lddt | 53,89 | 24,89 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
assert len(predicted_points.shape) == 3
assert predicted_points.shape[-1] == 3
assert true_points_mask.shape[-1] == 1
assert len(true_points_mask.shape) == 3
# Compute true and predicted distance matrices.
dmat_true = jnp.sqrt(1e-10 + jnp.sum(
(true_points[:, :, None] - true_points[:, None, :])**2, ... | """Measure (approximate) lDDT for a batch of coordinates.
lDDT reference:
Mariani, V., Biasini, M., Barbato, A. & Schwede, T. lDDT: A local
superposition-free score for comparing protein structures and models using
distance difference tests. Bioinformatics 29, 2722–2728 (2013).
lDDT is a measure of the di... | 155 | 628 | 591 | 1,219 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,277 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/lddt_test.py | 25,65 | 23,78 | test_lddt | LddtTest | 65,78 | 65,78 | class LddtTest(parameterized.TestCase, absltest.TestCase):
@parameterized.named_parameters(
('same',
[[0, 0, 0], [5, 0, 0], [10, 0, 0]],
[[0, 0, 0], [5, 0, 0], [10, 0, 0]],
[1, 1, 1]),
('all_shifted',
[[0, 0, 0], [5, 0, 0], [10, 0, 0]],
[[-1, 0, 0], [4, 0, 0], [9, 0, 0]... | class LddtTest(parameterized.TestCase, absltest.TestCase):
@parameterized.named_parameters(
('same',
[[0, 0, 0], [5, 0, 0], [10, 0, 0]],
[[0, 0, 0], [5, 0, 0], [10, 0, 0]],
[1, 1, 1]),
('all_shifted',
[[0, 0, 0], [5, 0, 0], [10, 0, 0]],
[[-1, 0, 0], [4, 0, 0], [9, 0, 0]... | predicted_pos = np.array([predicted_pos], dtype=np.float32)
true_points_mask = np.array([[[1]] * len(true_pos)], dtype=np.float32)
true_pos = np.array([true_pos], dtype=np.float32)
cutoff = 15.0
per_residue = True
result = lddt.lddt(
predicted_pos, true_pos, true_points_mask, cutoff,
... | predicted_pos = np.array([predicted_pos], dtype=np.float32)
true_points_mask = np.array([[[1]] * len(true_pos)], dtype=np.float32)
true_pos = np.array([true_pos], dtype=np.float32)
cutoff = 15.0
per_residue = True
result = lddt.lddt(
predicted_pos, true_pos, true_points_mask, cutoff,
... | 31 | 721 | 176 | 897 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,279 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 327,330 | 276,399 | do_call | AlphaFold | 330,350 | 330,350 | class AlphaFold(hk.Module):
"""AlphaFold model with recycling.
Jumper et al. (2021) Suppl. Alg. 2 "Inference"
"""
def __init__(self, config, name='alphafold'):
super().__init__(name=name)
self.config = config
self.global_config = config.global_config
def __call__(
self,
batch,
... | class AlphaFold(hk.Module):
"""AlphaFold model with recycling.
Jumper et al. (2021) Suppl. Alg. 2 "Inference"
"""
def __init__(self, config, name='alphafold'):
super().__init__(name=name)
self.config = config
self.global_config = config.global_config
def __call__(
self,
batch,
... | if self.config.resample_msa_in_recycling:
num_ensemble = batch_size // (self.config.num_recycle + 1)
def slice_recycle_idx(x):
start = recycle_idx * num_ensemble
size = num_ensemble
return jax.lax.dynamic_slice_in_dim(x, start, size, axis=0)
ensembled_batch = ... | if self.config.resample_msa_in_recycling:
num_ensemble = batch_size // (self.config.num_recycle + 1)
def slice_recycle_idx(x):
start = recycle_idx * num_ensemble
size = num_ensemble
return jax.lax.dynamic_slice_in_dim(x, start, size, axis=0)
ensembled_batch = ... | 48 | 1,112 | 268 | 1,380 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,280 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 227,228 | 129,276 | loss | AlphaFoldIteration | 228,237 | 228,237 | class AlphaFoldIteration(hk.Module):
"""A single recycling iteration of AlphaFold architecture.
Computes ensembled (averaged) representations from the provided features.
These representations are then passed to the various heads
that have been requested by the configuration file. Each head also returns a
los... | class AlphaFoldIteration(hk.Module):
"""A single recycling iteration of AlphaFold architecture.
Computes ensembled (averaged) representations from the provided features.
These representations are then passed to the various heads
that have been requested by the configuration file. Each head also returns a
los... | if filter_ret:
value = ret[name]
else:
value = ret
loss_output = module.loss(value, batch)
ret[name].update(loss_output)
loss = head_config.weight * ret[name]['loss']
return loss
| if filter_ret:
value = ret[name]
else:
value = ret
loss_output = module.loss(value, batch)
ret[name].update(loss_output)
loss = head_config.weight * ret[name]['loss']
return loss
| 21 | 1,529 | 81 | 1,610 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,281 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1470,1471 | 1433,1475 | loss | DistogramHead | 1471,1475 | 1471,1475 | class DistogramHead(hk.Module):
"""Head to predict a distogram.
Jumper et al. (2021) Suppl. Sec. 1.9.8 "Distogram prediction"
"""
def __init__(self, config, global_config, name='distogram_head'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call__(se... | class DistogramHead(hk.Module):
"""Head to predict a distogram.
Jumper et al. (2021) Suppl. Sec. 1.9.8 "Distogram prediction"
"""
def __init__(self, config, global_config, name='distogram_head'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call__(se... | return _distogram_log_loss(value['logits'], value['bin_edges'],
batch, self.config.num_bins)
| return _distogram_log_loss(value['logits'], value['bin_edges'],
batch, self.config.num_bins)
| 5 | 430 | 42 | 472 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,283 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1254,1255 | 1220,1277 | loss | ExperimentallyResolvedHead | 1255,1277 | 1255,1277 | class ExperimentallyResolvedHead(hk.Module):
"""Predicts if an atom is experimentally resolved in a high-res structure.
Only trained on high-resolution X-ray crystals & cryo-EM.
Jumper et al. (2021) Suppl. Sec. 1.9.10 '"Experimentally resolved" prediction'
"""
def __init__(self, config, global_config,
... | class ExperimentallyResolvedHead(hk.Module):
"""Predicts if an atom is experimentally resolved in a high-res structure.
Only trained on high-resolution X-ray crystals & cryo-EM.
Jumper et al. (2021) Suppl. Sec. 1.9.10 '"Experimentally resolved" prediction'
"""
def __init__(self, config, global_config,
... | logits = value['logits']
assert len(logits.shape) == 2
# Does the atom appear in the amino acid?
atom_exists = batch['atom37_atom_exists']
# Is the atom resolved in the experiment? Subset of atom_exists,
# *except for OXT*
all_atom_mask = batch['all_atom_mask'].astype(jnp.float32)
xent... | logits = value['logits']
assert len(logits.shape) == 2
# Does the atom appear in the amino acid?
atom_exists = batch['atom37_atom_exists']
# Is the atom resolved in the experiment? Subset of atom_exists,
# *except for OXT*
all_atom_mask = batch['all_atom_mask'].astype(jnp.float32)
xent... | 77 | 388 | 281 | 669 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,284 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1017,1018 | 976,1026 | loss | MaskedMsaHead | 1018,1026 | 1018,1026 | class MaskedMsaHead(hk.Module):
"""Head to predict MSA at the masked locations.
The MaskedMsaHead employs a BERT-style objective to reconstruct a masked
version of the full MSA, based on a linear projection of
the MSA representation.
Jumper et al. (2021) Suppl. Sec. 1.9.9 "Masked MSA prediction"
"""
def... | class MaskedMsaHead(hk.Module):
"""Head to predict MSA at the masked locations.
The MaskedMsaHead employs a BERT-style objective to reconstruct a masked
version of the full MSA, based on a linear projection of
the MSA representation.
Jumper et al. (2021) Suppl. Sec. 1.9.9 "Masked MSA prediction"
"""
def... | errors = softmax_cross_entropy(
labels=jax.nn.one_hot(batch['true_msa'], num_classes=self.num_output),
logits=value['logits'])
loss = (jnp.sum(errors * batch['bert_mask'], axis=(-2, -1)) /
(1e-8 + jnp.sum(batch['bert_mask'], axis=(-2, -1))))
return {'loss': loss}
| errors = softmax_cross_entropy(
labels=jax.nn.one_hot(batch['true_msa'], num_classes=self.num_output),
logits=value['logits'])
loss = (jnp.sum(errors * batch['bert_mask'], axis=(-2, -1)) /
(1e-8 + jnp.sum(batch['bert_mask'], axis=(-2, -1))))
return {'loss': loss}
| 22 | 465 | 125 | 590 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,285 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1568,1569 | 1507,1596 | compute_chunk | OuterProductMean | 1569,1580 | 1569,1580 | class OuterProductMean(hk.Module):
"""Computes mean outer product.
Jumper et al. (2021) Suppl. Alg. 10 "OuterProductMean"
"""
def __init__(self,
config,
global_config,
num_output_channel,
name='outer_product_mean'):
super().__init__(name=name)
... | class OuterProductMean(hk.Module):
"""Computes mean outer product.
Jumper et al. (2021) Suppl. Alg. 10 "OuterProductMean"
"""
def __init__(self,
config,
global_config,
num_output_channel,
name='outer_product_mean'):
super().__init__(name=name)
... | # This is equivalent to
#
# act = jnp.einsum('abc,ade->dceb', left_act, right_act)
# act = jnp.einsum('dceb,cef->bdf', act, output_w) + output_b
#
# but faster.
left_act = jnp.transpose(left_act, [0, 2, 1])
act = jnp.einsum('acb,ade->dceb', left_act, right_act)
act ... | # This is equivalent to
#
# act = jnp.einsum('abc,ade->dceb', left_act, right_act)
# act = jnp.einsum('dceb,cef->bdf', act, output_w) + output_b
#
# but faster.
left_act = jnp.transpose(left_act, [0, 2, 1])
act = jnp.einsum('acb,ade->dceb', left_act, right_act)
act ... | 47 | 753 | 199 | 952 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,286 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1170,1171 | 1130,1220 | loss | PredictedAlignedErrorHead | 1171,1220 | 1171,1220 | class PredictedAlignedErrorHead(hk.Module):
"""Head to predict the distance errors in the backbone alignment frames.
Can be used to compute predicted TM-Score.
Jumper et al. (2021) Suppl. Sec. 1.9.7 "TM-score prediction"
"""
def __init__(self, config, global_config,
name='predicted_aligned_er... | class PredictedAlignedErrorHead(hk.Module):
"""Head to predict the distance errors in the backbone alignment frames.
Can be used to compute predicted TM-Score.
Jumper et al. (2021) Suppl. Sec. 1.9.7 "TM-score prediction"
"""
def __init__(self, config, global_config,
name='predicted_aligned_er... | # Shape (num_res, 7)
predicted_affine = quat_affine.QuatAffine.from_tensor(
value['structure_module']['final_affines'])
# Shape (num_res, 7)
true_affine = quat_affine.QuatAffine.from_tensor(
batch['backbone_affine_tensor'])
# Shape (num_res)
mask = batch['backbone_affine_mask']
... | # Shape (num_res, 7)
predicted_affine = quat_affine.QuatAffine.from_tensor(
value['structure_module']['final_affines'])
# Shape (num_res, 7)
true_affine = quat_affine.QuatAffine.from_tensor(
batch['backbone_affine_tensor'])
# Shape (num_res)
mask = batch['backbone_affine_mask']
... | 161 | 456 | 731 | 1,187 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,287 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1084,1085 | 1026,1130 | loss | PredictedLDDTHead | 1085,1130 | 1085,1130 | class PredictedLDDTHead(hk.Module):
"""Head to predict the per-residue LDDT to be used as a confidence measure.
Jumper et al. (2021) Suppl. Sec. 1.9.6 "Model confidence prediction (pLDDT)"
Jumper et al. (2021) Suppl. Alg. 29 "predictPerResidueLDDT_Ca"
"""
def __init__(self, config, global_config, name='pred... | class PredictedLDDTHead(hk.Module):
"""Head to predict the per-residue LDDT to be used as a confidence measure.
Jumper et al. (2021) Suppl. Sec. 1.9.6 "Model confidence prediction (pLDDT)"
Jumper et al. (2021) Suppl. Alg. 29 "predictPerResidueLDDT_Ca"
"""
def __init__(self, config, global_config, name='pred... | # Shape (num_res, 37, 3)
pred_all_atom_pos = value['structure_module']['final_atom_positions']
# Shape (num_res, 37, 3)
true_all_atom_pos = batch['all_atom_positions']
# Shape (num_res, 37)
all_atom_mask = batch['all_atom_mask']
# Shape (num_res,)
lddt_ca = lddt.lddt(
# Shape (b... | # Shape (num_res, 37, 3)
pred_all_atom_pos = value['structure_module']['final_atom_positions']
# Shape (num_res, 37, 3)
true_all_atom_pos = batch['all_atom_positions']
# Shape (num_res, 37)
all_atom_mask = batch['all_atom_mask']
# Shape (num_res,)
lddt_ca = lddt.lddt(
# Shape (b... | 144 | 599 | 707 | 1,306 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,288 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 2160,2161 | 2118,2196 | map_fn | TemplateEmbedding | 2161,2163 | 2161,2163 | class TemplateEmbedding(hk.Module):
"""Embeds a set of templates.
Jumper et al. (2021) Suppl. Alg. 2 "Inference" lines 9-12
Jumper et al. (2021) Suppl. Alg. 17 "TemplatePointwiseAttention"
"""
def __init__(self, config, global_config, name='template_embedding'):
super().__init__(name=name)
self.conf... | class TemplateEmbedding(hk.Module):
"""Embeds a set of templates.
Jumper et al. (2021) Suppl. Alg. 2 "Inference" lines 9-12
Jumper et al. (2021) Suppl. Alg. 17 "TemplatePointwiseAttention"
"""
def __init__(self, config, global_config, name='template_embedding'):
super().__init__(name=name)
self.conf... | return template_embedder(query_embedding, batch, mask_2d, is_training)
| return template_embedder(query_embedding, batch, mask_2d, is_training)
| 5 | 942 | 27 | 969 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,289 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 432,433 | 399,482 | block | TemplatePairStack | 434,474 | 433,474 | class TemplatePairStack(hk.Module):
"""Pair stack for the templates.
Jumper et al. (2021) Suppl. Alg. 16 "TemplatePairStack"
"""
def __init__(self, config, global_config, name='template_pair_stack'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call_... | class TemplatePairStack(hk.Module):
"""Pair stack for the templates.
Jumper et al. (2021) Suppl. Alg. 16 "TemplatePairStack"
"""
def __init__(self, config, global_config, name='template_pair_stack'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call_... | pair_act, safe_key = x
dropout_wrapper_fn = functools.partial(
dropout_wrapper, is_training=is_training, global_config=gc)
safe_key, *sub_keys = safe_key.split(6)
sub_keys = iter(sub_keys)
pair_act = dropout_wrapper_fn(
TriangleAttention(c.triangle_attention_starting... | """One block of the template pair stack."""
pair_act, safe_key = x
dropout_wrapper_fn = functools.partial(
dropout_wrapper, is_training=is_training, global_config=gc)
safe_key, *sub_keys = safe_key.split(6)
sub_keys = iter(sub_keys)
pair_act = dropout_wrapper_fn(
... | 65 | 429 | 454 | 883 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,290 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules.py | 1388,1390 | 1290,1433 | _fused_triangle_multiplication | TriangleMultiplication | 1391,1433 | 1390,1433 | class TriangleMultiplication(hk.Module):
"""Triangle multiplication layer ("outgoing" or "incoming").
Jumper et al. (2021) Suppl. Alg. 11 "TriangleMultiplicationOutgoing"
Jumper et al. (2021) Suppl. Alg. 12 "TriangleMultiplicationIncoming"
"""
def __init__(self, config, global_config, name='triangle_multipl... | class TriangleMultiplication(hk.Module):
"""Triangle multiplication layer ("outgoing" or "incoming").
Jumper et al. (2021) Suppl. Alg. 11 "TriangleMultiplicationOutgoing"
Jumper et al. (2021) Suppl. Alg. 12 "TriangleMultiplicationIncoming"
"""
def __init__(self, config, global_config, name='triangle_multipl... | mask = left_mask[..., None]
c = self.config
gc = self.global_config
left_act = _layer_norm(axis=-1, name='left_norm_input')(left_act)
# Both left and right projections are fused into projection.
projection = common_modules.Linear(
2*c.num_intermediate_channel, name='projection')
pr... | """TriangleMultiplication with fused projection weights."""
mask = left_mask[..., None]
c = self.config
gc = self.global_config
left_act = _layer_norm(axis=-1, name='left_norm_input')(left_act)
# Both left and right projections are fused into projection.
projection = common_modules.Linear(... | 96 | 1,131 | 505 | 1,636 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,292 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules_multimer.py | 483,484 | 411,526 | recycle_body | AlphaFold | 484,489 | 484,489 | class AlphaFold(hk.Module):
"""AlphaFold-Multimer model with recycling.
"""
def __init__(self, config, name='alphafold'):
super().__init__(name=name)
self.config = config
self.global_config = config.global_config
def __call__(
self,
batch,
is_training,
return_representation... | class AlphaFold(hk.Module):
"""AlphaFold-Multimer model with recycling.
"""
def __init__(self, config, name='alphafold'):
super().__init__(name=name)
self.config = config
self.global_config = config.global_config
def __call__(
self,
batch,
is_training,
return_representation... | i, _, prev, safe_key = x
safe_key1, safe_key2 = safe_key.split() if c.resample_msa_in_recycling else safe_key.duplicate() # pylint: disable=line-too-long
ret = apply_network(prev=prev, safe_key=safe_key2)
return i+1, prev, get_prev(ret), safe_key1
| i, _, prev, safe_key = x
safe_key1, safe_key2 = safe_key.split() if c.resample_msa_in_recycling else safe_key.duplicate() # pylint: disable=line-too-long
ret = apply_network(prev=prev, safe_key=safe_key2)
return i+1, prev, get_prev(ret), safe_key1
| 26 | 1,279 | 111 | 1,390 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,293 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules_multimer.py | 327,328 | 294,411 | ensemble_body | AlphaFoldIteration | 329,344 | 328,344 | class AlphaFoldIteration(hk.Module):
"""A single recycling iteration of AlphaFold architecture.
Computes ensembled (averaged) representations from the provided features.
These representations are then passed to the various heads
that have been requested by the configuration file.
"""
def __init__(self, co... | class AlphaFoldIteration(hk.Module):
"""A single recycling iteration of AlphaFold architecture.
Computes ensembled (averaged) representations from the provided features.
These representations are then passed to the various heads
that have been requested by the configuration file.
"""
def __init__(self, co... | del unused_y
representations, safe_key = x
safe_key, safe_subkey = safe_key.split()
representations_update = embedding_module(
batch, is_training, safe_key=safe_subkey)
for k in representations:
if k not in {'msa', 'true_msa', 'bert_mask'}:
representations[k] +... | """Add into representations ensemble."""
del unused_y
representations, safe_key = x
safe_key, safe_subkey = safe_key.split()
representations_update = embedding_module(
batch, is_training, safe_key=safe_subkey)
for k in representations:
if k not in {'msa', 'true_msa... | 43 | 1,127 | 172 | 1,299 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,295 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules_multimer.py | 937,940 | 899,1048 | construct_input | SingleTemplateEmbedding | 940,1011 | 940,1011 | class SingleTemplateEmbedding(hk.Module):
"""Embed a single template."""
def __init__(self, config, global_config, name='single_template_embedding'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call__(self, query_embedding, template_aatype,
... | class SingleTemplateEmbedding(hk.Module):
"""Embed a single template."""
def __init__(self, config, global_config, name='single_template_embedding'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call__(self, query_embedding, template_aatype,
... |
# Compute distogram feature for the template.
template_positions, pseudo_beta_mask = modules.pseudo_beta_fn(
template_aatype, template_all_atom_positions, template_all_atom_mask)
pseudo_beta_mask_2d = (pseudo_beta_mask[:, None] *
pseudo_beta_mask[None, :])
... |
# Compute distogram feature for the template.
template_positions, pseudo_beta_mask = modules.pseudo_beta_fn(
template_aatype, template_all_atom_positions, template_all_atom_mask)
pseudo_beta_mask_2d = (pseudo_beta_mask[:, None] *
pseudo_beta_mask[None, :])
... | 254 | 871 | 1,077 | 1,948 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,296 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/modules_multimer.py | 878,879 | 819,899 | scan_fn | TemplateEmbedding | 879,881 | 879,881 | class TemplateEmbedding(hk.Module):
"""Embed a set of templates."""
def __init__(self, config, global_config, name='template_embedding'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call__(self, query_embedding, template_batch, padding_mask_2d,
... | class TemplateEmbedding(hk.Module):
"""Embed a set of templates."""
def __init__(self, config, global_config, name='template_embedding'):
super().__init__(name=name)
self.config = config
self.global_config = global_config
def __call__(self, query_embedding, template_batch, padding_mask_2d,
... | return carry + partial_template_embedder(*x), None
| return carry + partial_template_embedder(*x), None
| 5 | 929 | 18 | 947 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,297 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/prng.py | 21,22 | 1,70 | safe_dropout | 22,28 | 22,28 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | if is_training and rate != 0.0 and not is_deterministic:
return hk.dropout(safe_key.get(), rate, tensor)
else:
return tensor
| if is_training and rate != 0.0 and not is_deterministic:
return hk.dropout(safe_key.get(), rate, tensor)
else:
return tensor
| 16 | 605 | 56 | 661 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,298 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/prng.py | 50,51 | 28,56 | duplicate | SafeKey | 51,56 | 51,56 | class SafeKey:
"""Safety wrapper for PRNG keys."""
def __init__(self, key):
self._key = key
self._used = False
def _assert_not_used(self):
if self._used:
raise RuntimeError('Random key has been used previously.')
def get(self):
self._assert_not_used()
self._used = True
return se... | class SafeKey:
"""Safety wrapper for PRNG keys."""
def __init__(self, key):
self._key = key
self._used = False
def _assert_not_used(self):
if self._used:
raise RuntimeError('Random key has been used previously.')
def get(self):
self._assert_not_used()
self._used = True
return se... | self._assert_not_used()
self._used = True
return tuple(SafeKey(self._key) for _ in range(num_keys))
| self._assert_not_used()
self._used = True
return tuple(SafeKey(self._key) for _ in range(num_keys))
| 10 | 202 | 45 | 247 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,299 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/prng_test.py | 24,25 | 22,44 | test_key_reuse | PrngTest | 25,44 | 25,44 | class PrngTest(absltest.TestCase):
def test_key_reuse(self):
FILL_FUNC_BODY | class PrngTest(absltest.TestCase):
def test_key_reuse(self):
FILL_FUNC_BODY |
init_key = jax.random.PRNGKey(42)
safe_key = prng.SafeKey(init_key)
_, safe_key = safe_key.split()
raw_key = safe_key.get()
self.assertFalse((raw_key == init_key).all())
with self.assertRaises(RuntimeError):
safe_key.get()
with self.assertRaises(RuntimeError):
safe_key.split... |
init_key = jax.random.PRNGKey(42)
safe_key = prng.SafeKey(init_key)
_, safe_key = safe_key.split()
raw_key = safe_key.get()
self.assertFalse((raw_key == init_key).all())
with self.assertRaises(RuntimeError):
safe_key.get()
with self.assertRaises(RuntimeError):
safe_key.split... | 25 | 35 | 164 | 199 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,301 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/quat_affine.py | 259,260 | 181,344 | pre_compose | QuatAffine | 270,287 | 260,287 | class QuatAffine(object):
"""Affine transformation represented by quaternion and vector."""
def __init__(self, quaternion, translation, rotation=None, normalize=True,
unstack_inputs=False):
"""Initialize from quaternion and translation.
Args:
quaternion: Rotation represented by a quat... | class QuatAffine(object):
"""Affine transformation represented by quaternion and vector."""
def __init__(self, quaternion, translation, rotation=None, normalize=True,
unstack_inputs=False):
"""Initialize from quaternion and translation.
Args:
quaternion: Rotation represented by a quat... | vector_quaternion_update, x, y, z = jnp.split(update, [3, 4, 5], axis=-1)
trans_update = [jnp.squeeze(x, axis=-1),
jnp.squeeze(y, axis=-1),
jnp.squeeze(z, axis=-1)]
new_quaternion = (self.quaternion +
quat_multiply_by_vec(self.quaternion,
... | """Return a new QuatAffine which applies the transformation update first.
Args:
update: Length-6 vector. 3-vector of x, y, and z such that the quaternion
update is (1, x, y, z) and zero for the 3-vector is the identity
quaternion. 3-vector for translation concatenated.
Returns:
... | 43 | 1,667 | 250 | 1,917 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,302 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/quat_affine_test.py | 43,44 | 33,149 | test_conversion | QuatAffineTest | 44,68 | 44,68 | class QuatAffineTest(absltest.TestCase):
def _assert_check(self, to_check, tol=1e-5):
for k, (correct, generated) in to_check.items():
if VERBOSE:
logging.info(k)
logging.info('Correct %s', correct)
logging.info('Predicted %s', generated)
self.assertLess(np.max(np.abs(correct ... | class QuatAffineTest(absltest.TestCase):
def _assert_check(self, to_check, tol=1e-5):
for k, (correct, generated) in to_check.items():
if VERBOSE:
logging.info(k)
logging.info('Correct %s', correct)
logging.info('Predicted %s', generated)
self.assertLess(np.max(np.abs(correct ... | quat = jnp.array([-2., 5., -1., 4.])
rotation = jnp.array([
[0.26087, 0.130435, 0.956522],
[-0.565217, -0.782609, 0.26087],
[0.782609, -0.608696, -0.130435]])
translation = jnp.array([1., -3., 4.])
point = jnp.array([0.7, 3.2, -2.9])
a = quat_affine.QuatAffine(quat, transl... | quat = jnp.array([-2., 5., -1., 4.])
rotation = jnp.array([
[0.26087, 0.130435, 0.956522],
[-0.565217, -0.782609, 0.26087],
[0.782609, -0.608696, -0.130435]])
translation = jnp.array([1., -3., 4.])
point = jnp.array([0.7, 3.2, -2.9])
a = quat_affine.QuatAffine(quat, transl... | 70 | 1,417 | 402 | 1,819 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,304 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/model/utils.py | 121,122 | 1,174 | padding_consistent_rng | 143,174 | 122,174 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | def grid_keys(key, shape):
"""Generate a grid of rng keys that is consistent with different padding.
Generate random keys such that the keys will be identical, regardless of
how much padding is added to any dimension.
Args:
key: A PRNG key.
shape: The shape of the output array of keys th... | """Modify any element-wise random function to be consistent with padding.
Normally if you take a function like jax.random.normal and generate an array,
say of size (10,10), you will get a different set of random numbers to if you
add padding and take the first (10,10) sub-array.
This function makes a random... | 104 | 1,494 | 344 | 1,838 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,305 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/relax/amber_minimize_test.py | 27,28 | 1,134 | _load_test_protein | 28,33 | 28,33 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | pdb_path = os.path.join(absltest.get_default_test_srcdir(), data_path)
with open(pdb_path, 'r') as f:
return protein.from_pdb_string(f.read())
| pdb_path = os.path.join(absltest.get_default_test_srcdir(), data_path)
with open(pdb_path, 'r') as f:
return protein.from_pdb_string(f.read())
| 11 | 1,566 | 70 | 1,636 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,306 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/relax/amber_minimize_test.py | 69,70 | 33,132 | test_find_violations | AmberMinimizeTest | 70,132 | 70,132 | class AmberMinimizeTest(absltest.TestCase):
def test_multiple_disulfides_target(self):
prot = _load_test_protein(
'alphafold/relax/testdata/multiple_disulfides_target.pdb'
)
ret = amber_minimize.run_pipeline(prot, max_iterations=10, max_attempts=1,
stiffn... | class AmberMinimizeTest(absltest.TestCase):
def test_multiple_disulfides_target(self):
prot = _load_test_protein(
'alphafold/relax/testdata/multiple_disulfides_target.pdb'
)
ret = amber_minimize.run_pipeline(prot, max_iterations=10, max_attempts=1,
stiffn... | prot = _load_test_protein(
'alphafold/relax/testdata/multiple_disulfides_target.pdb'
)
viols, _ = amber_minimize.find_violations(prot)
expected_between_residues_connection_mask = np.zeros((191,), np.float32)
for residue in (42, 43, 59, 60, 135, 136):
expected_between_residues_conn... | prot = _load_test_protein(
'alphafold/relax/testdata/multiple_disulfides_target.pdb'
)
viols, _ = amber_minimize.find_violations(prot)
expected_between_residues_connection_mask = np.zeros((191,), np.float32)
for residue in (42, 43, 59, 60, 135, 136):
expected_between_residues_conn... | 126 | 540 | 823 | 1,363 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,307 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/relax/relax.py | 58,61 | 23,85 | process | AmberRelaxation | 62,85 | 61,85 | class AmberRelaxation(object):
"""Amber relaxation."""
def __init__(self,
*,
max_iterations: int,
tolerance: float,
stiffness: float,
exclude_residues: Sequence[int],
max_outer_iterations: int,
use_gpu: bool):
... | class AmberRelaxation(object):
"""Amber relaxation."""
def __init__(self,
*,
max_iterations: int,
tolerance: float,
stiffness: float,
exclude_residues: Sequence[int],
max_outer_iterations: int,
use_gpu: bool):
... | out = amber_minimize.run_pipeline(
prot=prot, max_iterations=self._max_iterations,
tolerance=self._tolerance, stiffness=self._stiffness,
exclude_residues=self._exclude_residues,
max_outer_iterations=self._max_outer_iterations,
use_gpu=self._use_gpu)
min_pos = out['pos']
... | """Runs Amber relax on a prediction, adds hydrogens, returns PDB string."""
out = amber_minimize.run_pipeline(
prot=prot, max_iterations=self._max_iterations,
tolerance=self._tolerance, stiffness=self._stiffness,
exclude_residues=self._exclude_residues,
max_outer_iterations=self.... | 53 | 464 | 374 | 838 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,308 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/relax/relax_test.py | 40,41 | 25,88 | test_process | RunAmberRelaxTest | 41,70 | 41,70 | class RunAmberRelaxTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.test_dir = os.path.join(
absltest.get_default_test_srcdir(),
'alphafold/relax/testdata/')
self.test_config = {
'max_iterations': 1,
'tolerance': 2.39,
'stiffness': 10.0,
'excl... | class RunAmberRelaxTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.test_dir = os.path.join(
absltest.get_default_test_srcdir(),
'alphafold/relax/testdata/')
self.test_config = {
'max_iterations': 1,
'tolerance': 2.39,
'stiffness': 10.0,
'excl... | amber_relax = relax.AmberRelaxation(**self.test_config)
with open(os.path.join(self.test_dir, 'model_output.pdb')) as f:
test_prot = protein.from_pdb_string(f.read())
pdb_min, debug_info, num_violations = amber_relax.process(prot=test_prot)
self.assertCountEqual(debug_info.keys(),
... | amber_relax = relax.AmberRelaxation(**self.test_config)
with open(os.path.join(self.test_dir, 'model_output.pdb')) as f:
test_prot = protein.from_pdb_string(f.read())
pdb_min, debug_info, num_violations = amber_relax.process(prot=test_prot)
self.assertCountEqual(debug_info.keys(),
... | 77 | 808 | 534 | 1,342 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,309 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/relax/utils.py | 22,23 | 1,70 | overwrite_b_factors | 34,61 | 23,61 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | if bfactors.shape[-1] != residue_constants.atom_type_num:
raise ValueError(
f'Invalid final dimension size for bfactors: {bfactors.shape[-1]}.')
parser = PDB.PDBParser(QUIET=True)
handle = io.StringIO(pdb_str)
structure = parser.get_structure('', handle)
curr_resid = ('', '', '')
idx = -1
fo... | """Overwrites the B-factors in pdb_str with contents of bfactors array.
Args:
pdb_str: An input PDB string.
bfactors: A numpy array with shape [1, n_residues, 37]. We assume that the
B-factors are per residue; i.e. that the nonzero entries are identical in
[0, i, :].
Returns:
A new PDB s... | 80 | 532 | 347 | 879 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
16,310 | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold | /home/hieuvd/dung_repo/raw/stars_01/google-deepmind_alphafold/alphafold/alphafold/relax/utils_test.py | 28,29 | 26,54 | test_overwrite_b_factors | UtilsTest | 29,54 | 29,54 | class UtilsTest(absltest.TestCase):
def test_overwrite_b_factors(self):
FILL_FUNC_BODY | class UtilsTest(absltest.TestCase):
def test_overwrite_b_factors(self):
FILL_FUNC_BODY | testdir = os.path.join(
absltest.get_default_test_srcdir(),
'alphafold/relax/testdata/'
'multiple_disulfides_target.pdb')
with open(testdir) as f:
test_pdb = f.read()
n_residues = 191
bfactors = np.stack([np.arange(0, n_residues)] * 37, axis=-1)
output_pdb = utils.over... | testdir = os.path.join(
absltest.get_default_test_srcdir(),
'alphafold/relax/testdata/'
'multiple_disulfides_target.pdb')
with open(testdir) as f:
test_pdb = f.read()
n_residues = 191
bfactors = np.stack([np.arange(0, n_residues)] * 37, axis=-1)
output_pdb = utils.over... | 95 | 38 | 446 | 484 | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
16,314 | /home/hieuvd/dung_repo/raw/stars_01/google-research_bert/bert | /home/hieuvd/dung_repo/raw/stars_01/google-research_bert/bert/tokenization_test.py | 66,67 | 26,136 | test_basic_tokenizer_no_lower | TokenizationTest | 67,73 | 67,73 | class TokenizationTest(tf.test.TestCase):
def test_full_tokenizer(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing", ","
]
with tempfile.NamedTemporaryFile(delete=False) as vocab_writer:
if six.PY2:
vocab_writer.write(""... | class TokenizationTest(tf.test.TestCase):
def test_full_tokenizer(self):
vocab_tokens = [
"[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
"##ing", ","
]
with tempfile.NamedTemporaryFile(delete=False) as vocab_writer:
if six.PY2:
vocab_writer.write(""... | tokenizer = tokenization.BasicTokenizer(do_lower_case=False)
self.assertAllEqual(
tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
["HeLLo", "!", "how", "Are", "yoU", "?"])
| tokenizer = tokenization.BasicTokenizer(do_lower_case=False)
self.assertAllEqual(
tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "),
["HeLLo", "!", "how", "Are", "yoU", "?"])
| 16 | 1,394 | 86 | 1,480 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
17,079 | /home/hieuvd/dung_repo/raw/stars_01/healthchecks_healthchecks/healthchecks | /home/hieuvd/dung_repo/raw/stars_01/healthchecks_healthchecks/healthchecks/hc/lib/html.py | 42,43 | 1,79 | extract_signal_styles | 56,79 | 43,79 | from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from typing import Any
class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["scrip... | from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from typing import Any
class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["scrip... | text = ""
styles: list[str] = []
tag, tag_idx = "", 0
for part in re.split(r"(</?(?:b|code)>)", markup):
if part == "<b>":
tag = "BOLD"
tag_idx = len(text)
elif part == "</b>":
assert tag == "BOLD"
len_tagged = len(text) - tag_idx
... | """Convert HTML syntax to Signal text styles.
This implementation has limited functionality, and only supports the features
we do use:
* only supports <b> and <code> tags
* does not support nested (<b><code>text</code></b>) tags
Example:
>>> extract_signal_styles("<b>foo</b> bar")
"fo... | 72 | 470 | 271 | 741 | from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from typing import Any
class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["scrip... | from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from typing import Any
class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["scrip... | |
17,080 | /home/hieuvd/dung_repo/raw/stars_01/healthchecks_healthchecks/healthchecks | /home/hieuvd/dung_repo/raw/stars_01/healthchecks_healthchecks/healthchecks/hc/lib/html.py | 24,25 | 9,33 | handle_data | TextOnlyParser | 25,28 | 25,28 | class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["script", "style"])
def handle_starttag(self, tag: str, attrs: Any) -> None:
if tag in self.skiplist:
self.active... | class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["script", "style"])
def handle_starttag(self, tag: str, attrs: Any) -> None:
if tag in self.skiplist:
self.active... | if self.active and data:
self.buf.append(data)
| if self.active and data:
self.buf.append(data)
| 5 | 213 | 23 | 236 | from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from typing import Any
class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["scrip... | from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from typing import Any
class TextOnlyParser(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.active = True
self.buf: list[str] = []
self.skiplist = set(["scrip... |
17,081 | /home/hieuvd/dung_repo/raw/stars_01/healthchecks_healthchecks/healthchecks | /home/hieuvd/dung_repo/raw/stars_01/healthchecks_healthchecks/healthchecks/hc/lib/string.py | 10,11 | 1,52 | replace | 35,50 | 11,50 | from __future__ import annotations
import re
uuid_match_regex = re.compile(
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
)
def replace(template: str, ctx: dict[str, str]) -> str:
FILL_FUNC_BODYdef is_valid_uuid_string(value: str) -> bool:
return bool(uuid_match_regex.match(value))
| from __future__ import annotations
import re
uuid_match_regex = re.compile(
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
)
def replace(template: str, ctx: dict[str, str]) -> str:
"""Replace placeholders with their values and return the result.
Example:
>>> replace("$NAME is dow... |
parts = template.split("$")
result = [parts.pop(0)]
for part in parts:
part = "$" + part
for placeholder, value in ctx.items():
if part.startswith(placeholder):
part = part.replace(placeholder, value, 1)
break
result.append(part)
ret... | """Replace placeholders with their values and return the result.
Example:
>>> replace("$NAME is down", {"$NAME": "foo"})
foo is down
This function explicitly ignores "variable variables".
In this example, placeholder's value itself contains a placeholder:
>>> replace("Hello $FOO", {"$FOO... | 31 | 372 | 116 | 488 | from __future__ import annotations
import re
uuid_match_regex = re.compile(
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
)
def replace(template: str, ctx: dict[str, str]) -> str:
FILL_FUNC_BODYdef is_valid_uuid_string(value: str) -> bool:
return bool(uuid_match_regex.match(value))
| from __future__ import annotations
import re
uuid_match_regex = re.compile(
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
)
def replace(template: str, ctx: dict[str, str]) -> str:
"""Replace placeholders with their values and return the result.
Example:
>>> replace("$NAME is dow... | |
17,251 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/examples/boft_controlnet/utils/tracemalloc.py | 9,10 | 1,59 | b2mb | 10,14 | 10,14 | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
| return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
| 19 | 568 | 35 | 603 | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | |
17,252 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/examples/boft_controlnet/utils/tracemalloc.py | 33,34 | 14,59 | peak_monitor_func | TorchTracemalloc | 34,45 | 34,45 | class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.cuda.memory_allocated()
self.process = psutil.Process()
self.cpu_begin = self.cpu_mem_used()
... | class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.cuda.memory_allocated()
self.process = psutil.Process()
self.cpu_begin = self.cpu_mem_used()
... | self.cpu_peak = -1
while True:
self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
# time.sleep(0.001) # 1msec
if not self.peak_monitoring:
break
| self.cpu_peak = -1
while True:
self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
# time.sleep(0.001) # 1msec
if not self.peak_monitoring:
break
| 33 | 434 | 108 | 542 | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
to... | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
to... |
17,253 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/examples/boft_dreambooth/utils/tracemalloc.py | 9,10 | 1,59 | b2mb | 10,14 | 10,14 | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
| return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
| 19 | 568 | 35 | 603 | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
FILL_FUNC_BODYclass TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = ... | |
17,254 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/examples/boft_dreambooth/utils/tracemalloc.py | 33,34 | 14,59 | peak_monitor_func | TorchTracemalloc | 34,45 | 34,45 | class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.cuda.memory_allocated()
self.process = psutil.Process()
self.cpu_begin = self.cpu_mem_used()
... | class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
self.begin = torch.cuda.memory_allocated()
self.process = psutil.Process()
self.cpu_begin = self.cpu_mem_used()
... | self.cpu_peak = -1
while True:
self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
# time.sleep(0.001) # 1msec
if not self.peak_monitoring:
break
| self.cpu_peak = -1
while True:
self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
# time.sleep(0.001) # 1msec
if not self.peak_monitoring:
break
| 33 | 434 | 108 | 542 | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
to... | import gc
import threading
import psutil
import torch
# Converting Bytes to Megabytes
def b2mb(x):
return int(x / 2**20)
# This context manager is used to track the peak memory usage of the process
class TorchTracemalloc:
def __enter__(self):
gc.collect()
torch.cuda.empty_cache()
to... |
17,256 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/examples/fp4_finetuning/finetune_fp4_opt_bnb_peft.py | 80,81 | 79,84 | forward | CastOutputToFloat | 81,84 | 81,84 | class CastOutputToFloat(nn.Sequential):
def forward(self, x):
FILL_FUNC_BODY | class CastOutputToFloat(nn.Sequential):
def forward(self, x):
FILL_FUNC_BODY | return super().forward(x).to(torch.float32)
| return super().forward(x).to(torch.float32)
| 2 | 32 | 23 | 55 | import os
import torch
import torch.nn as nn
import transformers
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# -*- coding: utf-8 -*-
"""Finetune-opt-bnb-peft.i... | import os
import torch
import torch.nn as nn
import transformers
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# -*- coding: utf-8 -*-
"""Finetune-opt-bnb-peft.i... |
17,258 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/scripts/launch_notebook_mp.py | 27,28 | 1,46 | init | 28,40 | 28,40 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1, 2)
def forward(self, x):
return self.linear(x)
model = MyModule().to("cuda")
peft.get_peft_model(model, peft.LoraConfig(target_modules=["linear"]))
... | class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1, 2)
def forward(self, x):
return self.linear(x)
model = MyModule().to("cuda")
peft.get_peft_model(model, peft.LoraConfig(target_modules=["linear"]))
... | 19 | 338 | 122 | 460 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | |
17,259 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/scripts/launch_notebook_mp.py | 33,34 | 28,36 | forward | MyModule | 34,36 | 34,36 | class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1, 2)
def forward(self, x):
FILL_FUNC_BODY | class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1, 2)
def forward(self, x):
FILL_FUNC_BODY | return self.linear(x)
| return self.linear(x)
| 2 | 67 | 12 | 79 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,261 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/config.py | 265,267 | 241,271 | is_prompt_learning | PromptLearningConfig | 267,271 | 267,271 | @dataclass
class PromptLearningConfig(PeftConfig):
"""
This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or
[`PromptTuning`].
Args:
num_virtual_tokens (`int`): The number of virtual tokens to use.
token_dim (`int`): The hidden embedd... | @dataclass
class PromptLearningConfig(PeftConfig):
"""
This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or
[`PromptTuning`].
Args:
num_virtual_tokens (`int`): The number of virtual tokens to use.
token_dim (`int`): The hidden embedd... | r"""
Utility method to check if the configuration is for prompt learning.
"""
return True
| r"""
Utility method to check if the configuration is for prompt learning.
"""
return True
| 15 | 374 | 29 | 403 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,262 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/helpers.py | 56,57 | 1,149 | update_generate_signature | 79,96 | 57,96 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | if not hasattr(model, "generate"):
return
current_signature = inspect.signature(model.generate)
if (
len(current_signature.parameters) == 2
and "args" in current_signature.parameters
and "kwargs" in current_signature.parameters
) or (len(current_signature.parameters) == 1... | """
Updates the generate signature of a PeftModel with overriding generate to include parents class signature
model (`PeftModel`): Peft model to update the generate signature
Example:
```python
>>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
>>> from peft import get_p... | 44 | 1,510 | 188 | 1,698 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | |
17,264 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adalora/bnb.py | 104,105 | 84,146 | forward | SVDLinear4bit | 105,143 | 105,143 | class SVDLinear4bit(torch.nn.Module, AdaLoraLayer):
# Low-rank matrix for SVD-based adaptation
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.0,
... | class SVDLinear4bit(torch.nn.Module, AdaLoraLayer):
# Low-rank matrix for SVD-based adaptation
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.0,
... | # note: no check for self.merged because merging is not supported (yet)
result = self.base_layer(x, *args, **kwargs)
if self.disable_adapters:
return result
# As per Tim Dettmers, for 4bit, we need to defensively clone here.
# The reason is t... | # note: no check for self.merged because merging is not supported (yet)
result = self.base_layer(x, *args, **kwargs)
if self.disable_adapters:
return result
# As per Tim Dettmers, for 4bit, we need to defensively clone here.
# The reason is t... | 154 | 303 | 481 | 784 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,265 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adalora/bnb.py | 46,47 | 26,82 | forward | SVDLinear8bitLt | 47,77 | 47,77 | class SVDLinear8bitLt(torch.nn.Module, AdaLoraLayer):
# Low-rank matrix for SVD-based adaptation
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.0,
... | class SVDLinear8bitLt(torch.nn.Module, AdaLoraLayer):
# Low-rank matrix for SVD-based adaptation
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.0,
... | # note: no check for self.merged because merging is not supported (yet)
result = self.base_layer(x)
if self.disable_adapters:
return result
for active_adapter in self.active_adapters:
if active_adapter not in self.lora_A.keys():
... | # note: no check for self.merged because merging is not supported (yet)
result = self.base_layer(x)
if self.disable_adapters:
return result
for active_adapter in self.active_adapters:
if active_adapter not in self.lora_A.keys():
... | 105 | 297 | 387 | 684 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,266 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adalora/gptq.py | 39,40 | 19,73 | forward | SVDQuantLinear | 40,73 | 40,73 | class SVDQuantLinear(torch.nn.Module, AdaLoraLayer):
def __init__(
self,
base_layer,
adapter_name,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.0,
init_lora_weights: bool = True,
**kwargs,
) -> None:
super().__init__()
A... | class SVDQuantLinear(torch.nn.Module, AdaLoraLayer):
def __init__(
self,
base_layer,
adapter_name,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.0,
init_lora_weights: bool = True,
**kwargs,
) -> None:
super().__init__()
A... | result = self.quant_linear_module(x)
if self.disable_adapters:
return result
for active_adapter in self.active_adapters:
if active_adapter not in self.lora_A.keys():
continue
lora_A = self.lora_A[active_adapter]
lora_B = self.lora... | result = self.quant_linear_module(x)
if self.disable_adapters:
return result
for active_adapter in self.active_adapters:
if active_adapter not in self.lora_A.keys():
continue
lora_A = self.lora_A[active_adapter]
lora_B = self.lora... | 113 | 254 | 423 | 677 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,267 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adaption_prompt/config.py | 67,71 | 1,81 | prepare_config | 72,81 | 71,81 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | if model.config.model_type not in TRANSFORMERS_MODEL_CONFIG:
raise ValueError("Unsupported model type for adaption prompt: '{model.config.model_type}'.")
model_config = TRANSFORMERS_MODEL_CONFIG[model.config.model_type]
if peft_config.target_modules is None:
peft_config.target_modules = mo... | """Prepare the config based on the llama model type."""
if model.config.model_type not in TRANSFORMERS_MODEL_CONFIG:
raise ValueError("Unsupported model type for adaption prompt: '{model.config.model_type}'.")
model_config = TRANSFORMERS_MODEL_CONFIG[model.config.model_type]
if peft_config.tar... | 25 | 758 | 123 | 881 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | |
17,268 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adaption_prompt/config.py | 37,39 | 24,44 | is_adaption_prompt | AdaptionPromptConfig | 40,44 | 39,44 | @dataclass
class AdaptionPromptConfig(PeftConfig):
"""Stores the configuration of an [`AdaptionPromptModel`]."""
target_modules: str = field(
default=None, metadata={"help": "Name of the attention submodules to insert adaption prompts into."}
)
adapter_len: int = field(default=None, metadata={"... | @dataclass
class AdaptionPromptConfig(PeftConfig):
"""Stores the configuration of an [`AdaptionPromptModel`]."""
target_modules: str = field(
default=None, metadata={"help": "Name of the attention submodules to insert adaption prompts into."}
)
adapter_len: int = field(default=None, metadata={"... | return True
# Contains the config that is specific to a transformers model type.
| """Return True if this is an adaption prompt config."""
return True
# Contains the config that is specific to a transformers model type.
| 14 | 216 | 26 | 242 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,269 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adaption_prompt/layer.py | 57,58 | 24,129 | forward | AdaptedAttention | 67,129 | 58,129 | class AdaptedAttention(nn.Module):
"""This module wraps a LLamaAttention module and injects adaption prompts."""
def __init__(self, model_type: str, adapter_len: int, model):
"""
Initialize object.
Args:
model_type: The transformer model type. This is used to retrieve the r... | class AdaptedAttention(nn.Module):
"""This module wraps a LLamaAttention module and injects adaption prompts."""
def __init__(self, model_type: str, adapter_len: int, model):
"""
Initialize object.
Args:
model_type: The transformer model type. This is used to retrieve the r... | if kwargs.get("output_attention", False):
raise NotImplementedError("output_attention is not currently supported.")
output, _, past_key_value = self.model(**kwargs)
bsz = output.shape[0]
q_len = output.shape[1]
embed_dim = output.shape[2]
k_proj_layer = TRANS... | """
Forward pass for the adapter which wraps the original LlamaAttention module.
"Official" paper implementation:
https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L141
Args:
kwargs: See the original LlamaAtte... | 230 | 650 | 1,133 | 1,783 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,270 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adaption_prompt/model.py | 120,121 | 26,162 | _create_adapted_attentions | AdaptionPromptModel | 122,130 | 121,130 | class AdaptionPromptModel(nn.Module):
"""
Implements adaption prompts as described in https://arxiv.org/pdf/2303.16199.pdf.
The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert
trainable prompts with gates (for zero init).
Notes on the mult... | class AdaptionPromptModel(nn.Module):
"""
Implements adaption prompts as described in https://arxiv.org/pdf/2303.16199.pdf.
The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert
trainable prompts with gates (for zero init).
Notes on the mult... | for par in parents:
attn = AdaptedAttention(
model_type=self.model.config.model_type,
adapter_len=config.adapter_len,
model=getattr(par, config.target_modules),
)
setattr(par, config.target_modules, attn)
| """Wrap LlamaAttention modules with newly created AdaptedAttention modules."""
for par in parents:
attn = AdaptedAttention(
model_type=self.model.config.model_type,
adapter_len=config.adapter_len,
model=getattr(par, config.target_modules),
... | 15 | 1,766 | 90 | 1,856 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,271 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/adaption_prompt/utils.py | 20,21 | 1,122 | llama_rotate_half | 30,35 | 21,35 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
| """
Rotate half the hidden dims of the input.
This function was duplicated verbatim from:
https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L126
This was done to eliminate the Llama transformers implementation ... | 18 | 1,906 | 67 | 1,973 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | |
17,273 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/ia3/bnb.py | 96,97 | 78,130 | forward | Linear4bit | 97,127 | 97,127 | class Linear4bit(torch.nn.Module, IA3Layer):
# IA3 implemented in a dense layer
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
is_feedforward: bool,
init_ia3_weights: bool = True,
**kwargs,
) -> None... | class Linear4bit(torch.nn.Module, IA3Layer):
# IA3 implemented in a dense layer
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
is_feedforward: bool,
init_ia3_weights: bool = True,
**kwargs,
) -> None... | # note: no check for self.merged because merging is not supported (yet)
if self.disable_adapters:
return self.base_layer(x)
ia3_scaling = 1
for active_adapter in self.active_adapters:
if active_adapter not in self.ia3_l.keys():
... | # note: no check for self.merged because merging is not supported (yet)
if self.disable_adapters:
return self.base_layer(x)
ia3_scaling = 1
for active_adapter in self.active_adapters:
if active_adapter not in self.ia3_l.keys():
... | 101 | 271 | 357 | 628 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,274 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/ia3/bnb.py | 44,45 | 26,76 | forward | Linear8bitLt | 45,71 | 45,71 | class Linear8bitLt(torch.nn.Module, IA3Layer):
# (IA)^3 implemented in a dense layer
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
is_feedforward: bool,
init_ia3_weights: bool = True,
**kwargs,
) ->... | class Linear8bitLt(torch.nn.Module, IA3Layer):
# (IA)^3 implemented in a dense layer
def __init__(
self,
base_layer: torch.nn.Module,
adapter_name: str,
is_feedforward: bool,
init_ia3_weights: bool = True,
**kwargs,
) ->... | # note: no check for self.merged because merging is not supported (yet)
if self.disable_adapters:
return self.base_layer(x)
ia3_scaling = 1
for active_adapter in self.active_adapters:
if active_adapter not in self.ia3_l.keys():
... | # note: no check for self.merged because merging is not supported (yet)
if self.disable_adapters:
return self.base_layer(x)
ia3_scaling = 1
for active_adapter in self.active_adapters:
if active_adapter not in self.ia3_l.keys():
... | 74 | 277 | 301 | 578 | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
17,275 | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft | /home/hieuvd/dung_repo/raw/stars_01/huggingface_peft/peft/src/peft/tuners/ln_tuning/layer.py | 43,44 | 25,118 | enable_adapters | LNTuningLayer | 51,63 | 44,63 | class LNTuningLayer(nn.Module, BaseTunerLayer):
"""
Selects a layer from the model.
"""
adapter_layer_names = ("ln_tuning_layers",)
def __init__(self, base_layer: nn.Module, adapter_name: str):
super().__init__()
self.base_layer = base_layer
self.ln_tuning_layers = nn.Modul... | class LNTuningLayer(nn.Module, BaseTunerLayer):
"""
Selects a layer from the model.
"""
adapter_layer_names = ("ln_tuning_layers",)
def __init__(self, base_layer: nn.Module, adapter_name: str):
super().__init__()
self.base_layer = base_layer
self.ln_tuning_layers = nn.Modul... | if enabled:
self.set_adapter(self.active_adapters)
self._disable_adapters = False
else:
if self.merged:
self.unmerge()
# disable grads on all adapter layers
for layer_name in self.adapter_layer_names:
layer = get... | """Toggle the enabling and disabling of adapters
Takes care of setting the requires_grad flag for the adapter weights.
Args:
enabled (bool): True to enable adapters, False to disable adapters
"""
if enabled:
self.set_adapter(self.active_adapters)
... | 29 | 945 | 126 | 1,071 | # Copyright 2024-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2024-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.