python_code stringlengths 0 4.04M | repo_name stringlengths 7 58 | file_path stringlengths 5 147 |
|---|---|---|
import torch
import torch.nn.functional as F
import opt_einsum as oe
from einops import repeat, rearrange
from model.functional.krylov import krylov
from model.ssm.companion import CompanionSSM
class ClosedLoopCompanionSSM(CompanionSSM):
"""
Closed-loop implementation of Companion SSM:
- Instantiate A, B... | spacetime-main | model/ssm/closed_loop/companion.py |
from .companion import ClosedLoopCompanionSSM
from .shift import ClosedLoopShiftSSM
| spacetime-main | model/ssm/closed_loop/__init__.py |
import torch
import torch.nn.functional as F
import opt_einsum as oe
from einops import repeat, rearrange
from model.functional.krylov import krylov
from model.ssm.closed_loop.companion import ClosedLoopCompanionSSM
class ClosedLoopShiftSSM(ClosedLoopCompanionSSM):
def __init__(self, **kwargs):
super()._... | spacetime-main | model/ssm/closed_loop/shift.py |
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from model.ssm.base import SSM
from model.ssm.preprocess.differencing import get_pascal
class ResidualSSM(SSM):
"""
Computes both order-N differencing and moving average residuals over input sequence
"""
def __init__(s... | spacetime-main | model/ssm/preprocess/residual.py |
import torch.nn as nn
from .differencing import DifferencingSSM
from .ma_residual import MovingAvgResidualSSM
from .residual import ResidualSSM
def init_preprocess_ssm(config):
if config['method'] == 'differencing':
ssm = DifferencingSSM
elif config['method'] == 'ma_residual':
ssm = MovingAvg... | spacetime-main | model/ssm/preprocess/__init__.py |
import torch
import torch.nn.functional as F
from model.ssm.base import SSM
class DifferencingSSM(SSM):
"""
Computes order-N differencing over input sequence
"""
def __init__(self, max_diff_order=4, **kwargs):
self.max_diff_order = max_diff_order
kwargs['n_heads'] = 1
kwargs['k... | spacetime-main | model/ssm/preprocess/differencing.py |
import torch
import torch.nn.functional as F
from model.ssm.base import SSM
class MovingAvgResidualSSM(SSM):
"""
Computes moving average residuals over input sequence
"""
def __init__(self, min_avg_window=4, max_avg_window=720, **kwargs):
self.min_avg_window = min_avg_window
self.max_a... | spacetime-main | model/ssm/preprocess/ma_residual.py |
import torch.nn as nn
from .base import Embedding
class LinearEmbedding(Embedding):
def __init__(self, input_dim, embedding_dim):
super().__init__(input_dim, embedding_dim)
def initialize_layers(self):
self.layers = nn.Linear(self.input_dim, self.embedding_dim) | spacetime-main | model/embedding/linear.py |
from .base import Embedding
from .linear import LinearEmbedding
from .repeat import RepeatEmbedding
def init_embedding(config):
methods = ['linear', 'identity', 'repeat']
if config['method'] == 'linear':
return LinearEmbedding(**config['kwargs'])
elif config['method'] == 'repeat':
return R... | spacetime-main | model/embedding/__init__.py |
from einops import repeat
from .base import Embedding
class RepeatEmbedding(Embedding):
def __init__(self,
input_dim: int,
embedding_dim: int=None,
n_heads: int=None,
n_kernels: int=None):
if embedding_dim is None:
try... | spacetime-main | model/embedding/repeat.py |
import torch.nn as nn
class Embedding(nn.Module):
def __init__(self,
input_dim: int,
embedding_dim: int):
"""
Generic class for encoding
"""
super().__init__()
self.input_dim = input_dim
self.embedding_dim = embedding_dim
s... | spacetime-main | model/embedding/base.py |
import math
import torch
import torch.nn.functional as F
from einops import rearrange, reduce
def companion_from_p(p):
"""
Arguments:
p: (..., d)
Return:
A: (..., d, d)
"""
batch_size, d = p.shape[:-1], p.shape[-1]
A = torch.zeros(*batch_size, d, d, dtype=p.dtype, device=p.de... | spacetime-main | model/functional/companion_krylov.py |
"""
Fast and helpful functions in the style of torch.nn.functional.
Credit to Albert Hungry Hippo Gu and Tri Flying Butterfly Dao.
- companion_krylov.py from Tri
- Others from Albert: https://github.com/HazyResearch/state-spaces/tree/main/src/models/functional
""" | spacetime-main | model/functional/__init__.py |
""" pykeops implementations of the core Cauchy kernel used in the S3 algorithm.
The interface of the Cauchy multiplication is:
v: (N)
z: (N)
w: (L)
Return: y (L)
y_k = \sum_i v_i / (z_i - w_k)
"""
if __name__ == '__main__':
import sys
import pathlib
p = pathlib.Path().absolute()
p... | spacetime-main | model/functional/cauchy.py |
""" Compute a Krylov function efficiently. (S3 renames the Krylov function to a "state space kernel")
A : (N, N)
b : (N,)
c : (N,)
Return: [c^T A^i b for i in [L]]
"""
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from model.functional.toeplitz import causal_convolution
def kryl... | spacetime-main | model/functional/krylov.py |
""" Custom implementation of fast complex operations.
This was written during earlier versions of Pytorch.
Later versions have native support for complex numbers and much of this is no longer necessary.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from src.torch.utils.dlp... | spacetime-main | model/functional/complex.py |
""" Utilities for computing convolutions.
There are 3 equivalent views:
1. causal convolution
2. multiplication of (lower) triangular Toeplitz matrices
3. polynomial multiplication (mod x^N)
"""
import torch
# import torch.nn as nn
import torch.nn.functional as F
# from model.complex import complex_mul
#... | spacetime-main | model/functional/toeplitz.py |
from .train import train_model
from .evaluate import evaluate_model, plot_forecasts | spacetime-main | train/__init__.py |
"""
Shared functions called during each epoch
"""
import importlib
import torch
from utils.logging import type_of_script
def initialize_shared_step(config):
step_module = importlib.import_module(f'train.step.{config.dataset_type}')
return getattr(step_module, 'shared_step')
def run_epoch(model, dat... | spacetime-main | train/epoch.py |
"""
Training functions and helpers
"""
import importlib
import torch
import numpy as np
import pandas as pd # Local logging
from tqdm.auto import tqdm
from .epoch import run_epoch
def print_epoch_metrics(metrics):
for split in metrics.keys():
print('-'*4, f'{split}', '-'*4)
for k, v in metrics[s... | spacetime-main | train/train.py |
"""
Functions for evaluating trained models and plotting forecasts
"""
import torch
from loss import get_loss
from .epoch import run_epoch
from utils.logging import print_header
def evaluate_model(model, **kwargs):
model.eval()
log_metrics = {}
with torch.no_grad():
_, metrics, total_y = run_epoc... | spacetime-main | train/evaluate.py |
spacetime-main | train/step/__init__.py | |
import torch
from tqdm import tqdm
from loss import get_loss
from utils.logging import type_of_script
def compute_informer_metrics(y_pred, y_true):
metrics = {}
criterions = {f'informer_{name}': get_loss(f'informer_{name}')
for name in ['rmse', 'mse', 'mae']}
for k, criterion in metric... | spacetime-main | train/step/informer.py |
import torch.nn as nn
class AffineTransform(nn.Module):
def __init__(self, lag=None):
"""
Transform data: f(x) = ax - b
"""
super().__init__()
self.lag = lag
def forward(self, x):
# Assume x.shape is B x L x D
raise NotImplementedError
... | spacetime-main | data_transforms/affine.py |
from .mean import MeanTransform, MeanInputTransform
from .standardize import StandardizeTransform
from .affine import InverseAffineTransform
from .last import LastAffineTransform
def get_data_transforms(method, lag):
supported_methods = ['mean', 'mean_input', 'last',
'standardize', 'none... | spacetime-main | data_transforms/__init__.py |
import torch
from .affine import AffineTransform
class StandardizeTransform(AffineTransform):
"""
Standardize lag terms, i.e., z = (x - mean(x)) / std(x)
- Computed as (1 / std(x)) * x - mean(x) * (1 / std(x)) to fit with inverse call,
which does (z + (mean(x) / std(x))) * std(x) = z * std(x) + mea... | spacetime-main | data_transforms/standardize.py |
import torch
from .affine import AffineTransform
class MeanTransform(AffineTransform):
"""
Zero-center values
"""
def __init__(self, lag):
super().__init__(lag=lag)
def forward(self, x):
self.a = torch.ones(1)
self.b = x[:, :self.lag, :].mean(dim=1)[:, None, :]
... | spacetime-main | data_transforms/mean.py |
from .affine import AffineTransform
class LastAffineTransform(AffineTransform):
def __init__(self, lag):
super().__init__(lag=lag)
def forward(self, x):
self.a = 1.
self.b = x[:, self.lag - 1, :][:, None, :]
return self.a * x - self.b | spacetime-main | data_transforms/last.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from setuptools import setup, find_packages
setup(name='cmr', version='1.0', packages=find_packages()) | CMR-main | setup.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# %%
import json
import argparse
import pandas as pd
from argparse import Namespace
import numpy as np
import glob, os
from pandas.core import base
os.chdir("/private/home/yuchenlin/SemanticDebugger")
base_dir = "experiments/results/qa/"
... | CMR-main | experiments/report_results.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import pandas as pd
import os
import glob
from io import StringIO
import altair as alt
from torch import clamp
from cmr.notebooks.draw_utils import draw_grouped_bars
# os.chdir()
# os.makedirs("csvs/", exist_ok=True)
# result_files = []
al... | CMR-main | experiments/bakcup/report_all_settings.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
maps = """MIR # 67.40 # QA_mir_lr=3e-5_ep=10_rs=32_rf=3_mcs=256_T=100,b=64,alpha=0.9,beta=0.5,gamma=0.8_result.json
CFT # 61.58 # QA_simplecl_lr=3e-5_ep=10_T=100,b=64,alpha=0.9,beta=0.5,gamma=0.8_result.json
ER # 66.62 # QA_er_lr=3e-5_ep=10_rs... | CMR-main | experiments/bakcup/report_heatmap.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
maps = """MIR # 67.40 # QA_mir_lr=3e-5_ep=10_rs=32_rf=3_mcs=256_T=100,b=64,alpha=0.9,beta=0.5,gamma=0.8_result.json
CFT # 61.58 # QA_simplecl_lr=3e-5_ep=10_T=100,b=64,alpha=0.9,beta=0.5,gamma=0.8_result.json
ER # 66.62 # QA_er_lr=3e-5_ep=10_rs... | CMR-main | experiments/bakcup/report_curves.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
| CMR-main | cmr/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This script was based on https://github.com/shmsw25/bart-closed-book-qa.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from cmr.models.utils import set_seeds
import s... | CMR-main | cmr/cli_bart.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from cmr.notebooks.draw_utils import draw_stacked_bars
from altair.vegalite.v4.schema.core import ColorName
from sklearn.utils import validation
import pandas as pd
import json
def visualize_stream(submission_stream, data_names, cfg):
t... | CMR-main | cmr/benchmark_gen/visualize_streams.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import enum
import json
import argparse
import random
from re import S
from cmr.models.utils import set_seeds
from transformers import T5Tokenizer, T5ForConditionalGeneration
import torch
import numpy as np
from tqdm import tqdm
import spacy,... | CMR-main | cmr/benchmark_gen/para_stream.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import argparse
from os import path
import random
import json
from cmr.models.utils import set_seeds
from cmr.task_manager.eval_metrics import evaluate_func
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import panda... | CMR-main | cmr/benchmark_gen/sample_submission_streams.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
| CMR-main | cmr/benchmark_gen/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import json
import argparse
from types import new_class
import random
parser = argparse.ArgumentParser()
parser.add_argument(
"--upstream_file",
default="data/mrqa_squad/mrqa_squad_train.jsonl", type=str)
parser.add_argument... | CMR-main | cmr/benchmark_gen/generate_offline_retrainfile.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from __future__ import absolute_import, division, print_function
import argparse
import json
import logging
import os
import random
from cmr.models.utils import set_seeds
import sys
import numpy as np
import torch
from cmr.benchmark_gen impo... | CMR-main | cmr/benchmark_gen/run_bart_infer.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import argparse
import json
import random
from cmr.task_manager.eval_metrics import evaluate_func
import numpy as np
def generate_bugs(predictions, truth_data, results_all, f1_upper_bound=0.5):
assert len(predictions) == len(truth_da... | CMR-main | cmr/benchmark_gen/sample_stream_data.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_file_pattern",
default="exp_results/data_streams/paraphrase/mrqa_naturalquestions_dev.data_stream.test.wr.para_data_#.json", type=s... | CMR-main | cmr/benchmark_gen/merge_json_file.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import json
import os
import sys
from argparse import Namespace
import torch
from cmr.models.mybart import MyBart
from cmr.models.run_bart import inference
from cmr.models.utils import (convert_model_to_single_gpu,
... | CMR-main | cmr/benchmark_gen/bart_api.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import numpy as np
import string
import re
from collections import Counter
from sklearn.metrics import matthews_corrcoef, f1_score
from scipy.stats import pearsonr, spearmanr
# from rouge import Rouge
METRICS = {
'mrqa_naturalquestions': ... | CMR-main | cmr/task_manager/eval_metrics.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
| CMR-main | cmr/task_manager/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import os
import json
from .base_datamanager import MyQADataset, MyDataLoader
from .eval_metrics import METRICS, evaluate_func
import torch
import numpy as np
class GeneralDataset(object):
def __init__(self, logger, args, data_path, dat... | CMR-main | cmr/task_manager/dataloader.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler
class MyQADataset(Dataset):
def __init__(self,
input_ids, attention_mask,
decoder_input_... | CMR-main | cmr/task_manager/base_datamanager.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import torch
import torch.nn as nn
from transformers import BartModel, RobertaModel
from transformers.activations import ACT2FN
from typing import List
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_featu... | CMR-main | cmr/models/hypernet.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
| CMR-main | cmr/models/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This script was based on https://github.com/shmsw25/bart-closed-book-qa.
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers import T5ForConditionalGeneration, BartForConditionalGeneration
from transfo... | CMR-main | cmr/models/mybart.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This script was based on https://github.com/shmsw25/bart-closed-book-qa.
import os
import numpy as np
import torch
from transformers import BartTokenizer, BartConfig
from transformers import AdamW, get_linear_schedule_with_warmup
from cmr.... | CMR-main | cmr/models/run_bart.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This script was based on https://github.com/shmsw25/bart-closed-book-qa.
import copy
import torch.nn as nn
import random
import numpy as np
import torch
def set_seeds(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_s... | CMR-main | cmr/models/utils.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from transformers.modeling_bart import EncoderLayer, DecoderLayer, BartEncoder, BartDecoder, BartModel, BartForConditionalGeneration
from transformers.modeling_bart import shift_tokens_right
from transformers.configuration_bart import BartConf... | CMR-main | cmr/models/bart_with_adapater.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from cmr.debug_algs.cl_simple_alg import ContinualFinetuning
from tqdm import tqdm
import json
import random
class OfflineDebugger(ContinualFinetuning):
def __init__(self, logger):
super().__init__(logger=logger)
self.n... | CMR-main | cmr/debug_algs/offline_debug_bounds.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
from logging import disable
import numpy as np
import torch
from cmr.models.mybart import MyBart
from cmr.models import run_bart
from cmr.models.utils import (convert_model_to_single_gpu,
... | CMR-main | cmr/debug_algs/cl_simple_alg.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import json
from altair.vegalite.v4.api import value
import numpy as np
import sys
import os
from numpy.lib.function_base import median
def get_prefix(filepath):
return filepath.split("/")[2].replace("_offline_eval","").replace("nq_dev_... | CMR-main | cmr/debug_algs/evaluation.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
import argparse
from torch import detach
from cmr.models.utils import set_seeds
from cmr.debug_algs.cl_none import NoneCL, OfflineCL
from cmr.debug_algs.cl_simple_alg import ContinualFinetuning
from cmr.debug_alg... | CMR-main | cmr/debug_algs/run_lifelong_finetune.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from cmr.debug_algs.cl_utils import get_top_interfered_examples, local_adaptation, KeyValueMemoryModule
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from cmr.debug_algs.cl_simple_alg import ContinualFinetuning
... | CMR-main | cmr/debug_algs/cl_mbcl_alg.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import random
import copy
from cmr.models.mybart import MyBart
from cmr.models import run_bart
import torch
import transformers
from cmr.models.utils import (convert_model_to_single_gpu,
freeze_embeds... | CMR-main | cmr/debug_algs/cl_utils.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import copy
import logging
import random
from cmr.debug_algs.cl_utils import _keep_first_answer
from cmr.models import run_bart
from cmr.task_manager.eval_metrics import evaluate_func
import torch
from transformers import BartTokenizer, BartC... | CMR-main | cmr/debug_algs/commons.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# TODO: remove this as we have the offline evaluation function now.
def _eval_before_fixing(self):
# Before Bug-Fixing
assert self.online_debug_results is not None
bug_eval_loader = self.bug_eval_loaders[self.timecode]
bug_bef... | CMR-main | cmr/debug_algs/_legacy_functions.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
from logging import disable
import numpy as np
import torch
from cmr.models.mybart import MyBart
from cmr.models import run_bart
from cmr.models.utils import (convert_model_to_single_gpu,
... | CMR-main | cmr/debug_algs/cl_online_ewc_alg.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
from logging import disable
from cmr.task_manager.eval_metrics import evaluate_func
from cmr.models.bart_with_adapater import BartWithAdapterConfig, MyBartWithAdapter
from cmr.debug_algs.cl_mbcl_alg import KeyVal... | CMR-main | cmr/debug_algs/cl_hypernet_alg.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
from datetime import time
from logging import disable
from cmr.debug_algs.cl_simple_alg import ContinualFinetuning
import numpy as np
import torch
from cmr.models.mybart import MyBart
from cmr.models import run_b... | CMR-main | cmr/debug_algs/cl_none.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import json
import random
from cmr.benchmark_gen import sample_stream_data
from cmr.task_manager.eval_metrics import evaluate_func
def create_training_stream(args, logger):
assert not args.use_dev_stream
# setattr(data_args, "dat... | CMR-main | cmr/debug_algs/distant_supervision/ds_utils.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
"""
This script is used to get the training data for learning a retriever that can get back the most forgettable examples given a batch of error cases to fix.
Input:
- The training streams. ---> get the error cases.
- model.
Output:
... | CMR-main | cmr/debug_algs/distant_supervision/data_collection.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import torch
from tqdm import tqdm
from transformers.modeling_bart import _prepare_bart_decoder_inputs
from transformers.tokenization_utils import trim_batch
import numpy as np
from cmr.debug_algs.cl_utils import _keep_first_answer
def maske... | CMR-main | cmr/debug_algs/index_based/index_utils.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
| CMR-main | cmr/debug_algs/index_based/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from cmr.debug_algs.cl_utils import get_top_interfered_examples, get_virtual_updated_model
from cmr.debug_algs.index_based.IO_each_index import BartIOIndexManager
from cmr.debug_algs.index_based.biencoder import BiEncoderIndexManager
from cmr.... | CMR-main | cmr/debug_algs/index_based/cl_indexed_alg.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
from cmr.debug_algs.cl_utils import _keep_first_answer
from cmr.debug_algs.cl_simple_alg import ContinualFinetuning
from tqdm import tqdm
import torch
from cmr.debug_algs.index_based.index_utils import get_bart_... | CMR-main | cmr/debug_algs/index_based/index_manager.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from argparse import Namespace
from cmr.debug_algs.cl_utils import _keep_first_answer
from cmr.debug_algs.cl_simple_alg import ContinualFinetuning
from tqdm import tqdm
import torch
from cmr.debug_algs.index_based.index_manager import BartInd... | CMR-main | cmr/debug_algs/index_based/IO_each_index.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import argparse
from logging import Logger
import logging
from torch.cuda import memory
from tqdm.utils import disp_trim
from cmr.debug_algs.index_based.index_manager import BartIndexManager
import torch
from torch import Tensor, combination... | CMR-main | cmr/debug_algs/index_based/biencoder.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import altair as alt
from altair.vegalite.v4.schema.core import Axis, Legend
def draw_curve(df, y_scale=[0, 1], fig_title="", y_title="Y Title", x_key="timecode", y_key="em:Q", height=800, width=1150, x_scale=[0, 100], color_dom=None, color_... | CMR-main | cmr/notebooks/draw_utils.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
from enum import unique
from posixpath import split
from re import L
import datasets
import numpy as np
import os
import gzip
import sys
import json
def show_statistics(lines):
len_list = []
for l in lines:
item = json.loads(... | CMR-main | data/data_formatter.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import distutils.command.clean
import os
import shutil
import subprocess
from pathlib import Path
from setuptools import find_packages, se... | agenthive-dev | setup.py |
import robohive
import torchrl
from rlhive import RoboHiveEnv
| agenthive-dev | test/smoke_test.py |
import argparse
import pytest
import torch
from rlhive.rl_envs import RoboHiveEnv
from torchrl.envs import (
CatTensors,
EnvCreator,
ParallelEnv,
R3MTransform,
TransformedEnv,
)
from torchrl.envs.utils import check_env_specs
def test_state_env():
pass
def test_pixel_env():
pass
@pytes... | agenthive-dev | test/test_envs.py |
import torch
def get_available_devices():
devices = [torch.device("cpu")]
n_cuda = torch.cuda.device_count()
if n_cuda > 0:
for i in range(n_cuda):
devices += [torch.device(f"cuda:{i}")]
return devices
| agenthive-dev | test/utils.py |
import argparse
import pytest
import torch
from omegaconf import OmegaConf
from rlhive.sim_algos.helpers import EnvConfig
from rlhive.sim_algos.run import make_env_constructor
from utils import get_available_devices
@pytest.mark.parametrize("device", get_available_devices())
def test_make_r3menv(device):
cfg = E... | agenthive-dev | test/test_helpers.py |
''' Use this script to comapare multiple results \n
Usage: python viz_resulyts.py -j expdir1_group0 expdir2_group0 -j expdir3_group1 expdir4_group1 -k "key1" "key2"...
'''
from vtils.plotting import simple_plot
import argparse
from scipy import signal
import pandas
import glob
def get_files(search_path, file_name)... | agenthive-dev | agents/utils/plot_all_sac.py |
''' Use this script to comapare multiple results \n
Usage: python agents/NPG/plot_all_npg.py -j agents/v0.1/kitchen/NPG/outputs_kitchenJ5c_3.8/ -j agents/v0.1/kitchen/NPG/outputs_kitchenJ5d_3.9/ -j /Users/vikashplus/Projects/mj_envs/kitchen/outputs_kitchenJ8a/ -l 'v0.1(fixed_init)' -l 'v0.1(random_init)' -l 'v0.2(r... | agenthive-dev | agents/utils/plot_all_npg.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from tensordict.tensordict import make_tensordict, TensorDictBase
from torchrl.data import BoundedTensorSpec... | agenthive-dev | rlhive/rl_envs.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Custom env reg for RoboHive usage in TorchRL
# Pixel rendering will be queried by torchrl, so we don't include those keys in visual_obs_ke... | agenthive-dev | rlhive/envs.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from .envs import (
register_franka_envs,
register_hand_envs,
register_kitchen_envs,
register_myo_envs,
)
register_franka_e... | agenthive-dev | rlhive/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Union
import torch
from torch.nn import Identity
from torchrl.data.tensor_specs import (
CompositeS... | agenthive-dev | rlhive/sim_algos/helpers/rrl_transform.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Multi-node distributed data collection with submitit in contexts where jobs can't launch other jobs.
The default configuration will ask f... | agenthive-dev | examples/collection_speed_delayed.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from omegaconf import DictConfig
os.environ["sim_backend"] = "MUJOCO"
def main(args: DictConfig):
import numpy as np
... | agenthive-dev | examples/redq.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from omegaconf import DictConfig
os.environ["sim_backend"] = "MUJOCO"
os.environ["MUJOCO_GL"] = "egl"
def main(args: DictConfi... | agenthive-dev | examples/sac.py |
"""Entry point for RLHive"""
import hydra
from omegaconf import DictConfig
from redq import main as train_redq
from sac import main as train_sac
@hydra.main(config_name="sac_mixed.yaml", config_path="config")
def main(args: DictConfig):
if args.algo == "sac":
train_sac(args)
if args.algo == "redq":
... | agenthive-dev | examples/train.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
os.environ["sim_backend"] = "MUJOCO"
import argparse
import time
import tqdm
from rlhive.rl_envs import RoboHiveEnv
from torch... | agenthive-dev | examples/collection_speed.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from numbers import Number
from typing import Union
import numpy as np
import torch
from tensordict.nn import TensorDictSequen... | agenthive-dev | examples/sac_loss.py |
import json
import random
import torch
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
ret... | agenthive-dev | scripts/bc/misc.py |
"""
Minimize bc loss (MLE, MSE, RWR etc.) with pytorch optimizers
"""
import logging
logging.disable(logging.CRITICAL)
import numpy as np
import torch
import time as timer
from tqdm import tqdm
from misc import tensorize
class BC:
def __init__(self, expert_paths,
policy,
epochs ... | agenthive-dev | scripts/bc/behavior_cloning.py |
"""
Job script to learn policy using BC
"""
import os
import time
from os import environ
environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'
environ['MKL_THREADING_LAYER']='GNU'
import pickle
import yaml
import hydra
import gym
import wandb
import numpy as np
from omegaconf import DictConfig, OmegaConf, ListConfig
from batch_n... | agenthive-dev | scripts/bc/run_bc_h5.py |
import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
class FCNetworkWithBatchNorm(nn.Module):
def __init__(self, obs_dim, act_dim,
hidden_sizes=(64,64),
nonlinearity='relu', # either 'tanh' or 'relu'
dropout=0, # pr... | agenthive-dev | scripts/bc/batch_norm_mlp.py |
import torch
import numpy as np
import torch.nn as nn
import torch.distributions as D
import torch.nn.functional as F
class GMMPolicy(nn.Module):
def __init__(self,
# network_kwargs
input_size,
output_size,
hidden_size=1024,
num_l... | agenthive-dev | scripts/bc/gmm_policy.py |
import torch
from rlhive.rl_envs import RoboHiveEnv
from rlhive.sim_algos.helpers.rrl_transform import RRLTransform
from torchrl.envs import (
CatTensors,
DoubleToFloat,
ObservationNorm,
R3MTransform,
SelectTransform,
TransformedEnv,
)
from torchrl.envs.transforms import Compose, FlattenObservat... | agenthive-dev | scripts/sac_mujoco/test.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import gc
import os
import hydra
import numpy as np
import torch
import torch.cuda
import tqdm
import wandb
from omegaconf import DictCon... | agenthive-dev | scripts/sac_mujoco/sac.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from numbers import Number
from typing import Union
import numpy as np
import torch
from tensordict.nn import TensorDictSequen... | agenthive-dev | scripts/sac_mujoco/sac_loss.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.