python_code stringlengths 0 4.04M | repo_name stringlengths 7 58 | file_path stringlengths 5 147 |
|---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
from typing import Iterable, Optional
from compiler_gym.datasets import Dataset
from compiler_gym.envs.mlir.datasets.... | CompilerGym-development | compiler_gym/envs/mlir/datasets/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Dict, List
from compiler_gym.errors import ServiceError
from compiler_gym.service.proto import ObservationSpace
f... | CompilerGym-development | compiler_gym/views/observation.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compiler_gym.views.observation import ObservationView
from compiler_gym.views.observation_space_spec import ObservationSpaceSpec
from comp... | CompilerGym-development | compiler_gym/views/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from typing import Dict, List
from compiler_gym.datasets import Benchmark
from compiler_gym.spaces.reward import Reward
from c... | CompilerGym-development | compiler_gym/views/reward.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Callable, ClassVar, Optional, Union
from gym.spaces import Space
from compiler_gym.service.proto import Event, Observ... | CompilerGym-development | compiler_gym/views/observation_space_spec.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/filter_group.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Lint as: python3
"""Functions and arguments used in the PyCoder project."""
import ast
import collections
import torch
... | APIsynth-master | Synthesis_incorporation/torch_functions.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch as T
from torch import nn
EMBEDDING_SIZE = 150
SHAPE_EMBEDDING_SIZE = 6
class pycoder_parameters... | APIsynth-master | Synthesis_incorporation/models/models.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Lint as: python3
"""An interface for predicting operations given input and output."""
import abc
import torch
import tor... | APIsynth-master | Synthesis_incorporation/models/prediction_model.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Lint as: python3
"""Creates prediction model from strings."""
import collections
from typing import Callable, Dict, List... | APIsynth-master | Synthesis_incorporation/models/prediction_model_factory.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/benchmarks/stackoverflow_benchmarks.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/value_search/value_search.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/value_search/operation_base.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/value_search/value_search_settings.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/value_search/operation_filtering.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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/L... | APIsynth-master | Synthesis_incorporation/value_search/tensor_member_operations.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/value_search/all_operations.py |
# Copyright 2021 The TF-Coder Authors.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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
#
... | APIsynth-master | Synthesis_incorporation/value_search/function_operation.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from logging import getLogger
import math
import os
import shutil
import time
import torch
import torch.... | DeeperCluster-main | eval_pretrain.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim
import torch.utils.... | DeeperCluster-main | eval_voc_classif.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import os
import apex
import numpy as np
import torch
import torch.distributed as dist
import torch.nn a... | DeeperCluster-main | main.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from logging import getLogger
import os
import time
import numpy as np
from sklearn import metrics
impor... | DeeperCluster-main | eval_linear.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import pickle
import faiss
import torch
import torch.distributed as dist
from to... | DeeperCluster-main | src/clustering.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import signal
import time
logger = getLogger()
def trigger_job_requeue(checkp... | DeeperCluster-main | src/slurm.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
| DeeperCluster-main | src/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import logging
import time
from datetime import timedelta
import pandas as pd
class LogFormatter():
def _... | DeeperCluster-main | src/logger.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import pickle
import time
import faiss
import numpy as np
import torch
import to... | DeeperCluster-main | src/distributed_kmeans.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from logging import getLogger
import os
import pickle
import shutil
import time
import numpy as np
from ... | DeeperCluster-main | src/utils.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import shutil
import time
import numpy as np
import torch
import torch.distribut... | DeeperCluster-main | src/trainer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
from logging import getLogger
import pickle
import numpy as np
import torch
import torch.nn as nn
from src.mo... | DeeperCluster-main | src/model/pretrain.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
| DeeperCluster-main | src/model/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import torch
import torch.nn as nn
import torch.nn.init as init
cfg = {
'D': [64, 64, 'M', 128, 128, 'M... | DeeperCluster-main | src/model/vgg16.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import torch
import torch.nn as nn
import torch.optim
from .vgg16 import VGG16
logger =... | DeeperCluster-main | src/model/model_factory.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
| DeeperCluster-main | src/data/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
from random import randrange
import os
import numpy as np
from sklearn.feature_extraction ... | DeeperCluster-main | src/data/loader.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import zipfile
import numpy as np
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMA... | DeeperCluster-main | src/data/YFCC100M.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import glob
import os
from collections import defaultdict
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD... | DeeperCluster-main | src/data/VOC2007.py |
"""Configuration parameters."""
config_args = {
# training
"seed": 1234,
"epochs": 50,
"batch_size": 256,
"learning_rate": 1e-3,
"eval_every": 10,
"patience": 20,
"optimizer": "RAdam",
"save": 1,
"fast_decoding": 1,
"num_samples": -1,
# model
"dtype": "double",
... | HypHC-master | config.py |
"""Script to visualize the HypHC clustering."""
import argparse
import json
import os
import matplotlib.pyplot as plt
import torch
from datasets.loading import load_data
from model.hyphc import HypHC
from utils.poincare import project
from utils.visualization import plot_tree_from_leaves
if __name__ == "__main__":
... | HypHC-master | visualize.py |
"""Train a hyperbolic embedding model for hierarchical clustering."""
import argparse
import json
import logging
import os
import numpy as np
import torch
import torch.utils.data as data
from tqdm import tqdm
import optim
from config import config_args
from datasets.hc_dataset import HCDataset
from datasets.loading ... | HypHC-master | train.py |
# from distutils.core import setup
from setuptools import setup
from Cython.Build import cythonize
import numpy
setup(
ext_modules=cythonize("mst.pyx", annotate=True, language_level="3"),
include_dirs=[numpy.get_include()],
)
| HypHC-master | mst/setup.py |
import numpy as np
import mst
if __name__ == '__main__':
x = np.array([0, 1, 3, 7, 15], dtype=np.float)
dists = np.abs(x[np.newaxis, :] - x[:, np.newaxis])
print(dists)
print(mst.mst(dists, 5))
print(-dists)
print(mst.mst(-dists, 5))
A = np.arange(16, dtype=np.float).reshape((4, 4))
pr... | HypHC-master | mst/test_mst.py |
import numpy as np
import unionfind
if __name__ == '__main__':
uf = unionfind.UnionFind(5)
uf.merge(np.array([[0, 1], [2, 3], [0, 4], [3, 4]]))
print(uf.parent)
print(uf.tree)
| HypHC-master | unionfind/test_uf.py |
# from distutils.core import setup
from setuptools import setup
from Cython.Build import cythonize
import numpy
setup(
ext_modules=cythonize("unionfind.pyx", annotate=True, language_level="3"),
include_dirs=[numpy.get_include()],
)
| HypHC-master | unionfind/setup.py |
"""Dataset loading."""
import os
import numpy as np
UCI_DATASETS = [
"glass",
"zoo",
"iris",
]
def load_data(dataset, normalize=True):
"""Load dataset.
@param dataset: dataset name
@type dataset: str
@param normalize: whether to normalize features or not
@type normalize: boolean
... | HypHC-master | datasets/loading.py |
"""Triplet sampling utils."""
import numpy as np
from tqdm import tqdm
def samples_triples(n_nodes, num_samples):
num_samples = int(num_samples)
all_nodes = np.arange(n_nodes)
mesh = np.array(np.meshgrid(all_nodes, all_nodes))
pairs = mesh.T.reshape(-1, 2)
pairs = pairs[pairs[:, 0] < pairs[:, 1]]... | HypHC-master | datasets/triples.py |
HypHC-master | datasets/__init__.py | |
"""Hierarchical clustering dataset."""
import logging
import numpy as np
import torch
import torch.utils.data as data
from datasets.triples import generate_all_triples, samples_triples
class HCDataset(data.Dataset):
"""Hierarchical clustering dataset."""
def __init__(self, features, labels, similarities, ... | HypHC-master | datasets/hc_dataset.py |
"""Riemannian optimizers."""
from .radam import RAdam
| HypHC-master | optim/__init__.py |
"""Riemannian adam optimizer geoopt implementation (https://github.com/geoopt/)."""
import torch.optim
from utils.poincare import expmap, egrad2rgrad, inner, project, ptransp
def copy_or_set_(dest, source):
"""
A workaround to respect strides of :code:`dest` when copying :code:`source`
(https://github.c... | HypHC-master | optim/radam.py |
"""Poincare utils functions."""
import torch
from utils.math import arctanh, tanh
MIN_NORM = 1e-15
BALL_EPS = {torch.float32: 4e-3, torch.float64: 1e-5}
def egrad2rgrad(p, dp):
"""Converts Euclidean gradient to Hyperbolic gradient."""
lambda_p = lambda_(p)
dp /= lambda_p.pow(2)
return dp
def lamb... | HypHC-master | utils/poincare.py |
"""LCA construction utils."""
import torch
from utils.poincare import MIN_NORM, hyp_dist_o
def isometric_transform(a, x):
"""Reflection (circle inversion of x through orthogonal circle centered at a)."""
r2 = torch.sum(a ** 2, dim=-1, keepdim=True) - 1.
u = x - a
return r2 / torch.sum(u ** 2, dim=-1... | HypHC-master | utils/lca.py |
"""Evaluation utils."""
import numpy as np
#from mst import reorder
from mst import mst
from utils.tree import descendants_traversal, descendants_count
def dasgupta_cost_iterative(tree, similarities):
""" Non-recursive version of DC. Also works on non-binary trees """
n = len(list(tree.nodes()))
root = ... | HypHC-master | utils/metrics.py |
"""Tree traversal util functions."""
def descendants_traversal(tree):
"""Get all descendants non-recursively, in traversal order."""
n = len(list(tree.nodes()))
root = n - 1
traversal = []
children = [list(tree.neighbors(node)) for node in range(n)] # children remaining to process
is_leaf =... | HypHC-master | utils/tree.py |
"""Decoding utils."""
import time
import numpy as np
import torch
from tqdm import tqdm
from mst import mst
from unionfind import unionfind
from utils.lca import hyp_lca
### Single linkage using MST trick
# @profile
def sl_np_mst(similarities):
n = similarities.shape[0]
ij, _ = mst.mst(similarities, n)
... | HypHC-master | utils/linkage.py |
HypHC-master | utils/__init__.py | |
"""Visualization utils."""
import matplotlib.pyplot as plt
import numpy as np
import torch
from utils.lca import hyp_lca
def mobius_add(x, y):
"""Mobius addition in numpy."""
xy = np.sum(x * y, 1, keepdims=True)
x2 = np.sum(x * x, 1, keepdims=True)
y2 = np.sum(y * y, 1, keepdims=True)
num = (1 + ... | HypHC-master | utils/visualization.py |
"""Math util functions."""
import torch
# ################# tanh ########################
class Artanh(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
x = x.clamp(-1 + 1e-5, 1 - 1e-5)
ctx.save_for_backward(x)
dtype = x.dtype
x = x.double()
return (torch.l... | HypHC-master | utils/math.py |
"""Training utils."""
import argparse
import hashlib
import os
def str2bool(v):
"""Converts string to boolean."""
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
els... | HypHC-master | utils/training.py |
HypHC-master | model/__init__.py | |
"""Hyperbolic hierarchical clustering model."""
import networkx as nx
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.lca import hyp_lca
from utils.linkage import nn_merge_uf_fast_np, sl_from_embeddings
from utils.poincare import project
class HypHC(nn.Module):
"""
Hyperbolic e... | HypHC-master | model/hyphc.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import time
import os
from six.moves import cPickle
import traceback
from co... | connect-caption-and-trace-main | tools/train.py |
connect-caption-and-trace-main | captioning/__init__.py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import torch
import torch.nn as nn
import numpy as np
import torch.optim as optim
import os
import torch.nn.functional as F
import six
from six.moves import cPickle
bad_endings = ['with','... | connect-caption-and-trace-main | captioning/utils/misc.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as uti... | connect-caption-and-trace-main | captioning/utils/eval_utils_orig.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as utils
from eval_utils import getCOC... | connect-caption-and-trace-main | captioning/utils/eval_multi.py |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Copy from fvcore
import logging
import os
from typing import Any
import yaml
from yacs.config import CfgNode as _CfgNode
import io as PathManager
BASE_KEY = "_BASE_"
class CfgNode(_CfgNode):
"""
Our own extended version of :class:`ya... | connect-caption-and-trace-main | captioning/utils/config.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as uti... | connect-caption-and-trace-main | captioning/utils/eval_utils_for_coco_caption.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as uti... | connect-caption-and-trace-main | captioning/utils/eval_utils_show_control_tell.py |
connect-caption-and-trace-main | captioning/utils/__init__.py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from captioning.utils imp... | connect-caption-and-trace-main | captioning/utils/for_debug_eval_spice.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class myResnet(nn.Module):
def __init__(self, resnet):
super(myResnet, self).__init__()
self.resnet = resnet
def forward(self, img, att_size=14):
x = img.unsqueeze(0)
x = self.resnet.conv1(x)
x = self.r... | connect-caption-and-trace-main | captioning/utils/resnet_utils.py |
import torch
import torch.nn as nn
import torchvision.models.resnet
from torchvision.models.resnet import BasicBlock, Bottleneck
class ResNet(torchvision.models.resnet.ResNet):
def __init__(self, block, layers, num_classes=1000):
super(ResNet, self).__init__(block, layers, num_classes)
self.maxpool... | connect-caption-and-trace-main | captioning/utils/resnet.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as uti... | connect-caption-and-trace-main | captioning/utils/eval_utils_joint.py |
from __future__ import print_function
import argparse
def if_use_feat(caption_model):
# Decide if load attention feature according to caption model
if caption_model in ['show_tell', 'all_img', 'fc', 'newfc']:
use_att, use_fc = False, True
elif caption_model == 'language_model':
use_att, us... | connect-caption-and-trace-main | captioning/utils/opts.py |
import torch
import scipy.optimize
import numpy as np
def local_OT(D, window = 0):
window = window
p = D.shape[1]; m = D.shape[2] # p < m, e.g., p = 10, m = 20
# construct the cx, ax=b
x = torch.rand([10,p*m])
A = torch.zeros([p,p*m])
b = torch.ones([p])
for i in range(p):
A[i, (i)... | connect-caption-and-trace-main | captioning/utils/local_optimal_transport.py |
from random import uniform
import numpy as np
from collections import OrderedDict, defaultdict
from itertools import tee
import time
# -----------------------------------------------
def find_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
def compute_div_n(caps,n=1):
aggr_div = []
for ... | connect-caption-and-trace-main | captioning/utils/div_utils.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import time
from collections import OrderedDict
import torch
import sys
try:
sys.path.append("cider")
from pyciderevalcap.ciderD.ciderD import CiderD
from pyciderevalcap.cider.ci... | connect-caption-and-trace-main | captioning/utils/rewards.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as uti... | connect-caption-and-trace-main | captioning/utils/eval_utils.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
from . import misc as uti... | connect-caption-and-trace-main | captioning/utils/eval_utils_caption_generation.py |
# This file contains Transformer network
# Most of the code is copied from http://nlp.seas.harvard.edu/2018/04/03/attention.html
# The cfg name correspondance:
# N=num_layers
# d_model=input_encoding_size
# d_ff=rnn_size
# h is always 8
from __future__ import absolute_import
from __future__ import division
from __fut... | connect-caption-and-trace-main | captioning/models/TransformerModel_trace_generation_caption_to_encoder.py |
# This file contains Transformer network
# Most of the code is copied from http://nlp.seas.harvard.edu/2018/04/03/attention.html
# The cfg name correspondance:
# N=num_layers
# d_model=input_encoding_size
# d_ff=rnn_size
# h is always 8
from __future__ import absolute_import
from __future__ import division
from __fut... | connect-caption-and-trace-main | captioning/models/cachedTransformer.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
from . import utils
from .CaptionModel import CaptionModel
class ShowTellModel(CaptionModel):
def __init__(s... | connect-caption-and-trace-main | captioning/models/ShowTellModel.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel_both_backup_2020_11_11.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel_both.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import copy
import numpy as np
import torch
from .ShowTellModel import ShowTellModel
from .FCModel import FCModel
from .AttModel_both import *
from .TransformerModel_mitr import TransformerModel
#... | connect-caption-and-trace-main | captioning/models/__init__.py |
# This file contains our mirrored Transformer network
# The branch for extracted visual features is implemented in "encoder",
# and then branches for trace and caption are implemented in "decoder"
# The cfg name correspondance:
# N_layer=num_layers
# d_model=input_encoding_size
# d_ff=rnn_size
# h is always 8
from __... | connect-caption-and-trace-main | captioning/models/TransformerModel_mitr.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel_encoder_trace.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel_standard_enco_deco_both.py |
"""
Instruction to use meshed_memory_transformer (https://arxiv.org/abs/1912.08226)
pip install git+https://github.com/ruotianluo/meshed-memory-transformer.git
Note:
Currently m2transformer is not performing as well as original transformer. Not sure why? Still investigating.
"""
from __future__ import absolute_impor... | connect-caption-and-trace-main | captioning/models/M2Transformer.py |
import torch
def repeat_tensors(n, x):
"""
For a tensor of size Bx..., we repeat it n times, and make it Bnx...
For collections, do nested repeat
"""
if torch.is_tensor(x):
x = x.unsqueeze(1) # Bx1x...
x = x.expand(-1, n, *([-1]*len(x.shape[2:]))) # Bxnx...
x = x.reshape(x.s... | connect-caption-and-trace-main | captioning/models/utils.py |
# This file contains ShowAttendTell and AllImg model
# ShowAttendTell is from Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
# https://arxiv.org/abs/1502.03044
# AllImg is a model where
# img feature is concatenated with word embedding at every time step as the input of lstm
from __futur... | connect-caption-and-trace-main | captioning/models/CaptionModel_orig.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel_caption_generation.py |
# Implementation for paper 'Attention on Attention for Image Captioning'
# https://arxiv.org/abs/1908.06954
# RT: Code from original author's repo: https://github.com/husthuaan/AoANet/
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import tor... | connect-caption-and-trace-main | captioning/models/AoAModel.py |
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model
# AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning
# https://arxiv.org/abs/1612.01887
# AdaAttMO is a modified version with maxout lstm
# Att2in is from Self-critical Sequence Training for Image Captioning
#... | connect-caption-and-trace-main | captioning/models/AttModel_orig.py |
# This file contains Transformer network
# Most of the code is copied from http://nlp.seas.harvard.edu/2018/04/03/attention.html
# The cfg name correspondance:
# N=num_layers
# d_model=input_encoding_size
# d_ff=rnn_size
# h is always 8
from __future__ import absolute_import
from __future__ import division
from __fut... | connect-caption-and-trace-main | captioning/models/TransformerModel_standard_enco_deco_both.py |
# This file contains ShowAttendTell and AllImg model
# ShowAttendTell is from Show, Attend and Tell: Neural Image Caption Generation with Visual Attention
# https://arxiv.org/abs/1502.03044
# AllImg is a model where
# img feature is concatenated with word embedding at every time step as the input of lstm
from __futur... | connect-caption-and-trace-main | captioning/models/CaptionModel.py |
# This file is the implementation for ensemble evaluation.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
from .CaptionModel import CaptionM... | connect-caption-and-trace-main | captioning/models/AttEnsemble.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
from . import utils
from .CaptionModel import CaptionModel
class LSTMCore(nn.Module):
def __init__(self, opt... | connect-caption-and-trace-main | captioning/models/FCModel.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.