crossfile_context_retrievalwref dict | prompt stringlengths 252 32.6k | right_context stringlengths 0 81.2k | metadata dict | crossfile_context_retrieval dict | groundtruth stringlengths 5 208 |
|---|---|---|---|---|---|
{
"list": [
{
"filename": "scripts/videocrafter/lvdm/models/modules/lora.py",
"retrieved_chunk": "def change_lora_v2(model, inject_lora=False, lora_scale=1.0, lora_path='', last_time_lora='', last_time_lora_scale=1.0, origin_weight=None):\n # remove lora\n if last_time_lora != '':\n origi... | import os
import torch
from PIL import Image
from videocrafter.lvdm.models.modules.lora import net_load_lora
from videocrafter.lvdm.utils.common_utils import instantiate_from_config
# ------------------------------------------------------------------------------------------
def load_model(config, ckpt_path, gpu_id=N... |
else:
model.cuda()
model.eval()
return model, global_step, epoch
# ------------------------------------------------------------------------------------------
@torch.no_grad()
def get_conditions(prompts, model, batch_size, cond_fps=None,):
if isinstance(prompts, str) or isinstance(prompt... | {
"context_start_lineno": 0,
"file": "scripts/videocrafter/sample_utils.py",
"groundtruth_start_lineno": 34,
"repository": "kabachuha-sd-webui-text2video-20ead10",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/3438"
} | {
"list": [
{
"filename": "scripts/videocrafter/lvdm/models/ddpm3d.py",
"retrieved_chunk": " print(f\"Missing Keys: {missing}\")\n if len(unexpected) > 0:\n print(f\"Unexpected Keys: {unexpected}\")\n def q_mean_variance(self, x_start, t):\n \"\"\"\n Get t... | to(f"cuda:{gpu_id}") |
{
"list": [
{
"filename": "models/autoencoder/modules/encoder.py",
"retrieved_chunk": " def encode(self, x):\n check_mode(self.mode, inspect.stack()[0][3])\n x = self.conv.inference(x)\n for i in range(self.num_blocks):\n x = self.conv_blocks[i].inference(x)\n ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# Reference (https://ieeexplore.ieee.org/document/9625818)
"""Decoder m... |
for i in range(self.num_blocks):
x = self.conv_blocks[i].inference(x)
x = self.conv2.inference(x)
return x | {
"context_start_lineno": 0,
"file": "models/autoencoder/modules/decoder.py",
"groundtruth_start_lineno": 124,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 125,
"task_id": "project_cc_python/3470"
} | {
"list": [
{
"filename": "models/autoencoder/modules/encoder.py",
"retrieved_chunk": " def encode(self, x):\n check_mode(self.mode, inspect.stack()[0][3])\n x = self.conv.inference(x)\n for i in range(self.num_blocks):\n x = self.conv_blocks[i].inference(x)\n ... | inference(z) |
{
"list": [
{
"filename": "scripts/videocrafter/lvdm/models/modules/condition_modules.py",
"retrieved_chunk": " for param in self.parameters():\n param.requires_grad = False\n def forward(self, text):\n batch_encoding = self.tokenizer(text, truncation=True, max_length=self.... | # This code is borrowed from Automatic1111's webui with modifications
# AGPL v3.0 (c) 2023 AUTOMATIC1111, read the full license here
# https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/LICENSE.txt
# Modified by kabachuha and incorporated into the AGPL v3.0 license of the project
# Copyright (C) 2023 ... |
embedded = self.model.token_embedding.wrapped(ids).squeeze(0)
return embedded
def empty_chunk(self):
"""creates an empty PromptChunk and returns it"""
chunk = PromptChunk()
chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1)
chunk.multipli... | {
"context_start_lineno": 0,
"file": "scripts/modelscope/clip_hardcode.py",
"groundtruth_start_lineno": 126,
"repository": "kabachuha-sd-webui-text2video-20ead10",
"right_context_start_lineno": 127,
"task_id": "project_cc_python/3443"
} | {
"list": [
{
"filename": "scripts/videocrafter/lvdm/models/modules/condition_modules.py",
"retrieved_chunk": " return self(text)",
"score": 59.04026327780937
},
{
"filename": "scripts/videocrafter/lvdm/models/autoencoder.py",
"retrieved_chunk": " if x.dim() == ... | device, dtype=torch.int) |
{
"list": [
{
"filename": "codecTrain.py",
"retrieved_chunk": "import logging\nimport argparse\nimport torch\nimport soundfile as sf\nfrom torch.utils.data import DataLoader\nfrom dataloader import CollaterAudio, CollaterAudioPair\nfrom dataloader import SingleDataset, MultiDataset\nfrom models.autoen... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# Reference (https://github.com/kan-bayashi/ParallelWaveGAN/)
import os... |
if self.encoder_config['generator_params']['input_channels'] > 1:
self.multi_channel = True
else:
self.multi_channel = False
# LOAD DATASET
def load_dataset(self, subset, subset_num):
data_path = os.path.join(
self.encoder_config['data']['path']... | {
"context_start_lineno": 0,
"file": "codecTest.py",
"groundtruth_start_lineno": 26,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 27,
"task_id": "project_cc_python/3454"
} | {
"list": [
{
"filename": "codecTrain.py",
"retrieved_chunk": "from models.vocoder.UnivNet import Discriminator as discriminator_univnet\nfrom trainer.autoencoder import Trainer as TrainerAutoEncoder\nfrom trainer.vocoder import Trainer as TrainerVocoder\nfrom trainer.denoise import Trainer as Trainer... | decoder_config.get('model_type', 'symAudioDec') |
{
"list": [
{
"filename": "scripts/videocrafter/lvdm/models/modules/attention_temporal.py",
"retrieved_chunk": " b = x.shape[0]\n q = self.to_q(x)\n context = default(context, x)\n k = self.to_k(context)\n v = self.to_v(context)\n q, k, v = map(lambda t: rearr... | # Part of the implementation is borrowed and modified from stable-diffusion,
# publicly avaialbe at https://github.com/Stability-AI/stablediffusion.
# Copyright 2021-2022 The Alibaba Fundamental Vision Team Authors. All rights reserved.
# https://github.com/modelscope/modelscope/tree/master/modelscope/pipelines/multi_... |
import xformers
out = xformers.ops.memory_efficient_attention(
q, k, v, op=get_xformers_flash_attention_op(q,k,v), attn_bias=mask,
)
elif getattr(cmd_opts, "opt_sdp_no_mem_attention", False) and can_use_sdp:
with torch.backends.cuda.sdp_kernel(ena... | {
"context_start_lineno": 0,
"file": "scripts/modelscope/t2v_model.py",
"groundtruth_start_lineno": 555,
"repository": "kabachuha-sd-webui-text2video-20ead10",
"right_context_start_lineno": 556,
"task_id": "project_cc_python/3446"
} | {
"list": [
{
"filename": "scripts/videocrafter/lvdm/models/modules/attention_temporal.py",
"retrieved_chunk": " mask = repeat(mask, 'b j -> (b h) () j', h=h)\n sim.masked_fill_(~mask, max_neg_value)\n attn = sim.softmax(dim=-1)\n out = einsum('b i j, b j d -> b i d... | device) <= (9, 0)): |
{
"list": [
{
"filename": "codecTrain.py",
"retrieved_chunk": " assert os.path.exists(analyzer_checkpoint), f\"Analyzer {analyzer_checkpoint} does not exist!\"\n analyzer_config = self._load_config(analyzer_checkpoint)\n self._initialize_analyzer(analyzer_config, analy... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import torch
from typing import Union
from models.autoencoder.A... |
return encoder
def _load_decoder(self, checkpoint):
# load config
config = self._load_config(checkpoint)
# load model
if config['model_type'] in ['symAudioDec', 'symAudioDecUniv']:
decoder = generator_audiodec
elif config['model_type'] in ['HiFiGAN', 'U... | {
"context_start_lineno": 0,
"file": "utils/audiodec.py",
"groundtruth_start_lineno": 40,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 41,
"task_id": "project_cc_python/3477"
} | {
"list": [
{
"filename": "codecTrain.py",
"retrieved_chunk": " self.model['analyzer'].load_state_dict(\n torch.load(checkpoint, map_location='cpu')['model']['generator'])\n logging.info(f\"Successfully load analyzer from {checkpoint}.\")\ndef main():\n parser = argparse.Ar... | load_state_dict(torch.load(checkpoint, map_location='cpu')['model']['generator']) |
{
"list": [
{
"filename": "layers/vq_module.py",
"retrieved_chunk": " self.codebook = self.codebook.reshape(-1, self.codebook.size(-1))\n def lookup(self, indices):\n quantized_out = F.embedding(indices, self.codebook) # Num x T x C\n return torch.sum(quantized_out, dim=0,keep... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from layers.vq_module import ResidualVQ
class Quantizer(t... |
return z
| {
"context_start_lineno": 0,
"file": "models/autoencoder/modules/quantizer.py",
"groundtruth_start_lineno": 46,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 47,
"task_id": "project_cc_python/3467"
} | {
"list": [
{
"filename": "codecTest.py",
"retrieved_chunk": " return y\n # INITIAL FOLDER\n def initial_folder(self, subset, output_name):\n # model name\n encoder = os.path.dirname(self.encoder_checkpoint).split('/')[-1]\n decoder = os.path.dirname(self.decoder_chec... | lookup(indices) |
{
"list": [
{
"filename": "trainer/vocoder.py",
"retrieved_chunk": " def _train_step(self, batch):\n \"\"\"Train model one step.\"\"\"\n mode = 'train'\n x = batch\n x = x.to(self.device)\n # fix analyzer\n if not self.fix_analyzer: \n for par... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# Reference (https://github.com/kan-bayashi/ParallelWaveGAN/)
"""Traini... |
parameter.requires_grad = False
for parameter in self.model["generator"].projector.parameters():
parameter.requires_grad = False
for parameter in self.model["generator"].quantizer.parameters():
parameter.requires_grad = False
... | {
"context_start_lineno": 0,
"file": "trainer/autoencoder.py",
"groundtruth_start_lineno": 67,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 68,
"task_id": "project_cc_python/3483"
} | {
"list": [
{
"filename": "trainer/vocoder.py",
"retrieved_chunk": " logging.info(\"Analyzer is fixed!\")\n self.model[\"analyzer\"].eval()\n #######################\n # Generator #\n #######################\n if self.steps > self.generator_start... | model["generator"].encoder.parameters(): |
{
"list": [
{
"filename": "models/autoencoder/AudioDec.py",
"retrieved_chunk": " self.decode(zq)\n def encode(self, x):\n (batch, channel, length) = x.size()\n if channel != self.input_channels: \n x = x.reshape(-1, self.input_channels, length) # (B, C, T) -> (B', C'... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
### useage ###
# (run w/ gpu): python demoFile.py --model libritts_v1 -i ... |
y = audiodec.decoder.decode(zq)[:, :, :x.size(-1)]
y = y.squeeze(1).transpose(1, 0).cpu().numpy() # T x C
sf.write(
args.output,
y,
fs,
"PCM_16",
)
print(f"Output {args.output}!")
if __name__ == "__main__":
main()
| {
"context_start_lineno": 0,
"file": "demoFile.py",
"groundtruth_start_lineno": 59,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 60,
"task_id": "project_cc_python/3451"
} | {
"list": [
{
"filename": "demoStream.py",
"retrieved_chunk": " tx_device=tx_device,\n rx_encoder=audiodec.rx_encoder,\n decoder=audiodec.decoder,\n rx_device=rx_device,\n )\n streamer.enable_filedump(\n input_stream_file=args.input,\n output_stream_file... | rx_encoder.lookup(idx) |
{
"list": [
{
"filename": "codecTrain.py",
"retrieved_chunk": "import logging\nimport argparse\nimport torch\nimport soundfile as sf\nfrom torch.utils.data import DataLoader\nfrom dataloader import CollaterAudio, CollaterAudioPair\nfrom dataloader import SingleDataset, MultiDataset\nfrom models.autoen... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# Reference (https://github.com/kan-bayashi/ParallelWaveGAN/)
import os... |
self.decoder_type = self.decoder_config.get('model_type', 'symAudioDec')
if self.encoder_config['generator_params']['input_channels'] > 1:
self.multi_channel = True
else:
self.multi_channel = False
# LOAD DATASET
def load_dataset(self, subset, subset_num):
... | {
"context_start_lineno": 0,
"file": "codecTest.py",
"groundtruth_start_lineno": 25,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 26,
"task_id": "project_cc_python/3453"
} | {
"list": [
{
"filename": "codecTrain.py",
"retrieved_chunk": "from models.vocoder.UnivNet import Discriminator as discriminator_univnet\nfrom trainer.autoencoder import Trainer as TrainerAutoEncoder\nfrom trainer.vocoder import Trainer as TrainerVocoder\nfrom trainer.denoise import Trainer as Trainer... | encoder_config.get('model_type', 'symAudioDec') |
{
"list": [
{
"filename": "trainer/denoise.py",
"retrieved_chunk": " # fix codebook\n self.model[\"generator\"].quantizer.codebook.eval()\n # initialize generator loss\n gen_loss = 0.0\n # main genertor operation\n y_nc, zq, z, vqloss, perplexity = self.model[... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from layers.vq_module import ResidualVQ
class Quantizer(t... |
zq = zq.transpose(2, 1)
return zq, indices
def encode(self, z):
zq, indices = self.codebook.forward_index(z.transpose(2, 1), flatten_idx=True)
return zq, indices
def decode(self, indices):
z = self.codebook.lookup(indices)
return z
| {
"context_start_lineno": 0,
"file": "models/autoencoder/modules/quantizer.py",
"groundtruth_start_lineno": 37,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 38,
"task_id": "project_cc_python/3466"
} | {
"list": [
{
"filename": "trainer/denoise.py",
"retrieved_chunk": " # metric loss\n gen_loss += self._metric_loss(y_nc, x_c, mode=mode)\n # update generator\n self._record_loss('generator_loss', gen_loss, mode=mode)\n self._update_generator(gen_loss)\n # upda... | forward_index(z.transpose(2, 1)) |
{
"list": [
{
"filename": "models/autoencoder/AudioDec.py",
"retrieved_chunk": " self.decode(zq)\n def encode(self, x):\n (batch, channel, length) = x.size()\n if channel != self.input_channels: \n x = x.reshape(-1, self.input_channels, length) # (B, C, T) -> (B', C'... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
### useage ###
# (run w/ gpu): python demoFile.py --model libritts_v1 -i ... |
y = y.squeeze(1).transpose(1, 0).cpu().numpy() # T x C
sf.write(
args.output,
y,
fs,
"PCM_16",
)
print(f"Output {args.output}!")
if __name__ == "__main__":
main()
| {
"context_start_lineno": 0,
"file": "demoFile.py",
"groundtruth_start_lineno": 60,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 61,
"task_id": "project_cc_python/3452"
} | {
"list": [
{
"filename": "demoStream.py",
"retrieved_chunk": " tx_device=tx_device,\n rx_encoder=audiodec.rx_encoder,\n decoder=audiodec.decoder,\n rx_device=rx_device,\n )\n streamer.enable_filedump(\n input_stream_file=args.input,\n output_stream_file... | decoder.decode(zq)[:, :, :x.size(-1)] |
{
"list": [
{
"filename": "tigrisdb/search.py",
"retrieved_chunk": "from tigrisdb.types import ClientConfig\nfrom tigrisdb.utils import schema_to_bytes\nclass Search:\n __client: SearchStub\n __config: ClientConfig\n def __init__(self, client: SearchStub, config: ClientConfig):\n self.... | import os
from unittest import TestCase
from unittest.mock import MagicMock, patch
import grpc
from tigrisdb.client import TigrisClient
from tigrisdb.types import ClientConfig
@patch("grpc.channel_ready_future")
class TigrisClientTest(TestCase):
def setUp(self) -> None:
self.done_future = MagicMock(grpc... | {
"context_start_lineno": 0,
"file": "tests/test_client.py",
"groundtruth_start_lineno": 132,
"repository": "tigrisdata-tigris-client-python-667d484",
"right_context_start_lineno": 133,
"task_id": "project_cc_python/3528"
} | {
"list": [
{
"filename": "tigrisdb/search.py",
"retrieved_chunk": " return self.__config.project\n def create_or_update_index(self, name: str, schema: dict) -> SearchIndex:\n req = CreateOrUpdateIndexRequest(\n project=self.project, name=name, schema=schema_to_bytes(schema... | get_vector_store("v1").name) | |
{
"list": [
{
"filename": "bin/stream.py",
"retrieved_chunk": " # encoder\n self.tx_encoder = tx_encoder\n self.tx_device = tx_device\n print(f'Encoder device: {tx_device}')\n # decoder\n self.rx_encoder = rx_encoder\n self.decoder = decoder\n se... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import torch
from typing import Union
from models.autoencoder.A... |
def assign_model(model):
if model == 'libritts_v1':
sample_rate = 24000
tx_steps = 500000
rx_steps = 500000
encoder_checkpoint = os.path.join('exp', 'autoencoder', 'symAD_libritts_24000_hop300', f"checkpoint-{tx_steps}steps.pkl")
decoder_checkpoint = os.path.join('exp'... | {
"context_start_lineno": 0,
"file": "utils/audiodec.py",
"groundtruth_start_lineno": 102,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 103,
"task_id": "project_cc_python/3481"
} | {
"list": [
{
"filename": "bin/stream.py",
"retrieved_chunk": " self.encoder_queue = queue.Queue()\n self.decoder_queue = queue.Queue()\n self.output_queue = queue.Queue()\n # file dump if requested\n self.input_dump = []\n self.output_dump = []\n self.... | decoder.decode(x) |
{
"list": [
{
"filename": "tigrisdb/types/filters/selector.py",
"retrieved_chunk": " @property\n def operator(self):\n return \"\"\n def query(self) -> Dict:\n return {self.field: self.value}\nclass Not(SelectorFilter):\n @property\n def operator(self):\n return \"$... | import abc
from typing import Any, Dict, Union
from tigrisdb.types import BaseOperator, Serializable
from .selector import SelectorFilter
class LogicalFilter(Serializable, BaseOperator, abc.ABC):
def __init__(self, *args: Union[SelectorFilter, Any]):
self.filters = args
def query(self) -> Dict:
... |
class And(LogicalFilter):
@property
def operator(self):
return "$and"
class Or(LogicalFilter):
@property
def operator(self):
return "$or"
| {
"context_start_lineno": 0,
"file": "tigrisdb/types/filters/logical.py",
"groundtruth_start_lineno": 18,
"repository": "tigrisdata-tigris-client-python-667d484",
"right_context_start_lineno": 19,
"task_id": "project_cc_python/3520"
} | {
"list": [
{
"filename": "tigrisdb/types/filters/selector.py",
"retrieved_chunk": " @property\n def operator(self):\n return \"\"\n def query(self) -> Dict:\n return {self.field: self.value}\nclass Not(SelectorFilter):\n @property\n def operator(self):\n return \"$... | operator: gen} |
{
"list": [
{
"filename": "tests/test_types_client_config.py",
"retrieved_chunk": " },\n )\n def test_init_with_partial_env(self):\n conf = ClientConfig(project=\"project\")\n self.assertEqual(conf.project, \"project\")\n self.assertEqual(conf.client_id, \"client_env\... | import os
from typing import Union
import grpc
from api.generated.server.v1.api_pb2_grpc import TigrisStub
from api.generated.server.v1.search_pb2_grpc import SearchStub
from tigrisdb.auth import AuthGateway
from tigrisdb.database import Database
from tigrisdb.errors import TigrisException
from tigrisdb.search import... |
else:
config = conf
if config.server_url.startswith("https://"):
config.server_url = config.server_url.replace("https://", "")
if config.server_url.startswith("http://"):
config.server_url = config.server_url.replace("http://", "")
if ":" not in conf... | {
"context_start_lineno": 0,
"file": "tigrisdb/client.py",
"groundtruth_start_lineno": 29,
"repository": "tigrisdata-tigris-client-python-667d484",
"right_context_start_lineno": 30,
"task_id": "project_cc_python/3517"
} | {
"list": [
{
"filename": "tigrisdb/database.py",
"retrieved_chunk": " return self.__config.project\n @property\n def branch(self):\n return self.__config.branch\n def create_or_update_collection(self, name: str, schema: dict) -> Collection:\n req = CreateOrUpdateCollecti... | merge(**conf) |
{
"list": [
{
"filename": "tests/ConversationHistoryTest.py",
"retrieved_chunk": " self.functions = FunctionRegistry()\n self.tokenizer = GPT3Tokenizer()\n def test_constructor(self):\n section = ConversationHistory('history')\n self.assertEqual(section.variable, 'histor... | from promptrix.promptrixTypes import Message, PromptFunctions, PromptMemory, RenderedPromptSection, Tokenizer
from promptrix.PromptSectionBase import PromptSectionBase
from promptrix.Utilities import Utilities
class ConversationHistory(PromptSectionBase):
def __init__(self, variable, tokens=1.0, required=False, us... |
separatorLength = len(tokenizer.encode(self.separator))
lines = []
for i in range(len(history)-1, -1, -1):
msg = history[i]
message = Utilities.to_string(tokenizer, msg['content'])
prefix = self.userPrefix if msg['role'] == 'user' else self.assistantPrefix
... | {
"context_start_lineno": 0,
"file": "src/promptrix/ConversationHistory.py",
"groundtruth_start_lineno": 15,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 16,
"task_id": "project_cc_python/3555"
} | {
"list": [
{
"filename": "tests/ConversationHistoryTest.py",
"retrieved_chunk": " self.assertEqual(section.text_prefix, \"\")\n async def test_renderAsMessages(self):\n section = ConversationHistory('history', 100)\n rendered = await section.renderAsMessages(self.memory, self.... | tokens, maxTokens) if self.tokens > 1.0 else maxTokens |
{
"list": [
{
"filename": "bin/stream.py",
"retrieved_chunk": " # encoder\n self.tx_encoder = tx_encoder\n self.tx_device = tx_device\n print(f'Encoder device: {tx_device}')\n # decoder\n self.rx_encoder = rx_encoder\n self.decoder = decoder\n se... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import torch
from typing import Union
from models.autoencoder.A... |
return self.decoder.decode(x)
def assign_model(model):
if model == 'libritts_v1':
sample_rate = 24000
tx_steps = 500000
rx_steps = 500000
encoder_checkpoint = os.path.join('exp', 'autoencoder', 'symAD_libritts_24000_hop300', f"checkpoint-{tx_steps}steps.pkl")
d... | {
"context_start_lineno": 0,
"file": "utils/audiodec.py",
"groundtruth_start_lineno": 101,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 102,
"task_id": "project_cc_python/3480"
} | {
"list": [
{
"filename": "bin/stream.py",
"retrieved_chunk": " self.encoder_queue = queue.Queue()\n self.decoder_queue = queue.Queue()\n self.output_queue = queue.Queue()\n # file dump if requested\n self.input_dump = []\n self.output_dump = []\n self.... | rx_encoder.lookup(x) |
{
"list": [
{
"filename": "tests/ConversationHistoryTest.py",
"retrieved_chunk": " self.functions = FunctionRegistry()\n self.tokenizer = GPT3Tokenizer()\n def test_constructor(self):\n section = ConversationHistory('history')\n self.assertEqual(section.variable, 'histor... | from promptrix.promptrixTypes import Message, PromptFunctions, PromptMemory, RenderedPromptSection, Tokenizer
from promptrix.PromptSectionBase import PromptSectionBase
from promptrix.Utilities import Utilities
class ConversationHistory(PromptSectionBase):
def __init__(self, variable, tokens=1.0, required=False, us... |
prefix = self.userPrefix if msg['role'] == 'user' else self.assistantPrefix
line = prefix + message.content
length = len(tokenizer.encode(line)) + (separatorLength if len(lines) > 0 else 0)
if len(lines) == 0 and self.required:
tokens += length
... | {
"context_start_lineno": 0,
"file": "src/promptrix/ConversationHistory.py",
"groundtruth_start_lineno": 20,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 21,
"task_id": "project_cc_python/3557"
} | {
"list": [
{
"filename": "tests/ConversationHistoryTest.py",
"retrieved_chunk": " self.assertEqual(section.text_prefix, \"\")\n async def test_renderAsMessages(self):\n section = ConversationHistory('history', 100)\n rendered = await section.renderAsMessages(self.memory, self.... | to_string(tokenizer, msg['content']) |
{
"list": [
{
"filename": "src/promptrix/PromptSectionBase.py",
"retrieved_chunk": " length -= len(encoded)\n if length < self.tokens:\n delta = self.tokens - length\n truncated = tokenizer.decode(encoded[:delta])\n ... | #from promptrixTypes import *
from promptrix.PromptSectionBase import PromptSectionBase
from promptrix.Utilities import Utilities
from typing import List, Callable, Any
from enum import Enum
import asyncio
def get_mem_str(memory, value):
#print (f'***** TemplateSection create_variable_renderer memory {memory}, val... |
def parse_template(self):
part = ''
state = ParseState.IN_TEXT
string_delim = ''
skip_next = False
for i in range(len(self.template)):
if skip_next:
skip_next = False
continue
char = self.template[i]
if sta... | {
"context_start_lineno": 0,
"file": "src/promptrix/TemplateSection.py",
"groundtruth_start_lineno": 32,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 33,
"task_id": "project_cc_python/3553"
} | {
"list": [
{
"filename": "src/promptrix/PromptSectionBase.py",
"retrieved_chunk": " length -= len(encoded)\n if length < self.tokens:\n delta = self.tokens - length\n truncated = tokenizer.decode(encoded[:delta])\n ... | return_messages([{'role': self.role, 'content': text}], length, tokenizer, max_tokens) |
{
"list": [
{
"filename": "src/promptrix/FunctionRegistry.py",
"retrieved_chunk": " return fn\n def addFunction(self, name: str, value: Callable) -> None:\n if self.has(name):\n raise Exception(f\"Function '{name}' already exists.\")\n self._functions[name] = value\n... | #from promptrixTypes import *
from promptrix.PromptSectionBase import PromptSectionBase
from promptrix.Utilities import Utilities
from typing import List, Callable, Any
from enum import Enum
import asyncio
def get_mem_str(memory, value):
#print (f'***** TemplateSection create_variable_renderer memory {memory}, val... |
def create_function_renderer(self, param: str) -> Callable[['PromptMemory', 'PromptFunctions', 'Tokenizer', int], 'Promise[str]']:
name = None
args = []
part = ''
def save_part():
nonlocal part, name, args
if len(part) > 0:
if not name:
... | {
"context_start_lineno": 0,
"file": "src/promptrix/TemplateSection.py",
"groundtruth_start_lineno": 84,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 85,
"task_id": "project_cc_python/3554"
} | {
"list": [
{
"filename": "src/promptrix/FunctionRegistry.py",
"retrieved_chunk": " return fn\n def addFunction(self, name: str, value: Callable) -> None:\n if self.has(name):\n raise Exception(f\"Function '{name}' already exists.\")\n self._functions[name] = value\n... | to_string(tokenizer, memory.get(name))) |
{
"list": [
{
"filename": "src/promptrix/LayoutEngine.py",
"retrieved_chunk": " True,\n tokenizer\n )\n output = [section.layout.output for section in layout if section.layout]\n text = self.separator.join(output)\n return RenderedPromptSection(text, l... | from typing import List
from promptrix.promptrixTypes import Message, PromptFunctions, PromptMemory, PromptSection, RenderedPromptSection, Tokenizer
from promptrix.PromptSectionBase import PromptSectionBase
from promptrix.LayoutEngine import LayoutEngine
class GroupSection(PromptSectionBase):
def __init__(self, se... | {
"context_start_lineno": 0,
"file": "src/promptrix/GroupSection.py",
"groundtruth_start_lineno": 18,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 19,
"task_id": "project_cc_python/3562"
} | {
"list": [
{
"filename": "src/promptrix/LayoutEngine.py",
"retrieved_chunk": " True,\n tokenizer\n )\n output = [section.layout.output for section in layout if section.layout]\n text = self.separator.join(output)\n return RenderedPromptSection(text, l... | return_messages([{'role': self.role, 'content': output}], length, tokenizer, maxTokens) | |
{
"list": [
{
"filename": "trainer/autoencoder.py",
"retrieved_chunk": " # Generator #\n #######################\n if self.generator_train:\n # initialize generator loss\n gen_loss = 0.0\n # main genertor operation\n y_, zq, z,... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# Reference (https://github.com/kan-bayashi/ParallelWaveGAN/)
"""Traini... |
# update generator
self._record_loss('generator_loss', gen_loss, mode=mode)
self._update_generator(gen_loss)
# update counts
self.steps += 1
self.tqdm.update(1)
self._check_train_finish()
@torch.no_grad()
def _eval_step(self, batch):
"""Single... | {
"context_start_lineno": 0,
"file": "trainer/denoise.py",
"groundtruth_start_lineno": 74,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 75,
"task_id": "project_cc_python/3494"
} | {
"list": [
{
"filename": "trainer/autoencoder.py",
"retrieved_chunk": " gen_loss += self._vq_loss(vqloss, mode=mode)\n # metric loss\n gen_loss += self._metric_loss(y_, x, mode=mode)\n # adversarial loss\n if self.discriminator_train:\n ... | _metric_loss(y_nc, x_c, mode=mode) |
{
"list": [
{
"filename": "src/promptrix/TemplateSection.py",
"retrieved_chunk": " #print(f'***** TemplateSection init template {self._parts}')\n def renderAsMessages(self, memory: 'PromptMemory', functions: 'PromptFunctions', tokenizer: 'Tokenizer', max_tokens: int) -> 'RenderedPromptSectio... | from promptrix.promptrixTypes import PromptMemory, PromptFunctions, Tokenizer, RenderedPromptSection, Message
from promptrix.PromptSectionBase import PromptSectionBase
class TextSection(PromptSectionBase):
def __init__(self, text: str, role: str, tokens: int = -1, required: bool = True, separator: str = '\n', text... | {
"context_start_lineno": 0,
"file": "src/promptrix/TextSection.py",
"groundtruth_start_lineno": 14,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 15,
"task_id": "project_cc_python/3560"
} | {
"list": [
{
"filename": "src/promptrix/GroupSection.py",
"retrieved_chunk": " def renderAsMessages(self, memory: PromptMemory, functions: PromptFunctions, tokenizer: Tokenizer, maxTokens: int):\n # Render sections to text\n renderedPromptSection = self._layoutEngine.renderAsText(mem... | return_messages([{'role': self.role, 'content': self.text}], self._length, tokenizer, max_tokens) | |
{
"list": [
{
"filename": "trainer/autoencoder.py",
"retrieved_chunk": " self.discriminator_start = config.get('start_steps', {}).get('discriminator', 200000)\n def _train_step(self, batch):\n \"\"\"Single step of training.\"\"\"\n mode = 'train'\n x = batch\n x =... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# Reference (https://github.com/kan-bayashi/ParallelWaveGAN/)
"""Traini... |
parameter.requires_grad = False
self.fix_analyzer = True
logging.info("Analyzer is fixed!")
self.model["analyzer"].eval()
#######################
# Generator #
#######################
if self.steps > self.generator_start:
... | {
"context_start_lineno": 0,
"file": "trainer/vocoder.py",
"groundtruth_start_lineno": 55,
"repository": "facebookresearch-AudioDec-9b49838",
"right_context_start_lineno": 56,
"task_id": "project_cc_python/3500"
} | {
"list": [
{
"filename": "trainer/autoencoder.py",
"retrieved_chunk": " self.generator_train = True\n # check discriminator step\n if self.steps < self.discriminator_start:\n self.discriminator_train = False\n else:\n self.discriminator_train = Tr... | model["analyzer"].parameters(): |
{
"list": [
{
"filename": "tests/FunctionRegistryTest.py",
"retrieved_chunk": " memory = VolatileMemory()\n tokenizer = GPT3Tokenizer()\n called = False\n def test_func(memory, functions, tokenizer, args):\n nonlocal called\n self.assertEqual(len(args)... | import unittest
from promptrix.TemplateSection import TemplateSection
from promptrix.VolatileMemory import VolatileMemory
from promptrix.FunctionRegistry import FunctionRegistry
from promptrix.GPT3Tokenizer import GPT3Tokenizer
import asyncio
class TestTemplateSection(unittest.TestCase):
def setUp(self):
s... |
self.assertEqual(section.role, "user")
self.assertEqual(section.tokens, -1)
self.assertEqual(section.required, True)
self.assertEqual(section.separator, "\n")
section = TemplateSection("Hello World", "system", 2.0, False)
self.assertEqual(section.template, "Hello World"... | {
"context_start_lineno": 0,
"file": "tests/TemplateSectionTest.py",
"groundtruth_start_lineno": 21,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 22,
"task_id": "project_cc_python/3568"
} | {
"list": [
{
"filename": "tests/FunctionRegistryTest.py",
"retrieved_chunk": " })\n registry.invoke(\"test\", memory, registry, tokenizer, [\"Hello World\"])\n self.assertTrue(called)\n with self.assertRaises(Exception):\n registry = FunctionRegistry()\n ... | template, "Hello World") |
{
"list": [
{
"filename": "tests/FunctionRegistryTest.py",
"retrieved_chunk": " memory = VolatileMemory()\n tokenizer = GPT3Tokenizer()\n called = False\n def test_func(memory, functions, tokenizer, args):\n nonlocal called\n self.assertEqual(len(args)... | import unittest
from promptrix.TemplateSection import TemplateSection
from promptrix.VolatileMemory import VolatileMemory
from promptrix.FunctionRegistry import FunctionRegistry
from promptrix.GPT3Tokenizer import GPT3Tokenizer
import asyncio
class TestTemplateSection(unittest.TestCase):
def setUp(self):
s... |
self.assertEqual(section.tokens, -1)
self.assertEqual(section.required, True)
self.assertEqual(section.separator, "\n")
section = TemplateSection("Hello World", "system", 2.0, False)
self.assertEqual(section.template, "Hello World")
self.assertEqual(section.role, "syste... | {
"context_start_lineno": 0,
"file": "tests/TemplateSectionTest.py",
"groundtruth_start_lineno": 22,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 23,
"task_id": "project_cc_python/3569"
} | {
"list": [
{
"filename": "tests/FunctionRegistryTest.py",
"retrieved_chunk": " })\n registry.invoke(\"test\", memory, registry, tokenizer, [\"Hello World\"])\n self.assertTrue(called)\n with self.assertRaises(Exception):\n registry = FunctionRegistry()\n ... | role, "user") |
{
"list": [
{
"filename": "tests/TemplateSectionTest.py",
"retrieved_chunk": " })\n self.functions = FunctionRegistry({\n 'test': lambda memory, functions, tokenizer, args: 'Hello World',\n 'test2': lambda memory, functions, tokenizer, args: args[0],\n 't... | import unittest
from FunctionRegistry import FunctionRegistry
from VolatileMemory import VolatileMemory
from GPT3Tokenizer import GPT3Tokenizer
class TestFunctionRegistry(unittest.TestCase):
def test_constructor(self):
registry = FunctionRegistry()
self.assertIsNotNone(registry)
self.assert... |
self.assertTrue(called)
with self.assertRaises(Exception):
registry = FunctionRegistry()
registry.invoke("test", memory, registry, tokenizer, ["Hello World"])
if __name__ == '__main__':
unittest.main()
| {
"context_start_lineno": 0,
"file": "tests/FunctionRegistryTest.py",
"groundtruth_start_lineno": 62,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 63,
"task_id": "project_cc_python/3586"
} | {
"list": [
{
"filename": "tests/TemplateSectionTest.py",
"retrieved_chunk": " self.assertEqual(section.role, \"user\")\n self.assertEqual(section.tokens, -1)\n self.assertEqual(section.required, True)\n self.assertEqual(section.separator, \"\\n\")\n section = Templa... | invoke("test", memory, registry, tokenizer, ["Hello World"]) |
{
"list": [
{
"filename": "src/promptrix/ConversationHistory.py",
"retrieved_chunk": " return RenderedPromptSection(output=self.separator.join(lines), length=tokens, tooLong=tokens > maxTokens)\n def renderAsMessages(self, memory, functions, tokenizer, maxTokens):\n history = memory.g... | import aiounittest, unittest
from promptrix.ConversationHistory import ConversationHistory
from promptrix.VolatileMemory import VolatileMemory
from promptrix.FunctionRegistry import FunctionRegistry
from promptrix.GPT3Tokenizer import GPT3Tokenizer
import asyncio
class TestConversationHistory(aiounittest.AsyncTestCase... |
self.assertEqual(section.required, False)
self.assertEqual(section.separator, "\n")
self.assertEqual(section.userPrefix, "user")
self.assertEqual(section.assistantPrefix, "assistant")
self.assertEqual(section.text_prefix, "")
async def test_renderAsMessages(self):
s... | {
"context_start_lineno": 0,
"file": "tests/ConversationHistoryTest.py",
"groundtruth_start_lineno": 27,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/3576"
} | {
"list": [
{
"filename": "tests/PromptSectionBaseTest.py",
"retrieved_chunk": " self.assertEqual(section.required, True)\n self.assertEqual(section.separator, \"\\n\")\n self.assertEqual(section.text_prefix, \"\")\n async def test_renderAsMessages(self):\n section = Tes... | tokens, 1.0) |
{
"list": [
{
"filename": "tests/TemplateSectionTest.py",
"retrieved_chunk": " self.assertEqual(section.role, \"user\")\n self.assertEqual(section.tokens, -1)\n self.assertEqual(section.required, True)\n self.assertEqual(section.separator, \"\\n\")\n section = Templa... | import aiounittest, unittest
from promptrix.ConversationHistory import ConversationHistory
from promptrix.VolatileMemory import VolatileMemory
from promptrix.FunctionRegistry import FunctionRegistry
from promptrix.GPT3Tokenizer import GPT3Tokenizer
import asyncio
class TestConversationHistory(aiounittest.AsyncTestCase... |
self.assertEqual(section.assistantPrefix, "assistant")
self.assertEqual(section.text_prefix, "")
async def test_renderAsMessages(self):
section = ConversationHistory('history', 100)
rendered = await section.renderAsMessages(self.memory, self.functions, self.tokenizer, 100)
... | {
"context_start_lineno": 0,
"file": "tests/ConversationHistoryTest.py",
"groundtruth_start_lineno": 30,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/3579"
} | {
"list": [
{
"filename": "tests/TemplateSectionTest.py",
"retrieved_chunk": " async def test_renderAsMessages(self):\n section = TemplateSection(\"Hello World\", \"user\")\n rendered = await section.renderAsMessages(self.memory, self.functions, self.tokenizer, 100)\n self.asse... | userPrefix, "user") |
{
"list": [
{
"filename": "src/promptrix/ConversationHistory.py",
"retrieved_chunk": " return RenderedPromptSection(output=self.separator.join(lines), length=tokens, tooLong=tokens > maxTokens)\n def renderAsMessages(self, memory, functions, tokenizer, maxTokens):\n history = memory.g... | import aiounittest, unittest
from promptrix.ConversationHistory import ConversationHistory
from promptrix.VolatileMemory import VolatileMemory
from promptrix.FunctionRegistry import FunctionRegistry
from promptrix.GPT3Tokenizer import GPT3Tokenizer
import asyncio
class TestConversationHistory(aiounittest.AsyncTestCase... |
self.assertEqual(section.tokens, 1.0)
self.assertEqual(section.required, False)
self.assertEqual(section.separator, "\n")
self.assertEqual(section.userPrefix, "user")
self.assertEqual(section.assistantPrefix, "assistant")
self.assertEqual(section.text_prefix, "")
as... | {
"context_start_lineno": 0,
"file": "tests/ConversationHistoryTest.py",
"groundtruth_start_lineno": 26,
"repository": "Stevenic-promptrix-py-6ed7059",
"right_context_start_lineno": 27,
"task_id": "project_cc_python/3575"
} | {
"list": [
{
"filename": "tests/PromptSectionBaseTest.py",
"retrieved_chunk": " self.assertEqual(section.required, True)\n self.assertEqual(section.separator, \"\\n\")\n self.assertEqual(section.text_prefix, \"\")\n async def test_renderAsMessages(self):\n section = Tes... | variable, 'history') |
{
"list": [
{
"filename": "algo/value_network.py",
"retrieved_chunk": " state.nodes[i][0] = points[i].vec.x\n state.nodes[i][1] = points[i].vec.y\n if args.env_dims == 3:\n state.nodes[i][2] = points[i].vec.z\n for e in edges:\n if (np.... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
edges[(j, i)]._area = self.state.edges[i][j]
edges[(j, i)].len = getlen2(points[j], points[i])
edges_list.append((j, i))
if (self.env_mode == 'DT'):
if self.state.edges[i][j][0] > 0:
d = ... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 206,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 207,
"task_id": "project_cc_python/3546"
} | {
"list": [
{
"filename": "algo/value_network.py",
"retrieved_chunk": " if (args.env_mode == 'DT'):\n state.edges[i][j][0] = e.d\n state.edges[j][i][0] = e.d\n state.edges[i][j][1] = e.t\n state.edges[j][i][1] =... | edges[i][j] > 0: |
{
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " mind = arealist[-1][4]\n for i in range(len(e)):\n if (new_e.u == e[i].v or new_e.u == e[i].u or new_e.v == e[i].v or new_e.v == e[i].u): continue\n _, _, dis = closestDistanceBetweenLines(p[new_e.u].Poi... | import sys, os
import openseespy.opensees as op
import numpy as np
import math
from truss_envs.dynamic import DynamicModel
from utils.utils import Bar, getlen2
def Envs_init(args__):
global args
global truss_env
args = args__
'''
global E
global pho
global Sigma_T
global Sigma_C
glo... |
dis_value = np.sum(dis_value)
stress_value = np.sum(stress_value)
buckle_value = np.sum(buckle_value)
slenderness_value = np.sum(slenderness_value)
longer_value = np.sum(longer_value)
shorter_value = np.sum(shorter_value)
cross_value = np.sum(cross_value)
if (mode == 'check'):
... | {
"context_start_lineno": 0,
"file": "truss_envs/reward.py",
"groundtruth_start_lineno": 78,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 79,
"task_id": "project_cc_python/3541"
} | {
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " _, _, dis = closestDistanceBetweenLines(p[new_e.u].Point2np(), p[new_e.v].Point2np(), p[e[i].u].Point2np(), p[e[i].v].Point2np(), clampAll = True)\n if (args.env_dims == 2):\n mina = min(mina, (dis - e[... | run(p, e, mode = mode) |
{
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " self.edges = -np.ones((num_points, num_points, 2), dtype=np.float64)\n def obs(self, nonexistent_edge = -1):\n r'''\n transfer self.state to observation\n :param nonexistent_edge: area value of no... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
ret[0] = False # Not in valid observation
if (self.env_mode == 'DT'):
if not self.state_observation_space.contains(self.state.obs(nonexistent_edge=self.state_observation_space.low[-2:])):
ret[0] = False # Not in valid observation
for i in range(se... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 183,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 184,
"task_id": "project_cc_python/3542"
} | {
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " obs[i * self.dimension: (i + 1) * self.dimension] = self.nodes[i]\n loc = self.num_points * self.dimension\n for i in range(self.num_points):\n for j in range(i + 1, self.num_poin... | contains(self.state.obs(nonexistent_edge=self.state_observation_space.low[-1])): |
{
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " self.edges = -np.ones((num_points, num_points, 2), dtype=np.float64)\n def obs(self, nonexistent_edge = -1):\n r'''\n transfer self.state to observation\n :param nonexistent_edge: area value of no... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
ret[0] = False # Not in valid observation
if (self.env_mode == 'DT'):
if not self.state_observation_space.contains(self.state.obs(nonexistent_edge=self.state_observation_space.low[-2:])):
ret[0] = False # Not in valid observation
for i in range(se... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 183,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 184,
"task_id": "project_cc_python/3543"
} | {
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " obs[i * self.dimension: (i + 1) * self.dimension] = self.nodes[i]\n loc = self.num_points * self.dimension\n for i in range(self.num_points):\n for j in range(i + 1, self.num_poin... | obs(nonexistent_edge=self.state_observation_space.low[-1])): |
{
"list": [
{
"filename": "Stage2/models/value_function/mlp_GNN.py",
"retrieved_chunk": " self.embed_node = Mlp(hidden_sizes=input_dims[:-1], output_size=self.embed_dim, input_size=4) #3 pos + 1 force = 4\n self.embed_edge = Mlp(hidden_sizes=input_dims[:-1], output_size=self.embe... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
valid, temp_state_dynamics = self.valid_truss()
if (valid[0] and valid[1] and valid[2] and valid[3] and temp_state_dynamics[1] < minaera):
minaera = temp_state_dynamics[1]
if (self.env_mode == 'DT'):
... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 373,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 374,
"task_id": "project_cc_python/3548"
} | {
"list": [
{
"filename": "Stage2/models/value_function/mlp_GNN.py",
"retrieved_chunk": " dim = 2\n else: dim = 1\n self.gcn1 = CGConv(channels=self.embed_dim, dim = dim)\n self.gcn2 = CGConv(channels=self.embed_dim, dim = dim)\n self.gcn3 = CGConv(channels=self.... | set(n_obs) |
{
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " self.edges = -np.ones((num_points, num_points, 2), dtype=np.float64)\n def obs(self, nonexistent_edge = -1):\n r'''\n transfer self.state to observation\n :param nonexistent_edge: area value of no... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
ret[0] = False # Not in valid observation
if (self.env_mode == 'DT'):
if not self.state_observation_space.contains(self.state.obs(nonexistent_edge=self.state_observation_space.low[-2:])):
ret[0] = False # Not in valid observation
for i in range(se... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 183,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 184,
"task_id": "project_cc_python/3544"
} | {
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " obs[i * self.dimension: (i + 1) * self.dimension] = self.nodes[i]\n loc = self.num_points * self.dimension\n for i in range(self.num_points):\n for j in range(i + 1, self.num_poin... | low[-1])): |
{
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " mind = arealist[-1][4]\n for i in range(len(e)):\n if (new_e.u == e[i].v or new_e.u == e[i].u or new_e.v == e[i].v or new_e.v == e[i].u): continue\n _, _, dis = closestDistanceBetweenLines(p[new_e.u].Poi... | import sys, os
import openseespy.opensees as op
import numpy as np
import math
from truss_envs.dynamic import DynamicModel
from utils.utils import Bar, getlen2
def Envs_init(args__):
global args
global truss_env
args = args__
'''
global E
global pho
global Sigma_T
global Sigma_C
glo... |
assert(new_e.t == se.t)
is_struct, mass, dis_value, stress_value, buckle_value, slenderness_value, longer_value, shorter_value, cross_value = truss_env.run(p, e, mode = mode)
dis_value = np.sum(dis_value)
stress_value = np.sum(stress_value)
buckle_value = np.sum(buckle_value)
slender... | {
"context_start_lineno": 0,
"file": "truss_envs/reward.py",
"groundtruth_start_lineno": 75,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 76,
"task_id": "project_cc_python/3539"
} | {
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " _, _, dis = closestDistanceBetweenLines(p[new_e.u].Point2np(), p[new_e.v].Point2np(), p[e[i].u].Point2np(), p[e[i].v].Point2np(), clampAll = True)\n if (args.env_dims == 2):\n mina = min(mina, (dis - e[... | v == se.v) |
{
"list": [
{
"filename": "utils/utils.py",
"retrieved_chunk": " :param path: path to store\n :return: None\n '''\n if (best == False):\n if (diverse_id == None):\n fo = open(os.path.join(path, str(int(mass * 1000)) + \".txt\"), \"w\")\n else: \n fo = op... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
obs = self.state.obs(nonexistent_edge=-1)
n_obs = copy.deepcopy(obs)
if (self.action_id[2] == 1): # Greedy update
n_obs = self.greedy_update(n_obs)
if (self.env_mode == 'Area'):
if self.action_id[1] != -1:
_i = int(self.action_id[1]) + self.num_p... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 406,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 407,
"task_id": "project_cc_python/3549"
} | {
"list": [
{
"filename": "utils/utils.py",
"retrieved_chunk": " fo.write(\"{} {}\\n\".format(n, n * (n - 1) // 2))\n for i in range(n):\n x = state.nodes[i][0]\n y = state.nodes[i][1]\n if state.dimension == 2:\n z = 0.0\n else:\n z = state.node... | contains(action), "actions({}) not in action space({})".format(action, self.action_space) |
{
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " mind = arealist[-1][4]\n for i in range(len(e)):\n if (new_e.u == e[i].v or new_e.u == e[i].u or new_e.v == e[i].v or new_e.v == e[i].u): continue\n _, _, dis = closestDistanceBetweenLines(p[new_e.u].Poi... | import sys, os
import openseespy.opensees as op
import numpy as np
import math
from truss_envs.dynamic import DynamicModel
from utils.utils import Bar, getlen2
def Envs_init(args__):
global args
global truss_env
args = args__
'''
global E
global pho
global Sigma_T
global Sigma_C
glo... |
assert(new_e.v == se.v)
assert(new_e.t == se.t)
is_struct, mass, dis_value, stress_value, buckle_value, slenderness_value, longer_value, shorter_value, cross_value = truss_env.run(p, e, mode = mode)
dis_value = np.sum(dis_value)
stress_value = np.sum(stress_value)
buckle_valu... | {
"context_start_lineno": 0,
"file": "truss_envs/reward.py",
"groundtruth_start_lineno": 74,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 75,
"task_id": "project_cc_python/3538"
} | {
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " _, _, dis = closestDistanceBetweenLines(p[new_e.u].Point2np(), p[new_e.v].Point2np(), p[e[i].u].Point2np(), p[e[i].v].Point2np(), clampAll = True)\n if (args.env_dims == 2):\n mina = min(mina, (dis - e[... | len == se.len) |
{
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " obs[i * self.dimension: (i + 1) * self.dimension] = self.nodes[i]\n loc = self.num_points * self.dimension\n for i in range(self.num_points):\n for j in range(i + 1, self.num_poin... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
if self.action_id[0] != -1:
n_obs[int(self.action_id[0]) * self.dimension: int(self.action_id[0] + 1) * self.dimension] += action[:-1] # act = [(a, b, c), d]
for _i in range(int(self.action_id[0]) * self.dimension, int(self.action_id[0] + 1) * self.dimension):
... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 416,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 417,
"task_id": "project_cc_python/3550"
} | {
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " :return: None\n '''\n for i in range(self.num_points):\n self.nodes[i] = obs[i * self.dimension: (i + 1) * self.dimension]\n loc = self.num_points * self.dimension\n if (self.env_mode =... | high[_i]), self.state_observation_space.low[_i]) |
{
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " mind = arealist[-1][4]\n for i in range(len(e)):\n if (new_e.u == e[i].v or new_e.u == e[i].u or new_e.v == e[i].v or new_e.v == e[i].u): continue\n _, _, dis = closestDistanceBetweenLines(p[new_e.u].Poi... | import sys, os
import openseespy.opensees as op
import numpy as np
import math
from truss_envs.dynamic import DynamicModel
from utils.utils import Bar, getlen2
def Envs_init(args__):
global args
global truss_env
args = args__
'''
global E
global pho
global Sigma_T
global Sigma_C
glo... |
is_struct, mass, dis_value, stress_value, buckle_value, slenderness_value, longer_value, shorter_value, cross_value = truss_env.run(p, e, mode = mode)
dis_value = np.sum(dis_value)
stress_value = np.sum(stress_value)
buckle_value = np.sum(buckle_value)
slenderness_value = np.sum(slenderness_valu... | {
"context_start_lineno": 0,
"file": "truss_envs/reward.py",
"groundtruth_start_lineno": 76,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 77,
"task_id": "project_cc_python/3540"
} | {
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " _, _, dis = closestDistanceBetweenLines(p[new_e.u].Point2np(), p[new_e.v].Point2np(), p[e[i].u].Point2np(), p[e[i].v].Point2np(), clampAll = True)\n if (args.env_dims == 2):\n mina = min(mina, (dis - e[... | t == se.t) |
{
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " loc = self.num_points * self.dimension\n for i in range(self.num_points):\n for j in range(i + 1, self.num_points):\n obs[loc: loc + 2] = nonexistent_edge if self.edges[i][j][... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
ret[1] = False # Duplicate nodes location
points = copy.deepcopy(self.initial_state_point)
for i in range(self.num_points):
points[i].vec.x = self.state.nodes[i][0]
points[i].vec.y = self.state.nodes[i][1]
if self.dimension == 3:
... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 192,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 193,
"task_id": "project_cc_python/3545"
} | {
"list": [
{
"filename": "Stage2/envs/state.py",
"retrieved_chunk": " :return: None\n '''\n for i in range(self.num_points):\n self.nodes[i] = obs[i * self.dimension: (i + 1) * self.dimension]\n loc = self.num_points * self.dimension\n if (self.env_mode =... | nodes[i] == self.state.nodes[j]).all(): |
{
"list": [
{
"filename": "src/access_control.py",
"retrieved_chunk": " s3.log_operation(\n audit_entry=s3.AuditEntry(\n account_id=account_id,\n role_name=permission_set.name,\n reason=reason,\n requester_slack_id=requester.id,\n reques... | import json
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from mypy_boto3_s3 import S3Client, type_defs
import boto3
from config import get_config, get_logger
cfg = get_config()
logger = get_logger(service="s3")
s3: S3Client = boto3.client("s3")
@dataclass
class Aud... |
logger.info("Posting audit entry to s3")
if isinstance(audit_entry.permission_duration, timedelta):
permission_duration = str(int(audit_entry.permission_duration.total_seconds()))
else:
permission_duration = "NA"
audit_entry_dict = asdict(audit_entry) | {
"permission_duration":... | {
"context_start_lineno": 0,
"file": "src/s3.py",
"groundtruth_start_lineno": 31,
"repository": "fivexl-terraform-aws-sso-elevator-fd46f09",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/3626"
} | {
"list": [
{
"filename": "src/access_control.py",
"retrieved_chunk": " operation_type=\"grant\",\n permission_duration=permission_duration,\n ),\n )\n schedule.schedule_revoke_event(\n permission_duration=permission_duration,\n schedule_client=schedule... | debug("Posting audit entry to s3", extra={"audit_entry": audit_entry}) |
{
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " d, t = None, None\n if (canadd(u, v, p, e, area, d, t)):\n e.append(Bar(u, v, leng = getlen2(p[u], p[v]), area = area, d = d, t = t))\n ret = soft_reward(reward_fun(p, e), p, e)\n ... | import sys, os
import openseespy.opensees as op
import numpy as np
import math
from truss_envs.dynamic import DynamicModel
from utils.utils import Bar, getlen2
def Envs_init(args__):
global args
global truss_env
args = args__
'''
global E
global pho
global Sigma_T
global Sigma_C
glo... |
assert(new_e.len == se.len)
assert(new_e.v == se.v)
assert(new_e.t == se.t)
is_struct, mass, dis_value, stress_value, buckle_value, slenderness_value, longer_value, shorter_value, cross_value = truss_env.run(p, e, mode = mode)
dis_value = np.sum(dis_value)
stress_valu... | {
"context_start_lineno": 0,
"file": "truss_envs/reward.py",
"groundtruth_start_lineno": 73,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 74,
"task_id": "project_cc_python/3537"
} | {
"list": [
{
"filename": "algo/UCTs.py",
"retrieved_chunk": " can_id = 0\n while (can_id < len(arealist) - 1 and arealist[can_id + 1][4] <= d): can_id += 1\n area_random = arealist[random.randint(0, can_id)]\n e[i].d = area_random[4]\n ... | area == se.area) |
{
"list": [
{
"filename": "src/slack_helpers.py",
"retrieved_chunk": " message: dict\n request: RequestForAccess\n class Config:\n frozen = True\n @root_validator(pre=True)\n def validate_payload(cls, values: dict) -> dict: # noqa: ANN101\n fields = jp.search(\"message.bl... | from datetime import timedelta
from typing import Literal
from pydantic import Field, root_validator
import entities
import sso
from entities.model import BaseModel
class RevokeEvent(BaseModel):
schedule_name: str
approver: entities.slack.User
requester: entities.slack.User
user_account_assignment: ... |
return values
class DiscardButtonsEvent(BaseModel):
action: Literal["discard_buttons_event"]
schedule_name: str
time_stamp: str
channel_id: str
class CheckOnInconsistency(BaseModel):
action: Literal["check_on_inconsistency"]
class SSOElevatorScheduledRevocation(BaseModel):
action:... | {
"context_start_lineno": 0,
"file": "src/events.py",
"groundtruth_start_lineno": 24,
"repository": "fivexl-terraform-aws-sso-elevator-fd46f09",
"right_context_start_lineno": 25,
"task_id": "project_cc_python/3625"
} | {
"list": [
{
"filename": "src/schedule.py",
"retrieved_chunk": " approver=approver,\n requester=requester,\n user_account_assignment=user_account_assignment,\n permission_duration=permission_duration,\n )\n logger.debug(\"Creating schedule\", extra={\"revoke_event\":... | parse_raw(values["revoke_event"]) |
{
"list": [
{
"filename": "truss_envs/reward.py",
"retrieved_chunk": " assert(new_e.t == se.t)\n is_struct, mass, dis_value, stress_value, buckle_value, slenderness_value, longer_value, shorter_value, cross_value = truss_env.run(p, e, mode = mode) \n dis_value = np.sum(dis_value)\n ... | import gym
import copy
import os
import numpy as np
import random
from collections import OrderedDict
from .space import StateObservationSpace, AutoregressiveEnvObservationSpace, AutoregressiveEnvActionSpace, ActionSpace
from utils.utils import is_edge_addable, readFile, getlen2, save_file, save_trajectory
from truss_... |
ret[3] = is_struct and max(dis_value, stress_value, buckle_value) < self.constraint_threshold and max(slenderness_value, longer_value, shorter_value, cross_value) <= 0 # Dynamic constraints
return ret, (is_struct, mass, dis_value, stress_value, buckle_value)
def reset(self, file_name=None):
... | {
"context_start_lineno": 0,
"file": "Stage2/envs/env.py",
"groundtruth_start_lineno": 229,
"repository": "StigLidu-AutoTruss-ffb5707",
"right_context_start_lineno": 230,
"task_id": "project_cc_python/3547"
} | {
"list": [
{
"filename": "Stage2/envs/dynamic2.py",
"retrieved_chunk": " def closestDistanceBetweenLines(self, a0, a1, b0, b1, \n clampAll = False, clampA0 = False,clampA1 = False,clampB0 = False,clampB1 = False):\n ''' \n Given two lines defined by numpy.array pairs (a0,a1,b0... | run(points, edges, mode = 'train') |
{
"list": [
{
"filename": "src/access_control.py",
"retrieved_chunk": " s3.log_operation(\n audit_entry=s3.AuditEntry(\n account_id=account_id,\n role_name=permission_set.name,\n reason=reason,\n requester_slack_id=requester.id,\n reques... | import json
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from mypy_boto3_s3 import S3Client, type_defs
import boto3
from config import get_config, get_logger
cfg = get_config()
logger = get_logger(service="s3")
s3: S3Client = boto3.client("s3")
@dataclass
class Aud... |
if isinstance(audit_entry.permission_duration, timedelta):
permission_duration = str(int(audit_entry.permission_duration.total_seconds()))
else:
permission_duration = "NA"
audit_entry_dict = asdict(audit_entry) | {
"permission_duration": permission_duration,
"time": str(now... | {
"context_start_lineno": 0,
"file": "src/s3.py",
"groundtruth_start_lineno": 32,
"repository": "fivexl-terraform-aws-sso-elevator-fd46f09",
"right_context_start_lineno": 33,
"task_id": "project_cc_python/3627"
} | {
"list": [
{
"filename": "src/access_control.py",
"retrieved_chunk": " operation_type=\"grant\",\n permission_duration=permission_duration,\n ),\n )\n schedule.schedule_revoke_event(\n permission_duration=permission_duration,\n schedule_client=schedule... | info("Posting audit entry to s3") |
{
"list": [
{
"filename": "operators/druid.py",
"retrieved_chunk": " def execute(self, context):\n if self.sql is not None:\n sql = self.sql\n elif self.sql_generator is not None:\n sql = self.sql_generator(**self.sql_generator_kwargs)\n else:\n ... |
import os
import time
import pandas as pd
from typing import Callable, Dict, Optional
from airflow.models import BaseOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.exceptions import AirflowException
from hooks.postgres import PostgresPandasHook
from utils.os_helper import make... |
self.log.info(f"Took {time.time() - start_time}s to pull SQL")
return df
def _transform_pandas(self, df: pd.DataFrame):
start_time = time.time()
if not self.pd_transformer:
return df
transformer_kwargs = self.pd_transformer_kwargs.copy()
transformer_kwar... | {
"context_start_lineno": 0,
"file": "operators/postgres.py",
"groundtruth_start_lineno": 183,
"repository": "tungduongbk-airflow-custom-plugins-f0f571d",
"right_context_start_lineno": 184,
"task_id": "project_cc_python/3589"
} | {
"list": [
{
"filename": "operators/druid.py",
"retrieved_chunk": " self.get_postgres_hook().insert_pandas_2_postgres(\n dataframe=dataframe,\n **self.pg_insert_kwargs\n )\nclass DruidMarkSegmentAsUnusedOperator(BaseOperator):\n \"\"\"\n Mard unused segments ... | query_from_postgres(sql) |
{
"list": [
{
"filename": "hooks/cassandra_custom.py",
"retrieved_chunk": " Cassandra connect interaction wrapper\n :param keyspace: The keyspace that overwrite keyspace in connection\n :type keyspace: str\n \"\"\"\n def __init__(\n self,\n keyspace=None,\n ... | import pandas as pd
from typing import Dict
from airflow.exceptions import AirflowException
from operators.postgres import PostgresPandasTransformOperator
from hooks.cassandra_custom import CassandraCustomHook
class PostgresToCassandraOperator(PostgresPandasTransformOperator):
"""
Transfer data from postgres ... |
cass_hook.insert_dataframe(df, self.cassandra_table, batch_insert_records=200)
def execute(self, context):
df = self._pull_postgres_to_pandas()
result = self._transform_pandas(df)
# result.replace({np.nan: None}, inplace=True)
if self.column_map:
result.rename(... | {
"context_start_lineno": 0,
"file": "operators/pg_to_cassandra.py",
"groundtruth_start_lineno": 52,
"repository": "tungduongbk-airflow-custom-plugins-f0f571d",
"right_context_start_lineno": 53,
"task_id": "project_cc_python/3601"
} | {
"list": [
{
"filename": "hooks/cassandra_custom.py",
"retrieved_chunk": " self.keyspace = keyspace\n def _resolve_consistency_level(self, consistency_level) -> ConsistencyLevel:\n if type(consistency_level) is str:\n if consistency_level == \"ALL\":\n r... | log.info(f"Writing dataframe {index} to cassandra") |
{
"list": [
{
"filename": "operators/ms_teams_webhook.py",
"retrieved_chunk": " self.message = message\n self.status = status\n self.owner = owner\n self.button_text = button_text\n self.theme_color = theme_color\n self.proxy = proxy\n self.hook = None\... |
from operators.ms_teams_webhook import MSTeamsWebhookOperator
from datetime import datetime, timedelta
def on_failure(context, **kwargs):
owner = context['dag'].default_args['owner']
message = f"""💩 💩 💩 💩 <strong>{owner}</strong>"""
teams_notification = MSTeamsWebhookOpera... |
def on_success(context, **kwargs):
owner = context['dag'].default_args['owner']
message = f"""A may ding, gut chop 💞 💞 <strong>{owner}</strong>"""
teams_notification = MSTeamsWebhookOperator(
status="SUCCESS",
task_id="msteams_notify_success",
owner=f'{owner}',
... | {
"context_start_lineno": 0,
"file": "utils/python_callable.py",
"groundtruth_start_lineno": 17,
"repository": "tungduongbk-airflow-custom-plugins-f0f571d",
"right_context_start_lineno": 18,
"task_id": "project_cc_python/3587"
} | {
"list": [
{
"filename": "operators/ms_teams_webhook.py",
"retrieved_chunk": " airflow_url = Variable.get(\"airflow_url\")\n logs_url = airflow_url + \"/admin/airflow/log?dag_id={}&task_id={}&execution_date={}\".format(\n dag_id, task_id, context['ts'])\n self.hook = M... | execute(context) |
{
"list": [
{
"filename": "operators/elasticsearch_parquet.py",
"retrieved_chunk": " def _to_parquet(self, store_dir, file_name, result_list):\n self.log.info(\" *** Saving data to parquet file ...\")\n df = pd.DataFrame(result_list)\n if not os.path.exists(store_dir):\n ... | import pandas as pd
from typing import Dict
from airflow.exceptions import AirflowException
from operators.postgres import PostgresPandasTransformOperator
from hooks.cassandra_custom import CassandraCustomHook
class PostgresToCassandraOperator(PostgresPandasTransformOperator):
"""
Transfer data from postgres ... |
def execute(self, context):
df = self._pull_postgres_to_pandas()
result = self._transform_pandas(df)
# result.replace({np.nan: None}, inplace=True)
if self.column_map:
result.rename(columns=self.column_map, inplace=True)
if isinstance(result, pd.DataFrame):
... | {
"context_start_lineno": 0,
"file": "operators/pg_to_cassandra.py",
"groundtruth_start_lineno": 54,
"repository": "tungduongbk-airflow-custom-plugins-f0f571d",
"right_context_start_lineno": 55,
"task_id": "project_cc_python/3602"
} | {
"list": [
{
"filename": "hooks/cassandra_custom.py",
"retrieved_chunk": " self.keyspace = keyspace\n def _resolve_consistency_level(self, consistency_level) -> ConsistencyLevel:\n if type(consistency_level) is str:\n if consistency_level == \"ALL\":\n r... | insert_dataframe(df, self.cassandra_table, batch_insert_records=200) |
{
"list": [
{
"filename": "operators/elasticsearch_parquet.py",
"retrieved_chunk": " self.log.info(\n \"Run elastic search query of index {}: \\n{}\".format(self.index, json.dumps(lucene_query, indent=2)))\n start_time = time.time()\n self.scan(client=es_client,\n ... | import time
import shutil
import contextlib
import pandas as pd
from datetime import timedelta
from typing import Callable, Dict, Optional, Union, List
from airflow.models import BaseOperator
from airflow.exceptions import AirflowException
from airflow.providers.apache.hive.hooks.hive import HiveServer2Hook, HiveMetast... |
self.log.info(f"STEP 5: clean hdfs temporary dir: {self.hdfs_temporary_dir}")
| {
"context_start_lineno": 0,
"file": "operators/hive.py",
"groundtruth_start_lineno": 241,
"repository": "tungduongbk-airflow-custom-plugins-f0f571d",
"right_context_start_lineno": 242,
"task_id": "project_cc_python/3599"
} | {
"list": [
{
"filename": "operators/postgres.py",
"retrieved_chunk": " transformed_df = self.pd_transformer(**transformer_kwargs)\n self.log.info(f\"Took {time.time() - start_time} s to transform pandas dataframe\")\n return transformed_df\n def _save_dataframe(self, df: pd.Da... | _remove(client, self.hdfs_temporary_dir) |
{
"list": [
{
"filename": "operators/postgres.py",
"retrieved_chunk": " self.log.info(f\"SQL: {sql}\")\n df = hook.query_from_postgres(sql)\n self.log.info(f\"Took {time.time() - start_time}s to pull SQL\")\n return df\n def _transform_pandas(self, df: pd.DataFrame):\n ... | import time
import shutil
import contextlib
import pandas as pd
from datetime import timedelta
from typing import Callable, Dict, Optional, Union, List
from airflow.models import BaseOperator
from airflow.exceptions import AirflowException
from airflow.providers.apache.hive.hooks.hive import HiveServer2Hook, HiveMetast... |
self.log.info("STEP 2: took {}s to push data to hdfs".format(time.time() - start_time))
start_time = time.time()
hqls = []
self._preprocess_partition()
hqls.extend(self._generate_create_hive_temporay_table())
hqls.extend(self._generate_insert_data_from_temporary... | {
"context_start_lineno": 0,
"file": "operators/hive.py",
"groundtruth_start_lineno": 226,
"repository": "tungduongbk-airflow-custom-plugins-f0f571d",
"right_context_start_lineno": 227,
"task_id": "project_cc_python/3598"
} | {
"list": [
{
"filename": "operators/postgres.py",
"retrieved_chunk": " transformed_df = self.pd_transformer(**transformer_kwargs)\n self.log.info(f\"Took {time.time() - start_time} s to transform pandas dataframe\")\n return transformed_df\n def _save_dataframe(self, df: pd.Da... | _copyObjToDir(self.local_temporary_dir, self.hdfs_temporary_dir, client, file_conf, file_filter=None) |
{
"list": [
{
"filename": "tests/test_builtins.py",
"retrieved_chunk": " result = await run_shell_command(command)\n assert \"adsflkajsdg: command not found\" in result\n@pytest.mark.asyncio\nasync def test_list_files():\n directory = \"chatlab/builtins\"\n files = await list_files(directo... | # flake8: noqa
from unittest import mock
from unittest.mock import MagicMock, patch
import pytest
from pydantic import BaseModel
from chatlab.registry import FunctionArgumentError, FunctionRegistry, UnknownFunctionError, generate_function_schema
# Define a function to use in testing
def simple_func(x: int, y: str, ... |
@pytest.mark.asyncio
async def test_function_registry_function_argument_error():
registry = FunctionRegistry()
registry.register(simple_func, SimpleModel)
with pytest.raises(
FunctionArgumentError, match="Invalid Function call on simple_func. Arguments must be a valid JSON object"
):
... | {
"context_start_lineno": 0,
"file": "tests/test_registry.py",
"groundtruth_start_lineno": 89,
"repository": "rgbkrk-chatlab-c126c9f",
"right_context_start_lineno": 90,
"task_id": "project_cc_python/3607"
} | {
"list": [
{
"filename": "tests/test_builtins.py",
"retrieved_chunk": " file_path = \"chatlab/builtins/files.py\"\n size = await get_file_size(file_path)\n assert isinstance(size, int)\n assert size > 0\n@pytest.mark.asyncio\nasync def test_is_file():\n file_path = \"chatlab/builtins/f... | call("unknown") |
{
"list": [
{
"filename": "tests/test_builtins.py",
"retrieved_chunk": " result = await run_shell_command(command)\n assert \"adsflkajsdg: command not found\" in result\n@pytest.mark.asyncio\nasync def test_list_files():\n directory = \"chatlab/builtins\"\n files = await list_files(directo... | # flake8: noqa
from unittest import mock
from unittest.mock import MagicMock, patch
import pytest
from pydantic import BaseModel
from chatlab.registry import FunctionArgumentError, FunctionRegistry, UnknownFunctionError, generate_function_schema
# Define a function to use in testing
def simple_func(x: int, y: str, ... |
with pytest.raises(
FunctionArgumentError, match="Invalid Function call on simple_func. Arguments must be a valid JSON object"
):
await registry.call("simple_func", arguments="not json")
@pytest.mark.asyncio
async def test_function_registry_call():
registry = FunctionRegistry()
regist... | {
"context_start_lineno": 0,
"file": "tests/test_registry.py",
"groundtruth_start_lineno": 95,
"repository": "rgbkrk-chatlab-c126c9f",
"right_context_start_lineno": 96,
"task_id": "project_cc_python/3608"
} | {
"list": [
{
"filename": "tests/test_builtins.py",
"retrieved_chunk": " file_path = \"chatlab/builtins/files.py\"\n size = await get_file_size(file_path)\n assert isinstance(size, int)\n assert size > 0\n@pytest.mark.asyncio\nasync def test_is_file():\n file_path = \"chatlab/builtins/f... | register(simple_func, SimpleModel) |
{
"list": [
{
"filename": "src/lcd/models/helpers.py",
"retrieved_chunk": " )\n out = torch.einsum(\"b h d e, b h c e -> b h c d\", qk, v)\n out = einops.rearrange(out, \"b h c d -> b (h c) d\")\n return self.dropout(self.to_out(out) + og_x)\n# -----------------------------... | import pdb
from collections import namedtuple
import numpy as np
import torch
from torch import nn
import lcd.utils as utils
from .helpers import Losses, apply_conditioning, cosine_beta_schedule, extract
Sample = namedtuple("Sample", "trajectories values chains")
@torch.no_grad()
def default_sample_fn(model, x, c... |
if inpaint is not None:
x = apply_conditioning(x, inpaint, self.action_dim)
if return_chain:
chain.append(x)
if return_chain:
chain = torch.stack(chain, dim=1) # type: ignore
if inpaint is not None:
x = apply_condition... | {
"context_start_lineno": 0,
"file": "src/lcd/models/diffusion.py",
"groundtruth_start_lineno": 277,
"repository": "ezhang7423-language-control-diffusion-63cdafb",
"right_context_start_lineno": 278,
"task_id": "project_cc_python/3657"
} | {
"list": [
{
"filename": "src/lcd/models/helpers.py",
"retrieved_chunk": "class WeightedLoss(nn.Module):\n def __init__(self, weights, action_dim):\n super().__init__()\n self.register_buffer(\"weights\", weights)\n self.action_dim = action_dim\n def forward(self, pred, tar... | sqrt() + c * pred_noise + sigma * noise |
{
"list": [
{
"filename": "src/textSummarizer/utils/common.py",
"retrieved_chunk": " \"\"\"create list of directories\n Args:\n path_to_directories (list): list of path of directories\n ignore_log (bool, optional): ignore if multiple dirs is to be created. Defaults to False.\n \... | import os
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO, format='[%(asctime)s]: %(message)s:')
project_name = "textSummarizer"
list_of_files = [
".github/workflows/.gitkeep",
f"src/{project_name}/__init__.py",
f"src/{project_name}/conponents/__init__.py",
f"src/{proj... |
if (not os.path.exists(filepath)) or (os.path.getsize(filepath) == 0):
with open(filepath,'w') as f:
pass
logging.info(f"Creating empty file: {filepath}")
else:
logging.info(f"{filename} is already exists")
| {
"context_start_lineno": 0,
"file": "template.py",
"groundtruth_start_lineno": 39,
"repository": "krishnaik06-Text-Summarization-NLP-Project-3308112",
"right_context_start_lineno": 40,
"task_id": "project_cc_python/3643"
} | {
"list": [
{
"filename": "src/textSummarizer/utils/common.py",
"retrieved_chunk": "def get_size(path: Path) -> str:\n \"\"\"get size in KB\n Args:\n path (Path): path of the file\n Returns:\n str: size in KB\n \"\"\"\n size_in_kb = round(os.path.getsize(path)/1024)\n r... | info(f"Creating directory:{filedir} for the file {filename}") |
{
"list": [
{
"filename": "poptransformer/models/llama2/mlp.py",
"retrieved_chunk": " }\n def collect_bind_layer_weights(self):\n self.gate_proj = Linear(self.context, 'gate_proj', self.input_size, self.hidden_size, use_bias=False)\n self.up_proj = Linear(self.context, 'up_proj', s... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
proj_tp_setting = {
'strategy_name': 'end',
}
self.c_proj = Linear(self.context, 'c_proj', self.hidden_size, self.input_size, **proj_tp_setting)
class MLP(TPMLP, BaseMLP):
layer_class_map = {
'tp': TPMLP,
'shard': BaseMLP}
def __init__(self, context, name,... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/mlp.py",
"groundtruth_start_lineno": 49,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 50,
"task_id": "project_cc_python/3692"
} | {
"list": [
{
"filename": "poptransformer/models/llama2/mlp.py",
"retrieved_chunk": " up_output = ops.mul(graph, up_output, gate_output)\n output = self.down_proj(graph, up_output)\n output = ops.reshape(graph, output, [self.batch_size, -1, self.input_size])\n return output... | context, 'c_fc', self.input_size, self.hidden_size, **fc_tp_setting) |
{
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " self.collect_bind_layer_weights()\n def collect_bind_layer_weights(self):\n weight_key = '.'.join([self.context, 'weight'])\n weight_np = self.get_param_from_state_dict(weight_key, [self.input... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
variance = ops.mul(graph, variance, variance)
variance = ops.reducemean(graph, variance)
variance = ops.add(graph, variance, variance_epsilon)
variance = ops.sqrt(graph, variance)
variance = ops.reciprocal(graph, variance)
variance = ops.cast(graph, variance, self.popart... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/rms_layer_norm.py",
"groundtruth_start_lineno": 27,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/3679"
} | {
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " norm_fn = self.norm_fn_map.get(norm_type, None)\n if not norm_fn:\n raise ValueError(f\"Invalid norm_fn {norm_type}, options: {self.norm_fn_map.keys()}\")\n x = norm_fn... | cast(graph, x, 'FLOAT') |
{
"list": [
{
"filename": "builder/builder/tests/ImportWorkflow_test.py",
"retrieved_chunk": " )\n assert m.nodes[0].output_namespace == \"module1\"\n assert m.nodes[1].name == \"module2\"\n assert (\n m.nodes[1].snakefile\n == \"builder/tests/workflow_import_test/modules/sle... | import pytest
from builder.builder import Model
from builder.builder import YAMLToConfig
def test_BuildSnakefile():
m = Model()
# Add modules
m.AddModule("module1", {"snakefile": "snakefile1"})
m.AddModule("module2", {"snakefile": "snakefile2"})
m.AddModule("module3", {"snakefile": "snakefile3"})... |
assert m.nodes[0].nodetype == "moduletype1"
# Verify module attributes assigned correctly
for key in module:
# output_namespace is wrangled
if key not in ["output_namespace"]:
assert getattr(m.nodes[0], key) == module[key]
def test_AddModule_MultipleInputNamespaces():
m = ... | {
"context_start_lineno": 0,
"file": "builder/builder/tests/builder_test.py",
"groundtruth_start_lineno": 128,
"repository": "kraemer-lab-GRAPEVNE-1d241a8",
"right_context_start_lineno": 129,
"task_id": "project_cc_python/3670"
} | {
"list": [
{
"filename": "builder/builder/ImportWorkflow.py",
"retrieved_chunk": " return m\ndef ParseFunctionSignature(signature: str):\n def f(*args, **kwargs):\n return args, kwargs\n name, args = signature.split(\"(\", 1)\n return name, *eval(\"f(\" + args)",
"score": 24.... | nodes[0].name == name |
{
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " self.dilations = [dilations] * 2 if isinstance(dilations, int) else dilations\n self.groups = groups\n self.bias = bias\n self.collect_bind_layer_weights()\n def collect_bind_layer_weights(se... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
weight_np = weight_np.transpose(1, 0)
weight_np = self.param_handler.process_linear_weight(weight_np, weight_key)
self.weight_id = self.add_initialized_input_tensor(weight_np, weight_key)
if self.use_bias:
bias_key = '.'.join([self.context, 'bias'])
bias_np = se... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/linear.py",
"groundtruth_start_lineno": 30,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/3696"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " bias_key = '.'.join([self.context, 'bias'])\n bias_np = self.get_param_from_state_dict(bias_key, [self.output_size])\n self.bias_id = self.add_initialized_input_tensor(bias_np, bias_key)\n ... | get_param_from_state_dict(weight_key, [self.output_size, self.input_size]) |
{
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " self.collect_bind_layer_weights()\n def collect_bind_layer_weights(self):\n weight_key = '.'.join([self.context, 'weight'])\n weight_np = self.get_param_from_state_dict(weight_key, [self.input... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.weight_id = self.add_initialized_input_tensor(weight_np, weight_key)
if self.use_bias:
bias_key = '.'.join([self.context, 'bias'])
bias_np = self.get_param_from_state_dict(bias_key, [self.output_size])
bias_np = self.param_handler.process_linear_bias(bias_np)
... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/linear.py",
"groundtruth_start_lineno": 32,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 33,
"task_id": "project_cc_python/3697"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " bias_key = '.'.join([self.context, 'bias'])\n bias_np = self.get_param_from_state_dict(bias_key, [self.output_size])\n self.bias_id = self.add_initialized_input_tensor(bias_np, bias_key)\n ... | process_linear_weight(weight_np, weight_key) |
{
"list": [
{
"filename": "builder/builder/tests/builder_test.py",
"retrieved_chunk": " )\n # Namespace connector\n m.AddConnector(\"conn12\", {\"map\": [\"module1\", \"module2\"]})\n m.AddConnector(\"conn23\", {\"map\": [\"module2\", \"module3\"]})\n c = m.ConstructSnakefileConfig()\n ... | import re
import yaml
from builder.builder import Model
from builder.builder_web import GetWorkflowFiles
def ImportWorkflowDir(
workflow_dir: str,
) -> Model:
"""Import linked modules snakemake workflow as Model object
Args:
filename: Path to the workflow file
levels: Number of levels t... |
# Retain namespace mapping
node.input_namespace = config.get("input_namespace", node.input_namespace)
node.output_namespace = config.get("output_namespace", node.output_namespace)
node.snakefile = workflow_config[rulename].get("snakefile", node.snakefile)
# Expand modules
m.Exp... | {
"context_start_lineno": 0,
"file": "builder/builder/ImportWorkflow.py",
"groundtruth_start_lineno": 29,
"repository": "kraemer-lab-GRAPEVNE-1d241a8",
"right_context_start_lineno": 30,
"task_id": "project_cc_python/3660"
} | {
"list": [
{
"filename": "builder/builder/builder.py",
"retrieved_chunk": " m\n for m in modules_list\n if (m in config) # GRAPEVNE config entry requirements here\n ]\n if not modules_list:\n # No valid modules found, return original node\n ... | AddModule(rulename, {"config": c}) |
{
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight_np = self.get_param_from_state_dict(weight_key, weight_shape)\n self.weight_id = self.add_initialized_input_tensor(weight_np, weight_key)\n if self.bias:\n bias_key = '.'.join([self.c... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
variance = ops.cast(graph, variance, self.popart_float_type)
x = ops.mul(graph, x, variance)
return ops.mul(graph, x, self.weight_id)
class TPRMSLayerNorm(BaseRMSLayerNorm):
pass
class RMSLayerNorm(TPRMSLayerNorm, BaseRMSLayerNorm):
layer_class_map = {
'tp': TPRMSLayerNorm,... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/rms_layer_norm.py",
"groundtruth_start_lineno": 32,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 33,
"task_id": "project_cc_python/3684"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight=self.weight_id,\n bias=self.bias_id if self.bias else None,\n kernel_shape=self.kernels,\n strides=self.strides,\n pads=self.pads,\n dilations=self.d... | reciprocal(graph, variance) |
{
"list": [
{
"filename": "poptransformer/models/llama2/mlp.py",
"retrieved_chunk": " self.context, 'down_proj', self.hidden_size, self.input_size, use_bias=False, **down_proj_tp_settings)\nclass MLP(TPMLP, ShardMLP):\n layer_class_map = {\n 'tp': TPMLP,\n 'shard': ShardMLP... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.c_proj = Linear(self.context, 'c_proj', self.hidden_size, self.input_size)
def __call__(self, graph, x):
with graph.nameScope(self.context):
x = ops.reshape(graph, x, [-1, self.input_size])
x = self.c_fc(graph, x)
x = self.act_fn(graph, x)
x = s... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/mlp.py",
"groundtruth_start_lineno": 30,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/3689"
} | {
"list": [
{
"filename": "poptransformer/models/llama2/mlp.py",
"retrieved_chunk": " self.logger.debug(f'initializing model type: {self.layer_class.__name__}')\n super().__init__(context, name, input_size, hidden_size, act_fn)\n def __call__(self, graph, x):\n return self.laye... | context, 'c_fc', self.input_size, self.hidden_size) |
{
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " self.collect_bind_layer_weights()\n def collect_bind_layer_weights(self):\n weight_key = '.'.join([self.context, 'weight'])\n weight_np = self.get_param_from_state_dict(weight_key, [self.input... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
variance = ops.reducemean(graph, variance)
variance = ops.add(graph, variance, variance_epsilon)
variance = ops.sqrt(graph, variance)
variance = ops.reciprocal(graph, variance)
variance = ops.cast(graph, variance, self.popart_float_type)
x = ops.mul(graph, x, variance)
... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/rms_layer_norm.py",
"groundtruth_start_lineno": 28,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 29,
"task_id": "project_cc_python/3680"
} | {
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " norm_fn = self.norm_fn_map.get(norm_type, None)\n if not norm_fn:\n raise ValueError(f\"Invalid norm_fn {norm_type}, options: {self.norm_fn_map.keys()}\")\n x = norm_fn... | mul(graph, variance, variance) |
{
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight_np = self.get_param_from_state_dict(weight_key, weight_shape)\n self.weight_id = self.add_initialized_input_tensor(weight_np, weight_key)\n if self.bias:\n bias_key = '.'.join([self.c... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.bias_id = self.add_initialized_input_tensor(bias_np, bias_key)
def __call__(self, graph, x):
with graph.nameScope(self.context):
x = self.param_handler.matmul(graph, x, self.weight_id)
x = ops.add(graph, x, self.bias_id) if self.use_bias else x
return x
c... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/linear.py",
"groundtruth_start_lineno": 38,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 39,
"task_id": "project_cc_python/3699"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight=self.weight_id,\n bias=self.bias_id if self.bias else None,\n kernel_shape=self.kernels,\n strides=self.strides,\n pads=self.pads,\n dilations=self.d... | process_linear_bias(bias_np) |
{
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " self.collect_bind_layer_weights()\n def collect_bind_layer_weights(self):\n weight_key = '.'.join([self.context, 'weight'])\n weight_np = self.get_param_from_state_dict(weight_key, [self.input... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
variance = ops.add(graph, variance, variance_epsilon)
variance = ops.sqrt(graph, variance)
variance = ops.reciprocal(graph, variance)
variance = ops.cast(graph, variance, self.popart_float_type)
x = ops.mul(graph, x, variance)
return ops.mul(graph, x, self.weight_id)
c... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/rms_layer_norm.py",
"groundtruth_start_lineno": 29,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 30,
"task_id": "project_cc_python/3681"
} | {
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " norm_fn = self.norm_fn_map.get(norm_type, None)\n if not norm_fn:\n raise ValueError(f\"Invalid norm_fn {norm_type}, options: {self.norm_fn_map.keys()}\")\n x = norm_fn... | reducemean(graph, variance) |
{
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " self.collect_bind_layer_weights()\n def collect_bind_layer_weights(self):\n weight_key = '.'.join([self.context, 'weight'])\n weight_np = self.get_param_from_state_dict(weight_key, [self.input... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
variance = ops.cast(graph, x, 'FLOAT')
variance = ops.mul(graph, variance, variance)
variance = ops.reducemean(graph, variance)
variance = ops.add(graph, variance, variance_epsilon)
variance = ops.sqrt(graph, variance)
variance = ops.reciprocal(graph, variance)
v... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/rms_layer_norm.py",
"groundtruth_start_lineno": 26,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 27,
"task_id": "project_cc_python/3677"
} | {
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " norm_fn = self.norm_fn_map.get(norm_type, None)\n if not norm_fn:\n raise ValueError(f\"Invalid norm_fn {norm_type}, options: {self.norm_fn_map.keys()}\")\n x = norm_fn... | constant(graph, np.array(self.eps).astype(np.float32), 'variance_epsilon') |
{
"list": [
{
"filename": "runner/runner/snakemake_runner_test/snakefile_test.py",
"retrieved_chunk": " [\"call_variants\", \"plot_quals\"],\n ]\n assert blocks[\"links\"][\"content\"] == expected_links\ndef test_SplitByRulesFromFile():\n filename = os.path.abspath(\"../examples/snakem... | import contextlib
import io
import json
import logging
import os
import platform
import shutil
import subprocess
import tempfile
from contextlib import redirect_stderr
from contextlib import redirect_stdout
from pathlib import Path
from typing import Dict
from typing import List
from typing import Optional
from typing ... |
words = content.split()
if not words:
continue
if words[0] == "rule":
blocktype = "rule"
name = words[1].replace(":", "")
elif words[0] == "module":
blocktype = "module"
name = words[1].replace(":", "")
else:
... | {
"context_start_lineno": 0,
"file": "runner/runner/snakemake_runner/snakefile.py",
"groundtruth_start_lineno": 268,
"repository": "kraemer-lab-GRAPEVNE-1d241a8",
"right_context_start_lineno": 269,
"task_id": "project_cc_python/3659"
} | {
"list": [
{
"filename": "runner/runner/snakemake_runner_test/snakefile_test.py",
"retrieved_chunk": " [\"sort_alignments\", \"call_variants\"],\n [\"sort_alignments\", \"call_variants\"],\n [\"sort_alignments\", \"call_variants\"],\n [\"map_reads\", \"sort_alignments\"],\... | GetBlockFromIndex(block_index) |
{
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " self.collect_bind_layer_weights()\n def collect_bind_layer_weights(self):\n weight_key = '.'.join([self.context, 'weight'])\n weight_np = self.get_param_from_state_dict(weight_key, [self.input... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
variance = ops.cast(graph, x, 'FLOAT')
variance = ops.mul(graph, variance, variance)
variance = ops.reducemean(graph, variance)
variance = ops.add(graph, variance, variance_epsilon)
variance = ops.sqrt(graph, variance)
variance = ops.reciprocal(graph, variance)
v... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/rms_layer_norm.py",
"groundtruth_start_lineno": 26,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 27,
"task_id": "project_cc_python/3678"
} | {
"list": [
{
"filename": "poptransformer/layers/layer_norm.py",
"retrieved_chunk": " norm_fn = self.norm_fn_map.get(norm_type, None)\n if not norm_fn:\n raise ValueError(f\"Invalid norm_fn {norm_type}, options: {self.norm_fn_map.keys()}\")\n x = norm_fn... | eps).astype(np.float32), 'variance_epsilon') |
{
"list": [
{
"filename": "poptransformer/utils/tensor_type.py",
"retrieved_chunk": "# Copyright (c) 2023 Graphcore Ltd.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
def __init__(self, context, name, input_size, eps):
super().__init__(context, name)
self.input_size = input_size
self.eps = eps
self.collect_bind_layer_weights()
def collect_bind_layer_weights(self):
weight_key = '.'.join([self.context, 'weight'])
weight_np = s... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/layer_norm.py",
"groundtruth_start_lineno": 19,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 20,
"task_id": "project_cc_python/3707"
} | {
"list": [
{
"filename": "poptransformer/utils/tensor_type.py",
"retrieved_chunk": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport numpy as np\nclass TensorType:\n all_precision = ['fp32', 'fp16', 'int4', 'fp8', 'fp8_weight']\n np... | group_norm, 'ce': ops.layer_norm_ce} |
{
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight_np = self.get_param_from_state_dict(weight_key, weight_shape)\n self.weight_id = self.add_initialized_input_tensor(weight_np, weight_key)\n if self.bias:\n bias_key = '.'.join([self.c... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
x = ops.add(graph, x, self.bias_id) if self.use_bias else x
return x
class TPLinear(BaseLinear):
def collect_bind_layer_weights(self):
vs_setting = {'vs_type': 'consecutive', 'group_size': 1}
self.param_handler = ParamHandler(
host_layer=self,
tp_strat... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/linear.py",
"groundtruth_start_lineno": 43,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 44,
"task_id": "project_cc_python/3700"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight=self.weight_id,\n bias=self.bias_id if self.bias else None,\n kernel_shape=self.kernels,\n strides=self.strides,\n pads=self.pads,\n dilations=self.d... | matmul(graph, x, self.weight_id) |
{
"list": [
{
"filename": "poptransformer/utils/param_handler/param_handler.py",
"retrieved_chunk": " weight_np = weight_fn_tp(weight_np, self.num_replicas, self.tp_strategy['weight_axis'])\n weight_np = weight_fn_precision(\n host_layer=self.host_layer,\n weight_np... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
if self.use_bias:
bias_key = '.'.join([self.context, 'bias'])
bias_np = self.get_param_from_state_dict(bias_key, [self.output_size])
bias_np = self.param_handler.process_linear_bias(bias_np)
self.bias_id = self.add_initialized_input_tensor(bias_np, bias_key, **v... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/linear.py",
"groundtruth_start_lineno": 61,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 62,
"task_id": "project_cc_python/3704"
} | {
"list": [
{
"filename": "poptransformer/utils/param_handler/param_handler.py",
"retrieved_chunk": " return weight_np\n def process_linear_bias(self, bias):\n bias_fn_tp = self.tp_strategy['bias_fn']\n bias = bias_fn_tp(bias, self.num_replicas, 0)\n return bias\n def... | add_initialized_input_tensor(weight_np, weight_key, **vs_setting) |
{
"list": [
{
"filename": "poptransformer/layers/linear.py",
"retrieved_chunk": " if self.use_bias:\n bias_key = '.'.join([self.context, 'bias'])\n bias_np = self.get_param_from_state_dict(bias_key, [self.output_size])\n bias_np = self.param_handler.process_line... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
return x
class TPLayerNorm(BaseLayerNorm):
pass
class LayerNorm(TPLayerNorm, BaseLayerNorm):
layer_class_map = {
'tp': TPLayerNorm,
'shard': BaseLayerNorm}
def __init__(self, context, name, input_size, eps):
model_type = self.model_type
self.layer_class = s... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/layer_norm.py",
"groundtruth_start_lineno": 41,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 42,
"task_id": "project_cc_python/3712"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " strides=self.strides,\n pads=self.pads,\n dilations=self.dilations,\n group=self.groups\n )\n return x\nclass TPConv2d(BaseConv2d):\n pass\nclass Conv1d(TPConv1d... | batch_size, sequence_length, self.input_size) |
{
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " bias_key = '.'.join([self.context, 'bias'])\n bias_np = self.get_param_from_state_dict(bias_key, [self.output_size])\n self.bias_id = self.add_initialized_input_tensor(bias_np, bias_key)\n ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
return x
class TPLinear(BaseLinear):
def collect_bind_layer_weights(self):
vs_setting = {'vs_type': 'consecutive', 'group_size': 1}
self.param_handler = ParamHandler(
host_layer=self,
tp_strategy_name=self.kwargs.get('strategy_name'),
**vs_setting
... | {
"context_start_lineno": 0,
"file": "poptransformer/layers/linear.py",
"groundtruth_start_lineno": 44,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 45,
"task_id": "project_cc_python/3701"
} | {
"list": [
{
"filename": "poptransformer/layers/conv.py",
"retrieved_chunk": " weight=self.weight_id,\n bias=self.bias_id if self.bias else None,\n kernel_shape=self.kernels,\n strides=self.strides,\n pads=self.pads,\n dilations=self.d... | add(graph, x, self.bias_id) if self.use_bias else x |
{
"list": [
{
"filename": "poptransformer/models/rwkv/model.py",
"retrieved_chunk": "class RWKVBlock(BaseLayer):\n def __init__(self, context, name, hidden_size, intermediate_size, attention_hidden_size, eps, layer_id):\n super().__init__(context, name)\n self.hidden_size = hidden_siz... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.receptance_linear = Linear(
self.context, 'receptance', self.hidden_size, self.attention_hidden_size, use_bias=False)
self.value_linear = Linear(
self.context, 'value', self.hidden_size, self.attention_hidden_size, use_bias=False)
self.output_linear = Linear(
... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 30,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/3739"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/model.py",
"retrieved_chunk": " if self.layer_id == 0:\n self.pre_ln = LayerNorm(self.context, 'pre_ln', self.hidden_size, self.eps)\n self.ln1 = LayerNorm(self.context, 'ln1', self.hidden_size, self.eps)\n self.ln2 ... | context, 'key', self.hidden_size, self.attention_hidden_size, use_bias=False) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " self.key_linear = Linear(\n self.context, 'key', self.hidden_size, self.intermediate_size, use_bias=False, **key_tp_setting)\n self.receptance_linear = Linear(\n self.context, 'recep... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
time_first_key = '.'.join([self.context, 'time_first'])
time_first_np = self.get_param_from_state_dict(time_first_key, [self.hidden_size])
self.time_first = self.add_initialized_input_tensor(time_first_np, time_first_key)
time_mix_key_name = '.'.join([self.context, 'time_mix_key'])
... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 40,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 41,
"task_id": "project_cc_python/3741"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " time_mix_receptance_np = self.get_param_from_state_dict(time_mix_receptance_name, [1, 1, self.hidden_size])\n self.time_mix_receptance = self.add_initialized_input_tensor(time_mix_receptance_np, time_mix_... | add_initialized_input_tensor(time_decay_np, time_decay_key) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " temp_layer_state = layer_state[0]\n key = self.gate(graph, hidden, self.time_mix_key, temp_layer_state)\n receptance = self.gate(graph, hidden, self.time_mix_receptance, temp_layer_state)\n ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
e1 = ops.exp(graph, ops.sub(graph, max_state, max_for_output))
e2 = ops.exp(graph, ops.sub(graph, temp1, max_for_output))
numerator = ops.add(graph, ops.mul(graph, e1, num_state), ops.mul(graph, e2, value))
denominator = ops.add(graph, ops.mul(graph, e1, den_state), e2)
... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 85,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 86,
"task_id": "project_cc_python/3750"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " output = ops.mul(graph, receptance, value)\n return output, layer_state\nclass TPRWKVFeedforward(BaseRWKVFeedforward):\n def collect_bind_layer_weights(self):\n key_tp_setting = {\n '... | maximum(graph, max_state, temp1) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " self.key_linear = Linear(\n self.context, 'key', self.hidden_size, self.intermediate_size, use_bias=False, **key_tp_setting)\n self.receptance_linear = Linear(\n self.context, 'recep... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.time_decay = self.add_initialized_input_tensor(time_decay_np, time_decay_key)
time_first_key = '.'.join([self.context, 'time_first'])
time_first_np = self.get_param_from_state_dict(time_first_key, [self.hidden_size])
self.time_first = self.add_initialized_input_tensor(time_first_n... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 39,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 40,
"task_id": "project_cc_python/3740"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " time_mix_receptance_np = self.get_param_from_state_dict(time_mix_receptance_name, [1, 1, self.hidden_size])\n self.time_mix_receptance = self.add_initialized_input_tensor(time_mix_receptance_np, time_mix_... | get_param_from_state_dict(time_decay_key, [self.hidden_size]) |
{
"list": [
{
"filename": "poptransformer/layers/rms_layer_norm.py",
"retrieved_chunk": " def __call__(self, graph, x):\n variance_epsilon = ops.constant(graph, np.array(self.eps).astype(np.float32), 'variance_epsilon')\n variance = ops.cast(graph, x, 'FLOAT')\n variance = ops.... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
e2 = ops.exp(graph, ops.sub(graph, temp1, max_for_output))
numerator = ops.add(graph, ops.mul(graph, e1, num_state), ops.mul(graph, e2, value))
denominator = ops.add(graph, ops.mul(graph, e1, den_state), e2)
output = ops.div(graph, numerator, denominator)
ti... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 86,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 87,
"task_id": "project_cc_python/3751"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " output = ops.mul(graph, receptance, value)\n return output, layer_state\nclass TPRWKVFeedforward(BaseRWKVFeedforward):\n def collect_bind_layer_weights(self):\n key_tp_setting = {\n '... | exp(graph, ops.sub(graph, max_state, max_for_output)) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " temp_layer_state = layer_state[0]\n key = self.gate(graph, hidden, self.time_mix_key, temp_layer_state)\n receptance = self.gate(graph, hidden, self.time_mix_receptance, temp_layer_state)\n ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
time_decay = ops.cast(graph, self.time_decay, 'FLOAT')
key = ops.cast(graph, key, 'FLOAT')
value = ops.cast(graph, value, 'FLOAT')
time_first = ops.cast(graph, self.time_first, 'FLOAT')
with graph.nameScope('rwkv_linear_attention'):
temp1 = ops.add(g... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 77,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 78,
"task_id": "project_cc_python/3748"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " output = ops.mul(graph, receptance, value)\n return output, layer_state\nclass TPRWKVFeedforward(BaseRWKVFeedforward):\n def collect_bind_layer_weights(self):\n key_tp_setting = {\n '... | precision == 'fp16': |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " temp_layer_state = layer_state[0]\n key = self.gate(graph, hidden, self.time_mix_key, temp_layer_state)\n receptance = self.gate(graph, hidden, self.time_mix_receptance, temp_layer_state)\n ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
key = ops.cast(graph, key, 'FLOAT')
value = ops.cast(graph, value, 'FLOAT')
time_first = ops.cast(graph, self.time_first, 'FLOAT')
with graph.nameScope('rwkv_linear_attention'):
temp1 = ops.add(graph, key, time_first)
max_for_output = ops.maximum(gra... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 78,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 79,
"task_id": "project_cc_python/3749"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " output = ops.mul(graph, receptance, value)\n return output, layer_state\nclass TPRWKVFeedforward(BaseRWKVFeedforward):\n def collect_bind_layer_weights(self):\n key_tp_setting = {\n '... | cast(graph, self.time_decay, 'FLOAT') |
{
"list": [
{
"filename": "poptransformer/models/rwkv/model.py",
"retrieved_chunk": "class RWKVBlock(BaseLayer):\n def __init__(self, context, name, hidden_size, intermediate_size, attention_hidden_size, eps, layer_id):\n super().__init__(context, name)\n self.hidden_size = hidden_siz... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.receptance_linear = Linear(self.context, 'receptance', self.hidden_size, self.hidden_size, use_bias=False)
self.value_linear = Linear(self.context, 'value', self.intermediate_size, self.hidden_size, use_bias=False)
time_mix_key_name = '.'.join([self.context, 'time_mix_key'])
time_... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/ffn.py",
"groundtruth_start_lineno": 27,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/3723"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/model.py",
"retrieved_chunk": " if self.layer_id == 0:\n self.pre_ln = LayerNorm(self.context, 'pre_ln', self.hidden_size, self.eps)\n self.ln1 = LayerNorm(self.context, 'ln1', self.hidden_size, self.eps)\n self.ln2 ... | context, 'key', self.hidden_size, self.intermediate_size, use_bias=False) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/attention.py",
"retrieved_chunk": " y2 = ops.sub(graph, ops.constant(graph, np.array(1).astype(self.np_float_type)), w)\n y2 = ops.mul(graph, y2, b)\n y = ops.add(graph, y1, y2)\n return y\n def __call__(self, graph, ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
key = ops.mul(graph, key, key)
value = self.value_linear(graph, key)
receptance = self.receptance_linear(graph, receptance)
receptance = ops.sigmoid(graph, receptance)
output = ops.mul(graph, receptance, value)
return output, layer_state
class TPRWKVFeedforward(BaseRWK... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/ffn.py",
"groundtruth_start_lineno": 52,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 53,
"task_id": "project_cc_python/3731"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/attention.py",
"retrieved_chunk": " layer_state[1] = hidden\n key = self.key_linear(graph, key)\n value = self.value_linear(graph, value)\n receptance = self.receptance_linear(graph, receptance)\n ... | relu(graph, key) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/attention.py",
"retrieved_chunk": " layer_state[1] = hidden\n key = self.key_linear(graph, key)\n value = self.value_linear(graph, value)\n receptance = self.receptance_linear(graph, receptance)\n ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
receptance = ops.sigmoid(graph, receptance)
output = ops.mul(graph, receptance, value)
return output, layer_state
class RWKVFeedforward(TPRWKVFeedforward, BaseRWKVFeedforward):
layer_class_map = {
'tp': TPRWKVFeedforward,
'shard': BaseRWKVFeedforward}
def __init__(sel... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/ffn.py",
"groundtruth_start_lineno": 94,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 95,
"task_id": "project_cc_python/3736"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/attention.py",
"retrieved_chunk": " with graph.nameScope('rwkv_linear_attention'):\n temp1 = ops.add(graph, key, time_first)\n max_for_output = ops.maximum(graph, max_state, temp1)\n e1 = ops.exp(graph, ops.s... | replicated_allgather(graph, receptance) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " self.key_linear = Linear(\n self.context, 'key', self.hidden_size, self.intermediate_size, use_bias=False, **key_tp_setting)\n self.receptance_linear = Linear(\n self.context, 'recep... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
time_first_key = '.'.join([self.context, 'time_first'])
time_first_np = self.get_param_from_state_dict(time_first_key, [self.hidden_size])
time_first_np = shard(time_first_np, self.num_replicas, -1)
self.time_first = self.add_initialized_input_tensor(time_first_np, time_first_key, **vs... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 129,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 130,
"task_id": "project_cc_python/3757"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " time_mix_receptance_np = self.get_param_from_state_dict(time_mix_receptance_name, [1, 1, self.hidden_size])\n self.time_mix_receptance = self.add_initialized_input_tensor(time_mix_receptance_np, time_mix_... | add_initialized_input_tensor(time_decay_np, time_decay_key, **vs_setting) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " self.key_linear = Linear(\n self.context, 'key', self.hidden_size, self.intermediate_size, use_bias=False, **key_tp_setting)\n self.receptance_linear = Linear(\n self.context, 'recep... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.time_decay = self.add_initialized_input_tensor(time_decay_np, time_decay_key, **vs_setting)
time_first_key = '.'.join([self.context, 'time_first'])
time_first_np = self.get_param_from_state_dict(time_first_key, [self.hidden_size])
time_first_np = shard(time_first_np, self.num_repl... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 128,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 129,
"task_id": "project_cc_python/3756"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " time_mix_receptance_np = self.get_param_from_state_dict(time_mix_receptance_name, [1, 1, self.hidden_size])\n self.time_mix_receptance = self.add_initialized_input_tensor(time_mix_receptance_np, time_mix_... | num_replicas, -1) |
{
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " self.key_linear = Linear(\n self.context, 'key', self.hidden_size, self.intermediate_size, use_bias=False, **key_tp_setting)\n self.receptance_linear = Linear(\n self.context, 'recep... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.receptance_linear = Linear(
self.context, 'receptance', self.hidden_size, self.attention_hidden_size, use_bias=False, **key_tp_setting)
self.value_linear = Linear(
self.context, 'value', self.hidden_size, self.attention_hidden_size, use_bias=False, **key_tp_setting)
... | {
"context_start_lineno": 0,
"file": "poptransformer/models/rwkv/attention.py",
"groundtruth_start_lineno": 117,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 118,
"task_id": "project_cc_python/3754"
} | {
"list": [
{
"filename": "poptransformer/models/rwkv/ffn.py",
"retrieved_chunk": " self.key_linear = Linear(\n self.context, 'key', self.hidden_size, self.intermediate_size, use_bias=False, **key_tp_setting)\n self.receptance_linear = Linear(\n self.context, 'recep... | context, 'key', self.hidden_size, self.attention_hidden_size, use_bias=False, **key_tp_setting) |
{
"list": [
{
"filename": "poptransformer/models/chatglm2/emebdding.py",
"retrieved_chunk": " def collect_bind_layer_weights(self):\n self.wte = Embedding(self.context, None, self.vocab_size, self.embd_size)\n def __call__(self, graph, input_ids, sequence_length):\n with graph.name... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
return ops.remap_tensor(graph, embeds)
class TPTransformerEmbedding(BaseTransformerEmbedding):
def __call__(self, graph, input_ids, position_ids, sequence_length):
with graph.nameScope(self.context):
input_embeds = self.wte(graph, input_ids, sequence_length)
pos_embeds = ... | {
"context_start_lineno": 0,
"file": "poptransformer/models/gpt2/embedding.py",
"groundtruth_start_lineno": 34,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 35,
"task_id": "project_cc_python/3765"
} | {
"list": [
{
"filename": "poptransformer/models/chatglm2/emebdding.py",
"retrieved_chunk": " embeds = graph.aiGraphcore.replicatedallreduce([embeds])\n return embeds\nclass TransformerEmbedding(TPTransformerEmbedding, BaseTransformerEmbedding):\n layer_class_map = {\"tp\": TPTran... | add(graph, input_embeds, pos_embeds) |
{
"list": [
{
"filename": "poptransformer/models/chatglm2/emebdding.py",
"retrieved_chunk": " def collect_bind_layer_weights(self):\n self.wte = Embedding(self.context, None, self.vocab_size, self.embd_size)\n def __call__(self, graph, input_ids, sequence_length):\n with graph.name... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
class TPTransformerEmbedding(BaseTransformerEmbedding):
def __call__(self, graph, input_ids, position_ids, sequence_length):
with graph.nameScope(self.context):
input_embeds = self.wte(graph, input_ids, sequence_length)
pos_embeds = self.wpe(graph, position_ids, sequence_length)
... | {
"context_start_lineno": 0,
"file": "poptransformer/models/gpt2/embedding.py",
"groundtruth_start_lineno": 35,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 36,
"task_id": "project_cc_python/3766"
} | {
"list": [
{
"filename": "poptransformer/models/chatglm2/emebdding.py",
"retrieved_chunk": " embeds = graph.aiGraphcore.replicatedallreduce([embeds])\n return embeds\nclass TransformerEmbedding(TPTransformerEmbedding, BaseTransformerEmbedding):\n layer_class_map = {\"tp\": TPTran... | remap_tensor(graph, embeds) |
{
"list": [
{
"filename": "src/nvidia_util.py",
"retrieved_chunk": " obj._present = len(obj._s) > 0\n return obj\n def yaml(self, dumper):\n if self._present:\n return dumper.represent_str(self._s)\n return dumper.represent_none(None)\n def html(self):\n ... | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
# ht... |
failsafe_firmware_loaded_information = util.Na("Not provided")
if failsafe_firmware_status:
failsafe_firmware_loaded_information = failsafe_firmware_loaded
serial_number_information = util.Na("Not provided")
if serial_number_status:
serial_number_information = se... | {
"context_start_lineno": 0,
"file": "src/ajantv2_util.py",
"groundtruth_start_lineno": 67,
"repository": "nvidia-holoscan-holoscan-test-suite-e7a809d",
"right_context_start_lineno": 68,
"task_id": "project_cc_python/3830"
} | {
"list": [
{
"filename": "src/nvidia_util.py",
"retrieved_chunk": "yaml.add_representer(EepromStr, lambda dumper, data: data.yaml(dumper))\nclass EepromMac:\n def __init__(self, b):\n self._s = \":\".join([\"%02X\" % c for c in b])\n def __str__(self):\n return self._s\n def ya... | Hex(pci_device_id) |
{
"list": [
{
"filename": "poptransformer/models/gpt2/model.py",
"retrieved_chunk": " x = ops.add(graph, x, temp_x)\n return x\nclass Transformer(BaseLayer):\n def __init__(self, context, name, vocab_size, embd_size, eps,\n n_head, max_length, n_layer, layer_per_ip... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
self.wpe = Embedding(self.context, 'wpe', self.max_position, self.embd_size)
def __call__(self, graph, input_ids, position_ids, sequence_length):
with graph.nameScope(self.context):
input_embeds = self.wte(graph, input_ids, sequence_length)
pos_embeds = self.wpe(graph, posi... | {
"context_start_lineno": 0,
"file": "poptransformer/models/gpt2/embedding.py",
"groundtruth_start_lineno": 27,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/3764"
} | {
"list": [
{
"filename": "poptransformer/models/chatglm2/emebdding.py",
"retrieved_chunk": " def collect_bind_layer_weights(self):\n self.wte = Embedding(self.context, None, self.vocab_size, self.embd_size)\n def __call__(self, graph, input_ids, sequence_length):\n with graph.name... | context, 'wte', self.vocab_size, self.embd_size) |
{
"list": [
{
"filename": "poptransformer/utils/prepare.py",
"retrieved_chunk": " REGISTRY.register(key, value)\n tensor_type = TensorType(global_args.precision)\n REGISTRY.register('tensor_type', tensor_type)\ndef register_config_logger(config):\n popart.getLogger().setLevel(config.po... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
REGISTRY.register('serial_factor', None)
REGISTRY.register('serial_mode', None)
REGISTRY.register('partialtype', None)
REGISTRY.register('amp', None)
REGISTRY.register('state_dict', {})
# main graph is to be built for certain, we build it here, move to other place if there be more comments
| {
"context_start_lineno": 0,
"file": "poptransformer/utils/registry.py",
"groundtruth_start_lineno": 40,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 41,
"task_id": "project_cc_python/3771"
} | {
"list": [
{
"filename": "poptransformer/utils/prepare.py",
"retrieved_chunk": " register_config_logger(config)\n model = instantiate(config.model)\n session = instantiate(config.session)\n model.build_graph()\n model.graph.saveInitializersExternally(\n model.initializers,\n ... | Builder(opsets={'ai.onnx': 10, 'ai.graphcore': 1})) |
{
"list": [
{
"filename": "poptransformer/utils/__init__.py",
"retrieved_chunk": "# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom .registry import REGISTRY\nfrom .device_scope import DeviceScope\nfrom .options_scope import OptionsScope\nfro... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
tensor_type = TensorType(global_args.precision)
REGISTRY.register('tensor_type', tensor_type)
def register_config_logger(config):
popart.getLogger().setLevel(config.popart_log_level.upper())
logger = logging.getLogger('poptransformer')
logger.setLevel(config.log_level.upper())
REGISTRY.registe... | {
"context_start_lineno": 0,
"file": "poptransformer/utils/prepare.py",
"groundtruth_start_lineno": 23,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 24,
"task_id": "project_cc_python/3774"
} | {
"list": [
{
"filename": "poptransformer/utils/__init__.py",
"retrieved_chunk": "# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom .registry import REGISTRY\nfrom .device_scope import DeviceScope\nfrom .options_scope import OptionsScope\nfro... | register(key, value) |
{
"list": [
{
"filename": "poptransformer/layers/base_layer.py",
"retrieved_chunk": " @property\n def np_float_type(self):\n return REGISTRY.get('tensor_type').np_float_type\n @property\n def precision(self):\n return REGISTRY.get('tensor_type').precision\n @property\n ... | # Copyright (c) 2023 Graphcore Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
REGISTRY.get('logger').debug(f'using amp: {self.amp}')
if self.partialtype is not None:
self.default_partialtype = REGISTRY.get('partialtype')
REGISTRY.update('partialtype', self.partialtype)
REGISTRY.get('logger').debug(f'using partialtype: {self.partialtype}')
... | {
"context_start_lineno": 0,
"file": "poptransformer/utils/options_scope.py",
"groundtruth_start_lineno": 32,
"repository": "graphcore-PopTransformer-1314598",
"right_context_start_lineno": 33,
"task_id": "project_cc_python/3773"
} | {
"list": [
{
"filename": "poptransformer/layers/base_layer.py",
"retrieved_chunk": " return OptionsScope(amp, partialtype, serial_factor, serial_mode)\n def device_scope(self, graph, virtual_graph_id=None, pipeline_stage_id=None, outline_attr=None):\n return DeviceScope(graph, virtua... | update('amp', self.amp) |
{
"list": [
{
"filename": "adapt/http.py",
"retrieved_chunk": " async def create_user_dm_channel(self, recipient_id: int) -> DMChannel:\n payload: CreateDMChannelPayload = {\n 'type': 'dm',\n 'recipient_id': recipient_id,\n }\n return await self.request('P... | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
from .enums import ChannelType
from .message import Message
from .object import AdaptObject
if TYPE_CHECKING:
from typing import Self, TypeAlias
from .guild import Guild
from .user import User
fro... |
if TYPE_CHECKING:
MessageableChannel: TypeAlias = TextChannel | PrivateChannel | PartialMessageable
| {
"context_start_lineno": 0,
"file": "adapt/models/channel.py",
"groundtruth_start_lineno": 351,
"repository": "AdaptChat-adapt.py-9e079c0",
"right_context_start_lineno": 352,
"task_id": "project_cc_python/3849"
} | {
"list": [
{
"filename": "adapt/models/user.py",
"retrieved_chunk": " self._dm_channel = found\n return found\n async def create_dm(self) -> DMChannel:\n \"\"\"|coro|\n Creates a DM channel with this user. This makes the API call despite whether a DM channel alr... | id} recipient_id={self.recipient_id}>' |
{
"list": [
{
"filename": "adapt/models/member.py",
"retrieved_chunk": " super().__init__(connection=guild._connection, id=id)\n self.guild = guild\n def __repr__(self) -> str:\n return f'<{self.__class__.__name__} id={self.id} guild_id={self.guild.id}>'\nclass Member(User, Par... | from __future__ import annotations
from typing import TYPE_CHECKING
from .bitflags import MessageFlags
from .enums import MessageType
from .object import AdaptObject
from ..util import MISSING
if TYPE_CHECKING:
from typing import Self
from .channel import MessageableChannel
from .guild import Guild
... | {
"context_start_lineno": 0,
"file": "adapt/models/message.py",
"groundtruth_start_lineno": 143,
"repository": "AdaptChat-adapt.py-9e079c0",
"right_context_start_lineno": 144,
"task_id": "project_cc_python/3855"
} | {
"list": [
{
"filename": "adapt/models/channel.py",
"retrieved_chunk": " factory = AnnouncementChannel\n else:\n # TODO\n factory = GuildChannel\n return factory(guild=guild, data=data)\nclass PrivateChannel(AdaptObject, ABC):\n \"\"\"Represents a DM or group channel in ... | id} channel_id={self.channel.id} author_id={self.author.id}>' | |
{
"list": [
{
"filename": "adapt/types/user.py",
"retrieved_chunk": "from __future__ import annotations\nfrom typing import Literal, TypedDict, TypeAlias\nfrom . import Snowflake\n__all__ = (\n 'TokenRetrievalMethod',\n 'RelationshipType',\n 'LoginRequest',\n 'LoginResponse',\n 'CreateU... | from __future__ import annotations
import aiohttp
import asyncio
from typing import Literal, TYPE_CHECKING
from .polyfill import removeprefix, removesuffix
from .server import AdaptServer
from .util import extract_user_id_from_token, resolve_image, MISSING
if TYPE_CHECKING:
from typing import Any, Final, TypeAl... |
RequestMethod: TypeAlias = Literal['GET', 'POST', 'PATCH', 'PUT', 'DELETE']
class HTTPClient:
"""Represents an HTTP client that makes requests to Adapt over HTTP."""
__slots__ = ('loop', 'session', 'client_id', 'server_url', '_token')
def __init__(
self,
*,
loop: asyncio.Abstra... | {
"context_start_lineno": 0,
"file": "adapt/http.py",
"groundtruth_start_lineno": 51,
"repository": "AdaptChat-adapt.py-9e079c0",
"right_context_start_lineno": 52,
"task_id": "project_cc_python/3843"
} | {
"list": [
{
"filename": "adapt/types/user.py",
"retrieved_chunk": " 'User',\n 'ClientUser',\n 'Relationship',\n)\nTokenRetrievalMethod: TypeAlias = Literal['new', 'revoke', 'reuse']\nclass _LoginRequestRequired(TypedDict):\n email: str\n password: str\nclass LoginRequest(_LoginRequest... | production().api |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.