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": "code/ch02.py", "retrieved_chunk": " table[a_prime] = p\n variables = [var for var in phi.variables if var.name is not name]\n return Factor(variables, table)\ndef condition_multiple(phi: Factor, evidence: Assignment) -> Factor:\n \"\"\" (From Chapter 3)\n...
import networkx as nx import numpy as np from abc import ABC, abstractmethod from scipy.stats import multivariate_normal from ch02 import Assignment, Factor, FactorTable, BayesianNetwork from ch02 import marginalize, condition_multiple class InferenceMethod(ABC): @abstractmethod def infer(self, *args, **kwa...
b = a.select(query) table[b] = table.get(b, default_val=0.0) + w variables = [var for var in bn.variables if var.name in query] phi = Factor(variables, table) phi.normalize() return phi def blanket(bn: BayesianNetwork, a: Assignment, i: int) -> Factor: """ ...
{ "context_start_lineno": 0, "file": "code/ch03.py", "groundtruth_start_lineno": 115, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 116, "task_id": "project_cc_python/1827" }
{ "list": [ { "filename": "code/ch02.py", "retrieved_chunk": " for i in list(nx.topological_sort(self.graph)):\n name, phi = self.variables[i].name, self.factors[i]\n a[name] = (condition_multiple(phi, a).sample())[name]\n return a", "score": 88.76318620486593...
sample()[name]
{ "list": [ { "filename": "code/ch09.py", "retrieved_chunk": " return self.U(s)\n a = self.explore(s)\n s_prime, r = self.P.randstep(s, a)\n q = r + self.P.gamma * self.simulate(s_prime, d - 1)\n self.N[(s, a)] += 1\n self.Q[(s, a)] += (q - self.Q[(s, a)])...
import numpy as np import random from collections import deque from typing import Callable from ch12 import scale_gradient from ch16 import RLMDP class IncrementalEstimate(): def __init__(self, mu: float | np.ndarray, alpha: Callable[[int], float], m: int): self.mu = mu # mean estimate se...
self.ell = (s, a, r) class SarsaLambda(Sarsa): def __init__(self, S: list[int], A: list[int], gamma: float, Q: np.ndarray, N: np.ndarray, alpha: float, lam: float, ell: ...
{ "context_start_lineno": 0, "file": "code/ch17.py", "groundtruth_start_lineno": 66, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 67, "task_id": "project_cc_python/1813" }
{ "list": [ { "filename": "code/ch16.py", "retrieved_chunk": " self.U = U # value function\n self.planner = planner\nclass MaximumLikelihoodMDP(ModelBasedMDP):\n def __init__(self,\n S: list[int],\n A: list[int],\n N: np.ndarray,\n ...
gamma * self.Q[s, a]) - self.Q[s_prev, a_prev])
{ "list": [ { "filename": "code/ch06.py", "retrieved_chunk": " evidence = Assignment(evidence | assignment)\n phi = M.infer(self.bn, query, evidence)\n u = np.sum([p*U(a) for a, p in phi.table.items()])\n if u > best_u:\n best_a, best_u = assi...
import networkx as nx import numpy as np from abc import ABC, abstractmethod from scipy.stats import multivariate_normal from ch02 import Assignment, Factor, FactorTable, BayesianNetwork from ch02 import marginalize, condition_multiple class InferenceMethod(ABC): @abstractmethod def infer(self, *args, **kwa...
phi = condition_multiple(phi, evidence) for name in (set(phi.variable_names) - set(query)): phi = marginalize(phi, name) phi.normalize() return phi class VariableElimination(DiscreteInferenceMethod): """ An implementation of the sum-product variable elimination alg...
{ "context_start_lineno": 0, "file": "code/ch03.py", "groundtruth_start_lineno": 33, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 34, "task_id": "project_cc_python/1820" }
{ "list": [ { "filename": "code/ch06.py", "retrieved_chunk": " The method additionally takes an inference strategy `M`.\n \"\"\"\n phi = M.infer(self.bn, query, evidence)\n voi = -(self.solve(evidence, M)[1])\n query_vars = [var for var in self.chance_vars if var.nam...
prod(bn.factors)
{ "list": [ { "filename": "code/tests/ch03/test_discreteinferencemethods.py", "retrieved_chunk": " def test_exact_inference(self, tol=1e-15):\n M = ExactInference()\n probabilities = self.run_inference(M)\n assert np.all(np.abs(probabilities - self.exact_probabilities) < tol)\n...
import numpy as np import sys; sys.path.append('./code/'); sys.path.append('../../') from typing import Any from ch07 import MDP from ThreeTileStraightlineHexworld import gamma, S, A, T, R, TR, policy class TestMDP(): P = MDP(gamma, S, A, T, R, TR) @staticmethod def U1(s: Any) -> float: return ...
assert self.P.backup(TestMDP.U2_vec, s=1) == 1.23 def test_randstep(self, tol=1e-2): count = 0 n_trials = 100000 for _ in range(n_trials): possible_results = [(1, -1.0), (2, 0.0)] result = self.P.randstep(s=1, a="east") assert result in possible_...
{ "context_start_lineno": 0, "file": "code/tests/ch07/test_mdp.py", "groundtruth_start_lineno": 50, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 51, "task_id": "project_cc_python/1833" }
{ "list": [ { "filename": "code/tests/ch03/test_discreteinferencemethods.py", "retrieved_chunk": " def test_gibbs_sampling(self, tol=1e-2, n_trials=10):\n for _ in range(n_trials):\n M = GibbsSampling(m_samples=10000, m_burnin=1000, m_skip=5, ordering=[2, 0, 1])\n proba...
backup(TestMDP.U2, s=1) == 1.23
{ "list": [ { "filename": "code/ch16.py", "retrieved_chunk": " @abstractmethod\n def lookahead(self, s: int, a: int) -> float:\n pass\n @abstractmethod\n def update(self, s: int, a: int, r: float, s_prime: int):\n pass\nclass ModelBasedMDP(RLMDP):\n def __init__(self, S: l...
import numpy as np import random from collections import deque from typing import Callable from ch12 import scale_gradient from ch16 import RLMDP class IncrementalEstimate(): def __init__(self, mu: float | np.ndarray, alpha: Callable[[int], float], m: int): self.mu = mu # mean estimate se...
class Sarsa(ModelFreeMDP): def __init__(self, S: list[int], A: list[int], gamma: float, Q: np.ndarray, alpha: float, ell: tuple[int, int, float]): super().__init__(A, gamma, Q, alpha) # The actio...
{ "context_start_lineno": 0, "file": "code/ch17.py", "groundtruth_start_lineno": 44, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 45, "task_id": "project_cc_python/1812" }
{ "list": [ { "filename": "code/ch16.py", "retrieved_chunk": " self.U = U # value function\n self.planner = planner\nclass MaximumLikelihoodMDP(ModelBasedMDP):\n def __init__(self,\n S: list[int],\n A: list[int],\n N: np.ndarray,\n ...
gamma * np.max(self.Q[s_prime])) - self.Q[s, a])
{ "list": [ { "filename": "code/tests/ch07/test_mdp.py", "retrieved_chunk": " def test_randstep(self, tol=1e-2):\n count = 0\n n_trials = 100000\n for _ in range(n_trials):\n possible_results = [(1, -1.0), (2, 0.0)]\n result = self.P.randstep(s=1, a=\"east...
import networkx as nx import numpy as np import sys; sys.path.append('./code/'); sys.path.append('../../') from ch02 import Variable, Assignment, FactorTable, Factor, BayesianNetwork from ch03 import ExactInference from ch06 import SimpleProblem class TestSimpleProblemMethods(): # This Decision Network is taken ...
# Compute real answer explicitly probs_query_given_evidence = M.infer(self.bn, query=["O_2"], evidence=Assignment({"O_1": 1})) # We know ExactInference() works from past tests base_result = self.P.solve(evidence=Assignment({"O_1": 1}), M=M) # We know SimpleProblem.solve(...) works if the abo...
{ "context_start_lineno": 0, "file": "code/tests/ch06/test_simpleproblem.py", "groundtruth_start_lineno": 69, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 70, "task_id": "project_cc_python/1838" }
{ "list": [ { "filename": "code/tests/ch07/test_mdp.py", "retrieved_chunk": " def test_randstep(self, tol=1e-2):\n count = 0\n n_trials = 100000\n for _ in range(n_trials):\n possible_results = [(1, -1.0), (2, 0.0)]\n result = self.P.randstep(s=1, a=\"east...
value_of_information(query=["O_2"], evidence=Assignment({"O_1": 1}), M=M)
{ "list": [ { "filename": "code/ch06.py", "retrieved_chunk": " self.bn = bn\n self.chance_vars = chance_vars\n self.decision_vars = decision_vars\n self.utility_vars = utility_vars\n self.utilities = utilities\n def solve(self, evidence: Assignment, M: DiscreteInf...
import networkx as nx import numpy as np import sys; sys.path.append('./code/'); sys.path.append('../../') from ch02 import Variable, Assignment, FactorTable, Factor, BayesianNetwork from ch03 import ExactInference from ch06 import SimpleProblem class TestSimpleProblemMethods(): # This Decision Network is taken ...
# Compute real answer explicitly M = ExactInference() # We know ExactInference works because it is already tested tmp = M.infer(self.bn, query=["D"], evidence=Assignment(Assignment({"T": 1}) | a)) utility_test1 = (tmp.table[Assignment({'D': 0})] * -1) + (tmp.table[Assi...
{ "context_start_lineno": 0, "file": "code/tests/ch06/test_simpleproblem.py", "groundtruth_start_lineno": 51, "repository": "griffinbholt-decisionmaking-code-py-e08645e", "right_context_start_lineno": 52, "task_id": "project_cc_python/1836" }
{ "list": [ { "filename": "code/tests/ch02/test_bayesiannetwork.py", "retrieved_chunk": " Assignment({\"d\": 0, \"e\": 0}): 0.96, Assignment({\"d\": 0, \"e\": 1}): 0.03,\n Assignment({\"d\": 1, \"e\": 0}): 0.04, Assignment({\"d\": 1, \"e\": 1}): 0.97})),\n Factor([C, E], F...
solve(evidence=a, M=ExactInference())
{ "list": [ { "filename": "jiggybase/collection.py", "retrieved_chunk": "from .models import CollectionPatchRequest, PluginAuthConfigOAuth, PatchPluginOAuthConfigRequest\nfrom .models import DocumentMetadata\nfrom typing import Union, List\nclass Collection(collection.Collection):\n \"\"\"\n der...
from typing import Any, Optional, List from pydantic import BaseConfig, EmailStr import enum from .models import CollectionPostRequest from .models.org import Org as OrgModel from .models.org import OrgRole, OrgMember, OrgPatchRequest from .models import PromptTask, PromptMessage, PromptTaskPostRequest, PromptTaskT...
print(rsp.json()) return Collection(self.session, **rsp.json()) def collections(self) -> list[Collection]: rsp = self.session.get(f"/orgs/{self.id}/collections") return [Collection(self.session, **c) for c in rsp.json()] def collection(self, name: str) -> Collection: c...
{ "context_start_lineno": 0, "file": "jiggybase/org.py", "groundtruth_start_lineno": 28, "repository": "jiggy-ai-jiggybase-068b82b", "right_context_start_lineno": 29, "task_id": "project_cc_python/1917" }
{ "list": [ { "filename": "jiggybase/collection.py", "retrieved_chunk": " super().__init__(*args, **kwargs)\n self.session = session \n api_key = self.session.api_key\n self.plugin_session = JiggyBaseSession(host=f'https://{kwargs[\"fqdn\"]}', api='', api_key=api_key...
id}/collections", model=CollectionPostRequest(**locals()))
{ "list": [ { "filename": "jiggybase/collection.py", "retrieved_chunk": " Delete a collection. Warning: this is permanent.\n \"\"\"\n self.session.delete(f\"/orgs/{self.org_id}/collections/{self.id}\")\n def get_chat_config(self) -> CollectionChatConfig:\n \"\"\"\n ...
from typing import Any, Optional, List from pydantic import BaseConfig, EmailStr import enum from .models import CollectionPostRequest from .models.org import Org as OrgModel from .models.org import OrgRole, OrgMember, OrgPatchRequest from .models import PromptTask, PromptMessage, PromptTaskPostRequest, PromptTaskT...
def __repr__(self) -> str: return str(self)
{ "context_start_lineno": 0, "file": "jiggybase/org.py", "groundtruth_start_lineno": 112, "repository": "jiggy-ai-jiggybase-068b82b", "right_context_start_lineno": 113, "task_id": "project_cc_python/1919" }
{ "list": [ { "filename": "jiggybase/collection.py", "retrieved_chunk": " \"\"\"\n Update the chat configuration for this collection.\n \"\"\"\n rsp = self.session.patch(f\"/orgs/{self.org_id}/collections/{self.id}/chat_config/{model}\", model=PatchCollectionChatConfig(prom...
gpt4_credits:4}, name={self.name:20}, description={self.description})"
{ "list": [ { "filename": "tasks/retrieval.py", "retrieved_chunk": " loss = sum(loss_dict.values())\n optimizer.zero_grad()\n scaler.scale(loss).backward()\n if config.optimizer.max_grad_norm > 0:\n scaler.unscale_(optimizer)\n torch.nn.utils.clip_...
import time import datetime import logging import wandb import os from os.path import join import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from models.model_vqa import Singularity from utils.logger import log_dict_to_wandb, setup_wandb from utils.config_utils import setup_main from...
metric_logger.update(lr=optimizer.param_groups[0]["lr"]) if is_main_process() and config.wandb.enable \ and global_step % log_freq == 0: logs = metric_logger.get_global_avg_dict() log_dict_to_wandb(logs, step=global_step, prefix="train/") global_step +=...
{ "context_start_lineno": 0, "file": "tasks/vqa.py", "groundtruth_start_lineno": 76, "repository": "JerryYLi-svitt-c8806b3", "right_context_start_lineno": 77, "task_id": "project_cc_python/1906" }
{ "list": [ { "filename": "tasks/retrieval.py", "retrieved_chunk": " # logging\n for name in loss_names:\n value = loss_dict[name]\n value = value if isinstance(value, float) else value.item()\n metric_logger.update(**{f\"{media_type}-{name}\": value})\n ...
update(loss=loss.item())
{ "list": [ { "filename": "jiggybase/collection.py", "retrieved_chunk": " Delete a collection. Warning: this is permanent.\n \"\"\"\n self.session.delete(f\"/orgs/{self.org_id}/collections/{self.id}\")\n def get_chat_config(self) -> CollectionChatConfig:\n \"\"\"\n ...
from typing import Any, Optional, List from pydantic import BaseConfig, EmailStr import enum from .models import CollectionPostRequest from .models.org import Org as OrgModel from .models.org import OrgRole, OrgMember, OrgPatchRequest from .models import PromptTask, PromptMessage, PromptTaskPostRequest, PromptTaskT...
def __repr__(self) -> str: return str(self)
{ "context_start_lineno": 0, "file": "jiggybase/org.py", "groundtruth_start_lineno": 112, "repository": "jiggy-ai-jiggybase-068b82b", "right_context_start_lineno": 113, "task_id": "project_cc_python/1918" }
{ "list": [ { "filename": "jiggybase/collection.py", "retrieved_chunk": " \"\"\"\n Update the chat configuration for this collection.\n \"\"\"\n rsp = self.session.patch(f\"/orgs/{self.org_id}/collections/{self.id}/chat_config/{model}\", model=PatchCollectionChatConfig(prom...
subscription_status:8}, gpt4_credts={self.gpt4_credits:4}, name={self.name:20}, description={self.description})"
{ "list": [ { "filename": "tasks/vqa.py", "retrieved_chunk": " metric_logger.synchronize_between_processes()\n logger.info(f\"Averaged train stats: {metric_logger.global_avg()}\")\n return global_step\n@torch.no_grad()\ndef evaluation(model, data_loader, tokenizer, device, config):\n model...
import os import time import datetime import logging import numpy as np import torch import torch.distributed as dist from einops import rearrange from utils.basic_utils import MetricLogger from utils.distributed import get_rank, get_world_size from utils.eval import reorder_frames from utils.visualization import sav...
for image, img_id in iterator: image = image.to(device, non_blocking=True) if config.eval_frame_ensemble == "concat": # default image_feat, pooled_image_feat = model.encode_image(image) # (bsz, #frm*L, d), (bsz, #frm, d) image_feat = image_feat.unsqueeze(1) # (bsz, 1, #...
{ "context_start_lineno": 0, "file": "tasks/retrieval_utils.py", "groundtruth_start_lineno": 60, "repository": "JerryYLi-svitt-c8806b3", "right_context_start_lineno": 61, "task_id": "project_cc_python/1903" }
{ "list": [ { "filename": "tasks/vqa.py", "retrieved_chunk": " ques_id = int(ques_id.item()) if not isinstance(ques_id, str) else ques_id\n _, pred = topk_prob.max(dim=0)\n result.append({\n \"question_id\": ques_id, \n \"answer\": raw_ans...
log_every(data_loader, 100, header)
{ "list": [ { "filename": "jiggybase/org.py", "retrieved_chunk": " rsp = self.session.post(f\"/orgs/{self.id}/collections\", model=CollectionPostRequest(**locals()))\n print(rsp.json())\n return Collection(self.session, **rsp.json())\n def collections(self) -> list[Collection]:...
from typing import List from .org import Org from .collection import Collection from .models.user import User, ApiKey from .jiggybase_session import JiggyBaseSession from .models.chat import Message, TypedCompletionRequest from pydantic import BaseModel class JiggyBase(): def __init__(self, api_key=None): ...
return Org(self.session, **resp.json()) def collections(self) -> List[Collection]: """ return all Collections in all Orgs that the user is a member of """ resp = self.session.get("/collections") return [Collection(self.session, **c) for c in resp.json()] def...
{ "context_start_lineno": 0, "file": "jiggybase/client.py", "groundtruth_start_lineno": 49, "repository": "jiggy-ai-jiggybase-068b82b", "right_context_start_lineno": 50, "task_id": "project_cc_python/1916" }
{ "list": [ { "filename": "jiggybase/org.py", "retrieved_chunk": " def delete_member(self, email : str):\n \"\"\"\n attempt to remove the specified name from this org\n \"\"\"\n member = [m for m in self.members() if m.email == email]\n if not member:\n ...
post("/orgs", json={"name":name})
{ "list": [ { "filename": "src/cnnClassifier/config/configuration.py", "retrieved_chunk": " data_ingestion_config = DataIngestionConfig(\n root_dir=config.root_dir,\n source_URL=config.source_URL,\n local_data_file=config.local_data_file,\n unzip_dir=...
from cnnClassifier.config.configuration import ConfigurationManager from cnnClassifier.components.prepare_base_model import PrepareBaseModel from cnnClassifier import logger STAGE_NAME = "Prepare base model" class PrepareBaseModelTrainingPipeline: def __init__(self): pass def main(self): con...
if __name__ == '__main__': try: logger.info(f"*******************") logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<") obj = PrepareBaseModelTrainingPipeline() obj.main() logger.info(f">>>>>> stage {STAGE_NAME} completed <<<<<<\n\nx==========x") except Excepti...
{ "context_start_lineno": 0, "file": "src/cnnClassifier/pipeline/stage_02_prepare_base_model.py", "groundtruth_start_lineno": 16, "repository": "krishnaik06-Chicken-Disease-Classification-Projects-d0f5e13", "right_context_start_lineno": 17, "task_id": "project_cc_python/1958" }
{ "list": [ { "filename": "main.py", "retrieved_chunk": " logger.info(f\">>>>>> stage {STAGE_NAME} completed <<<<<<\\n\\nx==========x\")\nexcept Exception as e:\n logger.exception(e)\n raise e\nSTAGE_NAME = \"Training\"\ntry: \n logger.info(f\"*******************\")\n logger.info(f...
update_base_model()
{ "list": [ { "filename": "src/cnnClassifier/config/configuration.py", "retrieved_chunk": " def __init__(\n self,\n config_filepath = CONFIG_FILE_PATH,\n params_filepath = PARAMS_FILE_PATH):\n self.config = read_yaml(config_filepath)\n self.params = read_yaml(para...
from cnnClassifier.config.configuration import ConfigurationManager from cnnClassifier.components.data_ingestion import DataIngestion from cnnClassifier import logger STAGE_NAME = "Data Ingestion stage" class DataIngestionTrainingPipeline: def __init__(self): pass def main(self): config = Co...
if __name__ == '__main__': try: logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<") obj = DataIngestionTrainingPipeline() obj.main() logger.info(f">>>>>> stage {STAGE_NAME} completed <<<<<<\n\nx==========x") except Exception as e: logger.exception(e) rai...
{ "context_start_lineno": 0, "file": "src/cnnClassifier/pipeline/stage_01_data_ingestion.py", "groundtruth_start_lineno": 16, "repository": "krishnaik06-Chicken-Disease-Classification-Projects-d0f5e13", "right_context_start_lineno": 17, "task_id": "project_cc_python/1964" }
{ "list": [ { "filename": "main.py", "retrieved_chunk": " logger.info(f\">>>>>> stage {STAGE_NAME} completed <<<<<<\\n\\nx==========x\")\nexcept Exception as e:\n logger.exception(e)\n raise e\nSTAGE_NAME = \"Prepare base model\"\ntry: \n logger.info(f\"*******************\")\n log...
extract_zip_file()
{ "list": [ { "filename": "src/cnnClassifier/components/evaluation.py", "retrieved_chunk": " self.valid_generator = valid_datagenerator.flow_from_directory(\n directory=self.config.training_data,\n subset=\"validation\",\n shuffle=False,\n **dataflow_...
from cnnClassifier.config.configuration import ConfigurationManager from cnnClassifier.components.evaluation import Evaluation from cnnClassifier import logger STAGE_NAME = "Evaluation stage" class EvaluationPipeline: def __init__(self): pass def main(self): config = ConfigurationManager(...
if __name__ == '__main__': try: logger.info(f"*******************") logger.info(f">>>>>> stage {STAGE_NAME} started <<<<<<") obj = EvaluationPipeline() obj.main() logger.info(f">>>>>> stage {STAGE_NAME} completed <<<<<<\n\nx==========x") except Exception as e: ...
{ "context_start_lineno": 0, "file": "src/cnnClassifier/pipeline/stage_04_evaluation.py", "groundtruth_start_lineno": 19, "repository": "krishnaik06-Chicken-Disease-Classification-Projects-d0f5e13", "right_context_start_lineno": 20, "task_id": "project_cc_python/1961" }
{ "list": [ { "filename": "src/cnnClassifier/components/evaluation.py", "retrieved_chunk": " model = self.load_model(self.config.path_of_model)\n self._valid_generator()\n self.score = model.evaluate(self.valid_generator)\n def save_score(self):\n scores = {\"loss\": sel...
save_score()
{ "list": [ { "filename": "src/cnnClassifier/pipeline/predict.py", "retrieved_chunk": " imagename = self.filename\n test_image = image.load_img(imagename, target_size = (224,224))\n test_image = image.img_to_array(test_image)\n test_image = np.expand_dims(test_image, axis =...
from flask import Flask, request, jsonify, render_template import os from flask_cors import CORS, cross_origin from cnnClassifier.utils.common import decodeImage from cnnClassifier.pipeline.predict import PredictionPipeline os.putenv('LANG', 'en_US.UTF-8') os.putenv('LC_ALL', 'en_US.UTF-8') app = Flask(__name__) COR...
return jsonify(result) if __name__ == "__main__": clApp = ClientApp() # app.run(host='0.0.0.0', port=8080) #local host # app.run(host='0.0.0.0', port=8080) #for AWS app.run(host='0.0.0.0', port=80) #for AZURE
{ "context_start_lineno": 0, "file": "app.py", "groundtruth_start_lineno": 39, "repository": "krishnaik06-Chicken-Disease-Classification-Projects-d0f5e13", "right_context_start_lineno": 40, "task_id": "project_cc_python/1954" }
{ "list": [ { "filename": "src/cnnClassifier/pipeline/predict.py", "retrieved_chunk": " prediction = 'Coccidiosis'\n return [{ \"image\" : prediction}]", "score": 23.27551961447391 }, { "filename": "src/cnnClassifier/pipeline/predict.py", "retrieved_chun...
predict()
{ "list": [ { "filename": "src/cnnClassifier/config/configuration.py", "retrieved_chunk": " data_ingestion_config = DataIngestionConfig(\n root_dir=config.root_dir,\n source_URL=config.source_URL,\n local_data_file=config.local_data_file,\n unzip_dir=...
import os import urllib.request as request import zipfile from cnnClassifier import logger from cnnClassifier.utils.common import get_size from cnnClassifier.entity.config_entity import DataIngestionConfig from pathlib import Path class DataIngestion: def __init__(self, config: DataIngestionConfig): self....
else: logger.info(f"File already exists of size: {get_size(Path(self.config.local_data_file))}") def extract_zip_file(self): """ zip_file_path: str Extracts the zip file into the data directory Function returns None """ unzip_path = self....
{ "context_start_lineno": 0, "file": "src/cnnClassifier/components/data_ingestion.py", "groundtruth_start_lineno": 21, "repository": "krishnaik06-Chicken-Disease-Classification-Projects-d0f5e13", "right_context_start_lineno": 22, "task_id": "project_cc_python/1955" }
{ "list": [ { "filename": "src/cnnClassifier/config/configuration.py", "retrieved_chunk": " prepare_base_model_config = PrepareBaseModelConfig(\n root_dir=Path(config.root_dir),\n base_model_path=Path(config.base_model_path),\n updated_base_model_path=Path(confi...
info(f"{filename} download! with following info: \n{headers}")
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " columns = self.columns\n examples = self.make_examples(columns)\n examples = self.annotate(examples)\n prompt = self.make_prompt(examples)\n prompt = task_instruction_editor(prompt)\n st....
from typing import Dict, List import pandas as pd import streamlit as st from st_ner_annotate import st_ner_annotate from doccano_mini.layout import BasePage from doccano_mini.prompts import make_named_entity_recognition_prompt from doccano_mini.storages.entity import EntitySessionStorage from doccano_mini.storages.s...
entities = st_ner_annotate(selected_type, text, entities, key=text) self.entity_repository.store_by_text(text, entities) return examples def make_prompt(self, examples: List[Dict]): examples = [ {**example, "entities": self.entity_repository.find_by_text(example["text"]...
{ "context_start_lineno": 0, "file": "doccano_mini/pages/05_Named_Entity_Recognition.py", "groundtruth_start_lineno": 43, "repository": "doccano-doccano-mini-0ef6c33", "right_context_start_lineno": 44, "task_id": "project_cc_python/2006" }
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " llm = openai_model_form()\n with st.expander(\"See your prompt\"):\n st.markdown(f\"```\\n{prompt.format(**inputs)}\\n```\")\n if llm is None:\n st.error(\"Enter your API key.\")\n ...
find_by_text(text)
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " columns = self.columns\n examples = self.make_examples(columns)\n examples = self.annotate(examples)\n prompt = self.make_prompt(examples)\n prompt = task_instruction_editor(prompt)\n st....
from typing import Dict, List import pandas as pd import streamlit as st from st_ner_annotate import st_ner_annotate from doccano_mini.layout import BasePage from doccano_mini.prompts import make_named_entity_recognition_prompt from doccano_mini.storages.entity import EntitySessionStorage from doccano_mini.storages.s...
text = examples[step]["text"] entities = self.entity_repository.find_by_text(text) entities = st_ner_annotate(selected_type, text, entities, key=text) self.entity_repository.store_by_text(text, entities) return examples def make_prompt(self, examples: List[Dict]): e...
{ "context_start_lineno": 0, "file": "doccano_mini/pages/05_Named_Entity_Recognition.py", "groundtruth_start_lineno": 41, "repository": "doccano-doccano-mini-0ef6c33", "right_context_start_lineno": 42, "task_id": "project_cc_python/2005" }
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " llm = openai_model_form()\n with st.expander(\"See your prompt\"):\n st.markdown(f\"```\\n{prompt.format(**inputs)}\\n```\")\n if llm is None:\n st.error(\"Enter your API key.\")\n ...
get_step()
{ "list": [ { "filename": "doccano_mini/storages/entity.py", "retrieved_chunk": " entities = self.storage.get_state(\"entities\")\n return entities.get(text, [])\n def store_by_text(self, text: str, entities: List[Entity]) -> None:\n current_entities = self.storage.get_state(\"...
from typing import Dict, List import pandas as pd import streamlit as st from st_ner_annotate import st_ner_annotate from doccano_mini.layout import BasePage from doccano_mini.prompts import make_named_entity_recognition_prompt from doccano_mini.storages.entity import EntitySessionStorage from doccano_mini.storages.s...
return examples def make_prompt(self, examples: List[Dict]): examples = [ {**example, "entities": self.entity_repository.find_by_text(example["text"])} for example in examples ] return make_named_entity_recognition_prompt(examples, types=self.types) def prepare_inp...
{ "context_start_lineno": 0, "file": "doccano_mini/pages/05_Named_Entity_Recognition.py", "groundtruth_start_lineno": 45, "repository": "doccano-doccano-mini-0ef6c33", "right_context_start_lineno": 46, "task_id": "project_cc_python/2007" }
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " llm = openai_model_form()\n with st.expander(\"See your prompt\"):\n st.markdown(f\"```\\n{prompt.format(**inputs)}\\n```\")\n if llm is None:\n st.error(\"Enter your API key.\")\n ...
store_by_text(text, entities)
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " columns = self.columns\n examples = self.make_examples(columns)\n examples = self.annotate(examples)\n prompt = self.make_prompt(examples)\n prompt = task_instruction_editor(prompt)\n st....
from typing import Dict, List import pandas as pd import streamlit as st from st_ner_annotate import st_ner_annotate from doccano_mini.layout import BasePage from doccano_mini.prompts import make_named_entity_recognition_prompt from doccano_mini.storages.entity import EntitySessionStorage from doccano_mini.storages.s...
step = self.stepper_repository.get_step() text = examples[step]["text"] entities = self.entity_repository.find_by_text(text) entities = st_ner_annotate(selected_type, text, entities, key=text) self.entity_repository.store_by_text(text, entities) return examples def ...
{ "context_start_lineno": 0, "file": "doccano_mini/pages/05_Named_Entity_Recognition.py", "groundtruth_start_lineno": 40, "repository": "doccano-doccano-mini-0ef6c33", "right_context_start_lineno": 41, "task_id": "project_cc_python/2004" }
{ "list": [ { "filename": "doccano_mini/layout.py", "retrieved_chunk": " llm = openai_model_form()\n with st.expander(\"See your prompt\"):\n st.markdown(f\"```\\n{prompt.format(**inputs)}\\n```\")\n if llm is None:\n st.error(\"Enter your API key.\")\n ...
fit(len(examples))
{ "list": [ { "filename": "doccano_mini/prompts.py", "retrieved_chunk": " input_variables=columns[:-1],\n )\n return prompt\ndef make_named_entity_recognition_prompt(examples: List[dict], **kwargs) -> FewShotPromptTemplate:\n task_instruction = (\n \"You are a highly intelligent...
from typing import Dict, List import pandas as pd import streamlit as st from st_ner_annotate import st_ner_annotate from doccano_mini.layout import BasePage from doccano_mini.prompts import make_named_entity_recognition_prompt from doccano_mini.storages.entity import EntitySessionStorage from doccano_mini.storages.s...
col2.button("Next", on_click=self.stepper_repository.increment, args=(len(examples),)) self.stepper_repository.fit(len(examples)) step = self.stepper_repository.get_step() text = examples[step]["text"] entities = self.entity_repository.find_by_text(text) entities = st_n...
{ "context_start_lineno": 0, "file": "doccano_mini/pages/05_Named_Entity_Recognition.py", "groundtruth_start_lineno": 37, "repository": "doccano-doccano-mini-0ef6c33", "right_context_start_lineno": 38, "task_id": "project_cc_python/2002" }
{ "list": [ { "filename": "doccano_mini/prompts.py", "retrieved_chunk": " task_instruction += \"The following entity types are allowed:\\n\"\n for type in types:\n task_instruction += f\"- {type}\\n\"\n for example in examples:\n entities = [\n {\"mention\": example[\...
decrement, args=(len(examples),))
{ "list": [ { "filename": "doccano_mini/models/stepper.py", "retrieved_chunk": "class Stepper:\n def __init__(self, step=0):\n self._step = step\n @property\n def step(self) -> int:\n return self._step\n def fit(self, total: int):\n if self._step >= total:\n ...
import streamlit as st from doccano_mini.models.stepper import Stepper from doccano_mini.storages.session_storage import SessionStorage class StepperSessionStorage: def __init__(self) -> None: self.storage = SessionStorage(state=st.session_state) self.storage.init_state("step", 0) def get_st...
def increment(self, total: int) -> None: step = self.storage.get_state("step") stepper = Stepper(step) stepper.increment(total) self.storage.set_state("step", stepper.step) def decrement(self, total: int) -> None: step = self.storage.get_state("step") stepper =...
{ "context_start_lineno": 0, "file": "doccano_mini/storages/stepper.py", "groundtruth_start_lineno": 18, "repository": "doccano-doccano-mini-0ef6c33", "right_context_start_lineno": 19, "task_id": "project_cc_python/2021" }
{ "list": [ { "filename": "doccano_mini/models/stepper.py", "retrieved_chunk": " if step >= total:\n raise ValueError(f\"step must be less than {total}\")\n if step < 0:\n raise ValueError(\"step must be greater than 0\")\n self._step = step\n def incremen...
set_state("step", stepper.step)
{ "list": [ { "filename": "eztw/scripts/dump_providers.py", "retrieved_chunk": "import sys\nfrom .. import get_providers, get_provider, EztwException\ndef main():\n if len(sys.argv) < 2:\n print(f\"USAGE: {sys.argv[0]} [output filename] <events>\")\n sys.exit(1)\n with_events = Fal...
""" This is a useful script that can consume any provider based on its GUID and optional keywords (defaults to MAX_KEYWORDS). Events are not parsed, but rather their event records are printed and also their hex data (using the hexdump module, if it's installed, or binascii.hexlify otherwise). """ import sys import time...
raise ValueError(f"Invalid GUID value {provider_guid!r}") if len(sys.argv) > 2: keywords = int(sys.argv[2], 16) else: keywords = MAX_KEYWORDS config = EztwProviderConfig(provider_guid, keywords) session_name = ad_hoc_session_name() LOGGER.info(f"Consuming events from {provid...
{ "context_start_lineno": 0, "file": "eztw/scripts/consume_raw_provider.py", "groundtruth_start_lineno": 29, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 30, "task_id": "project_cc_python/2085" }
{ "list": [ { "filename": "eztw/scripts/dump_providers.py", "retrieved_chunk": " sys.exit(2)\n with_events = True\n print(f\"Collecting all providers and GUIDs...\")\n all_providers = get_providers()\n to_write = []\n if not with_events:\n for guid, name in sorted(...
verify(provider_guid):
{ "list": [ { "filename": "models/mpti_learner.py", "retrieved_chunk": " # init model and optimizer\n self.model = MultiPrototypeTransductiveInference(args)\n print(self.model)\n if torch.cuda.is_available():\n self.model.cuda()\n if mode=='train':\n ...
""" Finetune Baseline for Few-shot 3D Point Cloud Semantic Segmentation """ import torch import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from runs.eval import evaluate_metric from runs.pre_train im...
# load pretrained model for point cloud encoding self.model = load_pretrain_checkpoint(self.model, args.pretrain_checkpoint_path) def train(self, support_x, support_y): """ Args: support_x: support point clouds with shape (n_way*k_shot, in_channels, num_points) ...
{ "context_start_lineno": 0, "file": "runs/fine_tune.py", "groundtruth_start_lineno": 34, "repository": "heshuting555-PAP-FZS3D-e3fc6cb", "right_context_start_lineno": 35, "task_id": "project_cc_python/1967" }
{ "list": [ { "filename": "models/mpti_learner.py", "retrieved_chunk": " {'params': self.model.att_learner.parameters()}], lr=args.lr)\n else:\n self.optimizer = torch.optim.Adam(\n [{'params': self.model.encoder.parameters(), 'lr': 0.00...
segmenter.parameters(), lr=args.lr)
{ "list": [ { "filename": "runs/mpti_train.py", "retrieved_chunk": " for batch_idx, (data, sampled_classes) in enumerate(TRAIN_LOADER):\n if torch.cuda.is_available():\n data = cast_cuda(data)\n loss, accuracy = MPTI.train(data)\n if (batch_idx+1) % 100 == 0:\n ...
""" Finetune Baseline for Few-shot 3D Point Cloud Semantic Segmentation """ import torch import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from runs.eval import evaluate_metric from runs.pre_train im...
global_iter += 1 # test on query set query_pred, test_loss, accuracy = FT.test(query_x, query_y) WRITER.add_scalar('Test/loss', test_loss, global_iter) WRITER.add_scalar('Test/accuracy', accuracy, global_iter) logger.cprint( '=====[Valid] Batch_idx: %d ...
{ "context_start_lineno": 0, "file": "runs/fine_tune.py", "groundtruth_start_lineno": 134, "repository": "heshuting555-PAP-FZS3D-e3fc6cb", "right_context_start_lineno": 135, "task_id": "project_cc_python/1972" }
{ "list": [ { "filename": "models/proto_learner.py", "retrieved_chunk": " self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n self.lr_scheduler.step()\n query_pred = F.softmax(query_logits, dim=1).argmax(dim=1)\n correct = torch.eq(query_pre...
cprint('=====[Train] Batch_idx: %d | Iter: %d | Loss: %.4f =====' % (batch_idx, i, train_loss.item()))
{ "list": [ { "filename": "runs/proto_train.py", "retrieved_chunk": " num_point=args.pc_npts, pc_attribs=args.pc_attribs,\n pc_augm=args.pc_augm, pc_augm_config=PC_AUGMENT_CONFIG)\n VALID_DATASET = MyTestDataset(args.data_path, args.dataset,...
"""Evaluating functions for Few-shot 3D Point Cloud Semantic Segmentation """ import os import numpy as np from datetime import datetime import torch from torch.utils.data import DataLoader from dataloaders.loader import MyTestDataset, batch_test_task_collate from models.proto_learner import ProtoLearner from model...
{ "context_start_lineno": 0, "file": "runs/eval.py", "groundtruth_start_lineno": 127, "repository": "heshuting555-PAP-FZS3D-e3fc6cb", "right_context_start_lineno": 128, "task_id": "project_cc_python/1974" }
{ "list": [ { "filename": "runs/proto_train.py", "retrieved_chunk": " # train\n best_iou = 0\n import time\n for batch_idx, (data, sampled_classes) in enumerate(TRAIN_LOADER):\n if torch.cuda.is_available():\n data = cast_cuda(data)\n loss, accuracy = PL.train(data...
cprint('\n=====[TEST] Loss: %.4f | Mean IoU: %f =====\n' % (test_loss, mean_IoU))
{ "list": [ { "filename": "trainutils/train_branched.py", "retrieved_chunk": " pred_fine = torch.argmax(soft_fine, dim=1)\n loss_ce1 = ce_loss(out_coarse, q_lc)\n loss_dice1 = dice_loss_coarse(soft_coarse, q_lc)\n loss_coarse = 0.5 * (loss_ce1 + loss_dice1)\...
import os import math import random import shutil import logging import numpy as np from tqdm.auto import tqdm import torch from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from torch.nn.modules.loss import CrossEntropyLoss from test import test_all_case from val import test_single_case ...
threshold = (0.75 + 0.25 * sigmoid_rampup(iter_num, max_iterations)) * np.log(2) mask_f = (uncertainty_f < threshold).float() consistency_loss = torch.sum(mask_f * consistency_dist_f) / (2 * torch.sum(mask_f) + 1e-16) loss['consistency loss'] = consistency_weight * cons...
{ "context_start_lineno": 0, "file": "trainutils/train_uncertainty_aware_mean_teacher.py", "groundtruth_start_lineno": 148, "repository": "OvO1111-EfficientSubclassLearning-afdd90e", "right_context_start_lineno": 149, "task_id": "project_cc_python/2041" }
{ "list": [ { "filename": "trainutils/train_branched.py", "retrieved_chunk": " loss['negative learning loss'] = nce_loss(out[param.exp.labeled_batch_size:], q_lc[param.exp.labeled_batch_size:])\n if param.exp.mixup_label:\n mixed_im, mixed_lf, alpha = sampled_b...
softmax_mse_loss(out_fine[args.labeled_bs:], ema_out_fine)
{ "list": [ { "filename": "eztw/scripts/dump_providers.py", "retrieved_chunk": "import sys\nfrom .. import get_providers, get_provider, EztwException\ndef main():\n if len(sys.argv) < 2:\n print(f\"USAGE: {sys.argv[0]} [output filename] <events>\")\n sys.exit(1)\n with_events = Fal...
""" This is a useful script that can consume any locally registered provider directly from command-line. It automatically parses any registered events and allows easy exploration of trace providers. If only specific events are desired, provide them as the last parameter as a comma-separated list of IDs. Otherwise (def...
for i, (event_record, parsed_event) in enumerate(consume_events(events, keywords=keywords)): print(f"=== [Event {i}] {time.ctime(event_record.timestamp)} ===") print(event_record) print(parsed_event) if __name__ == "__main__": main()
{ "context_start_lineno": 0, "file": "eztw/scripts/consume_provider.py", "groundtruth_start_lineno": 30, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 31, "task_id": "project_cc_python/2090" }
{ "list": [ { "filename": "eztw/scripts/consume_raw_provider.py", "retrieved_chunk": " keywords = MAX_KEYWORDS\n config = EztwProviderConfig(provider_guid, keywords)\n session_name = ad_hoc_session_name()\n LOGGER.info(f\"Consuming events from {provider_guid} with keywords {hex(keyword...
info(f"Consuming {len(events)} events from {provider.guid} - press Ctrl+C to stop")
{ "list": [ { "filename": "eztw/controller.py", "retrieved_chunk": " LOGGER.info(f\"Stopping trace session {self.session_name!r}\")\n trace_properties = TraceProperties()\n rc = ControlTrace(self.session_handle, None, trace_properties.properties, EVENT_TRACE_CONTROL_STOP)\n ...
""" Implementation of EztwConsumer, which allows consuming real time event records from an existing real-time trace session. """ import ctypes import queue import time import threading import contextlib import win32api import winerror from .log import LOGGER from .guid import GUID from .common import UCHAR, USHORT, UL...
rc = self.CloseTrace(self.session_handle) if rc not in [winerror.ERROR_SUCCESS, winerror.ERROR_CTX_CLOSE_PENDING]: raise EztwConsumerException( f"CloseTrace failed for session {self.session_name!r} with error {rc}") self.session_handle = None def _buffer_callbac...
{ "context_start_lineno": 0, "file": "eztw/consumer.py", "groundtruth_start_lineno": 279, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 280, "task_id": "project_cc_python/2080" }
{ "list": [ { "filename": "eztw/controller.py", "retrieved_chunk": " def enable_provider(self, provider_guid: str, keywords: int, level: int):\n # TODO: support filters, stack trace and other advanced features\n # etp = ENABLE_TRACE_PARAMETERS()\n # etp.Version = ENABLE_TRACE_P...
info(f"Closing trace consumer for session {self.session_name!r}")
{ "list": [ { "filename": "eztw/tests/test_eztw.py", "retrieved_chunk": " (\"field_uint8\", EVENT_FIELD_INTYPE.INTYPE_UINT8, 1),\n (\"field_int16\", EVENT_FIELD_INTYPE.INTYPE_INT16, -1000),\n (\"field_uint16\", EVENT_FIELD_INTYPE.INTYPE_UINT16, 1000),\n (\"f...
""" Implementation of EztwEvent which represents a single event template. Each event may have multiple versions, each with different fields. This class also allows parsing the context-specific contents of an event record. """ import struct import ctypes import functools from collections import OrderedDict from dataclas...
consume_func = self.consume_UINT32 case EVENT_FIELD_INTYPE.INTYPE_INT64: consume_func = self.consume_INT64 case EVENT_FIELD_INTYPE.INTYPE_UINT64 | EVENT_FIELD_INTYPE.INTYPE_HEXINT64: consume_func = self.consume_UINT64 case EVENT_FIELD_...
{ "context_start_lineno": 0, "file": "eztw/event.py", "groundtruth_start_lineno": 152, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 153, "task_id": "project_cc_python/2061" }
{ "list": [ { "filename": "eztw/tests/test_eztw.py", "retrieved_chunk": " (\"field_guid\", EVENT_FIELD_INTYPE.INTYPE_GUID, provider_guid),\n (\"field_pointer\", EVENT_FIELD_INTYPE.INTYPE_POINTER, 123456789),\n (\"field_filetime\", EVENT_FIELD_INTYPE.INTYPE_FILETIME, 12...
INTYPE_UINT32 | EVENT_FIELD_INTYPE.INTYPE_HEXINT32:
{ "list": [ { "filename": "eztw/provider.py", "retrieved_chunk": " provider_guid = self.provider_guid_by_name.get(canonize_provider_name(provider_name))\n if not provider_guid:\n raise EztwProviderException(f\"Could not find locally registered provider named {provider_name!r}\...
""" Implementation of EztwEvent which represents a single event template. Each event may have multiple versions, each with different fields. This class also allows parsing the context-specific contents of an event record. """ import struct import ctypes import functools from collections import OrderedDict from dataclas...
def consume_STRING(self, size=None): if size is None: str_value = ctypes.string_at(self.data[self.cur_offset:]) # Advance internal offset by string size plus null termination byte self.cur_offset += len(str_value) + 1 else: # Manually append null ter...
{ "context_start_lineno": 0, "file": "eztw/event.py", "groundtruth_start_lineno": 77, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 78, "task_id": "project_cc_python/2054" }
{ "list": [ { "filename": "eztw/provider.py", "retrieved_chunk": " return self.get_provider_by_guid(event_record.provider_guid).parse(event_record)\n def __repr__(self):\n return f\"{self.__class__.__name__}({len(self.provider_name_by_guid)} registered providers)\"\n##################...
from_buffer_copy(self.consume(16)))
{ "list": [ { "filename": "eztw/session.py", "retrieved_chunk": " for provider_guid, event_count in event_counter.items():\n provider_name = eztwm.get_provider_name_from_guid(provider_guid)\n print(f\"\\tProvider {provider_guid} ({provider_name}):\")\n ...
""" Implementation of EztwProvider which represents a single provider (and its events). Implementation of EztwManager - a utility class for efficiently managing and accessing providers by name and GUID. In addition, multiple API functions are exposed: get_provider - return EztwProvider by GUID or name get_prov...
return self.get_provider_by_guid(guid_or_name) else: return self.get_provider_by_name(guid_or_name) def parse(self, event_record: EventRecord): return self.get_provider_by_guid(event_record.provider_guid).parse(event_record) def __repr__(self): return f"{self._...
{ "context_start_lineno": 0, "file": "eztw/provider.py", "groundtruth_start_lineno": 179, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 180, "task_id": "project_cc_python/2053" }
{ "list": [ { "filename": "eztw/event.py", "retrieved_chunk": " f\"{event_record.id} of provider {event_record.provider_guid}\")\n # Get the list of fields and the pre-created \"template\"\n event_fields, event_template = self.versions[event_recor...
verify(guid_or_name):
{ "list": [ { "filename": "chainbench/test_data/base.py", "retrieved_chunk": " @property\n def data(self) -> BlockchainData:\n if self._data is None:\n raise ValueError(\"Data is not initialized\")\n return self._data\n @staticmethod\n def _parse_hex_to_int(value: ...
from typing import Mapping from chainbench.test_data.base import BaseTestData, BlockchainData, Blocks, ChainInfo from chainbench.util.rng import get_rng class EVMTestData(BaseTestData): TXS_REQUIRED = 100 ACCOUNTS_REQUIRED = 200 SAVE_BLOCKS = 20 CHAIN_INFO: Mapping[int, ChainInfo] = { 1: { ...
def _fetch_block(self, block_number: int | str, return_txs: bool = True) -> tuple[int, dict]: if isinstance(block_number, int): block_number = hex(block_number) elif (block_number := block_number.lower()) not in ( "latest", "earliest", "pending", ...
{ "context_start_lineno": 0, "file": "chainbench/test_data/evm.py", "groundtruth_start_lineno": 40, "repository": "chainstacklabs-chainbench-177c49e", "right_context_start_lineno": 41, "task_id": "project_cc_python/1987" }
{ "list": [ { "filename": "chainbench/test_data/base.py", "retrieved_chunk": " self._logger.debug(\"Locked\")\n self._data: BlockchainData | None = None\n def update(self, host_url: str, parsed_options: Namespace) -> BlockchainData:\n self._logger.info(\"Updating data\")\n ...
_make_call("eth_chainId"))
{ "list": [ { "filename": "chainbench/test_data/base.py", "retrieved_chunk": " @property\n def data(self) -> BlockchainData:\n if self._data is None:\n raise ValueError(\"Data is not initialized\")\n return self._data\n @staticmethod\n def _parse_hex_to_int(value: ...
from typing import Mapping from chainbench.test_data.base import BaseTestData, BlockchainData, Blocks, ChainInfo from chainbench.util.rng import get_rng class EVMTestData(BaseTestData): TXS_REQUIRED = 100 ACCOUNTS_REQUIRED = 200 SAVE_BLOCKS = 20 CHAIN_INFO: Mapping[int, ChainInfo] = { 1: { ...
def _fetch_block(self, block_number: int | str, return_txs: bool = True) -> tuple[int, dict]: if isinstance(block_number, int): block_number = hex(block_number) elif (block_number := block_number.lower()) not in ( "latest", "earliest", "pending", ...
{ "context_start_lineno": 0, "file": "chainbench/test_data/evm.py", "groundtruth_start_lineno": 40, "repository": "chainstacklabs-chainbench-177c49e", "right_context_start_lineno": 41, "task_id": "project_cc_python/1986" }
{ "list": [ { "filename": "chainbench/test_data/base.py", "retrieved_chunk": " self._logger.debug(\"Locked\")\n self._data: BlockchainData | None = None\n def update(self, host_url: str, parsed_options: Namespace) -> BlockchainData:\n self._logger.info(\"Updating data\")\n ...
_parse_hex_to_int(self._make_call("eth_chainId"))
{ "list": [ { "filename": "eztw/scripts/consume_provider.py", "retrieved_chunk": "from .. import get_provider, consume_events, MAX_KEYWORDS\nfrom ..log import LOGGER\ndef main():\n if len(sys.argv) < 2:\n print(f\"USAGE: {sys.argv[0]} [provider name or GUID] <event ids, comma-separated>\")\n...
""" This useful script allows to "tap" into any pre-existing real-time trace session and start consuming and parsing its events. For example: python -m eztw.scripts.tap_session EventLog-System """ import sys import time from ..log import LOGGER from .. import EztwSessionIterator def main(): if len(sys.argv) < 2:...
for i, (event_record, parsed_event) in enumerate(EztwSessionIterator(sys.argv[1])): print(f"=== [Event {i}] {time.ctime(event_record.timestamp)} ==") print(event_record) print(parsed_event) if __name__ == "__main__": main()
{ "context_start_lineno": 0, "file": "eztw/scripts/tap_session.py", "groundtruth_start_lineno": 17, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 18, "task_id": "project_cc_python/2091" }
{ "list": [ { "filename": "eztw/scripts/consume_provider.py", "retrieved_chunk": " events = provider.get_events_by_ids(event_ids)\n else:\n # Consume all provider's events\n events = provider.events\n keywords = {provider.guid: MAX_KEYWORDS}\n LOGGER.info(f\"Consuming...
info(f"Tapping into session {sys.argv[1]!r} - press Ctrl+C to stop")
{ "list": [ { "filename": "eztw/scripts/consume_raw_provider.py", "retrieved_chunk": "def main():\n if len(sys.argv) < 2:\n print(f\"USAGE: {sys.argv[0]} [provider GUID] <hex keywords, default is 0xffffffffffffffff>\")\n sys.exit(1)\n provider_guid = sys.argv[1]\n if not GUID.ve...
""" This is a useful script that can consume any locally registered provider directly from command-line. It automatically parses any registered events and allows easy exploration of trace providers. If only specific events are desired, provide them as the last parameter as a comma-separated list of IDs. Otherwise (def...
LOGGER.info(f"Consuming {len(events)} events from {provider.guid} - press Ctrl+C to stop") for i, (event_record, parsed_event) in enumerate(consume_events(events, keywords=keywords)): print(f"=== [Event {i}] {time.ctime(event_record.timestamp)} ===") print(event_record) print(parsed_eve...
{ "context_start_lineno": 0, "file": "eztw/scripts/consume_provider.py", "groundtruth_start_lineno": 29, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 30, "task_id": "project_cc_python/2089" }
{ "list": [ { "filename": "eztw/scripts/consume_raw_provider.py", "retrieved_chunk": " keywords = MAX_KEYWORDS\n config = EztwProviderConfig(provider_guid, keywords)\n session_name = ad_hoc_session_name()\n LOGGER.info(f\"Consuming events from {provider_guid} with keywords {hex(keyword...
guid: MAX_KEYWORDS}
{ "list": [ { "filename": "eztw/scripts/consume_provider.py", "retrieved_chunk": "from .. import get_provider, consume_events, MAX_KEYWORDS\nfrom ..log import LOGGER\ndef main():\n if len(sys.argv) < 2:\n print(f\"USAGE: {sys.argv[0]} [provider name or GUID] <event ids, comma-separated>\")\n...
""" This is a useful script that can consume any provider based on its GUID and optional keywords (defaults to MAX_KEYWORDS). Events are not parsed, but rather their event records are printed and also their hex data (using the hexdump module, if it's installed, or binascii.hexlify otherwise). """ import sys import time...
with EztwController(session_name, config): for i, event_record in enumerate(EztwConsumer(session_name)): print(f"=== [Event {i}] {time.ctime(event_record.timestamp)} ===") if event_record.provider_guid == MSNT_SystemTrace_GUID: print("<SYSTEM TRACE EVENT>") ...
{ "context_start_lineno": 0, "file": "eztw/scripts/consume_raw_provider.py", "groundtruth_start_lineno": 37, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 38, "task_id": "project_cc_python/2086" }
{ "list": [ { "filename": "eztw/scripts/consume_provider.py", "retrieved_chunk": " events = provider.get_events_by_ids(event_ids)\n else:\n # Consume all provider's events\n events = provider.events\n keywords = {provider.guid: MAX_KEYWORDS}\n LOGGER.info(f\"Consuming...
info(f"Consuming events from {provider_guid} with keywords {hex(keywords)} - press Ctrl+C to stop")
{ "list": [ { "filename": "eztw/scripts/consume_raw_provider.py", "retrieved_chunk": "def main():\n if len(sys.argv) < 2:\n print(f\"USAGE: {sys.argv[0]} [provider GUID] <hex keywords, default is 0xffffffffffffffff>\")\n sys.exit(1)\n provider_guid = sys.argv[1]\n if not GUID.ve...
""" This is a useful script that can consume any locally registered provider directly from command-line. It automatically parses any registered events and allows easy exploration of trace providers. If only specific events are desired, provide them as the last parameter as a comma-separated list of IDs. Otherwise (def...
else: # Consume all provider's events events = provider.events keywords = {provider.guid: MAX_KEYWORDS} LOGGER.info(f"Consuming {len(events)} events from {provider.guid} - press Ctrl+C to stop") for i, (event_record, parsed_event) in enumerate(consume_events(events, keywords=keyword...
{ "context_start_lineno": 0, "file": "eztw/scripts/consume_provider.py", "groundtruth_start_lineno": 25, "repository": "Cybereason-eztw-94a0ae9", "right_context_start_lineno": 26, "task_id": "project_cc_python/2087" }
{ "list": [ { "filename": "eztw/scripts/dump_providers.py", "retrieved_chunk": " sys.exit(2)\n with_events = True\n print(f\"Collecting all providers and GUIDs...\")\n all_providers = get_providers()\n to_write = []\n if not with_events:\n for guid, name in sorted(...
get_events_by_ids(event_ids)
{ "list": [ { "filename": "spoolman/database/spool.py", "retrieved_chunk": " first_used: Optional[datetime] = None,\n last_used: Optional[datetime] = None,\n location: Optional[str] = None,\n lot_nr: Optional[str] = None,\n comment: Optional[str] = None,\n archived: bool = False,\n) ...
"""Helper functions for interacting with filament database objects.""" from typing import Optional from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import contains_eager, joinedload from spoolman.database import models, vendor...
if vendor_id is not None: vendor_item = await vendor.get_by_id(db, vendor_id) db_item = models.Filament( name=name, vendor=vendor_item, material=material, price=price, density=density, diameter=diameter, weight=weight, spool_weight=spool_...
{ "context_start_lineno": 0, "file": "spoolman/database/filament.py", "groundtruth_start_lineno": 31, "repository": "Donkie-Spoolman-2fcfc38", "right_context_start_lineno": 32, "task_id": "project_cc_python/1949" }
{ "list": [ { "filename": "spoolman/database/spool.py", "retrieved_chunk": " if remaining_weight is not None:\n if filament_item.weight is None:\n raise ItemCreateError(\"remaining_weight can only be used if the filament type has a weight set.\")\n used_weig...
Vendor] = None # noqa: FA100
{ "list": [ { "filename": "spoolman/env.py", "retrieved_chunk": " if self is DatabaseType.POSTGRES:\n return \"postgresql+asyncpg\"\n if self is DatabaseType.MYSQL:\n return \"mysql+aiomysql\"\n if self is DatabaseType.SQLITE:\n return \"sqlite+aio...
"""SQLAlchemy database setup.""" import datetime import logging import shutil import sqlite3 from collections.abc import AsyncGenerator from os import PathLike from pathlib import Path from typing import Optional, Union from scheduler.asyncio.scheduler import Scheduler from sqlalchemy import URL from sqlalchemy.ext.a...
logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) connect_args = {} if self.connection_url.drivername == "sqlite+aiosqlite": connect_args["timeout"] = 60 self.engine = create_async_engine( self.connection_url, connect_args=connect_ar...
{ "context_start_lineno": 0, "file": "spoolman/database/database.py", "groundtruth_start_lineno": 74, "repository": "Donkie-Spoolman-2fcfc38", "right_context_start_lineno": 75, "task_id": "project_cc_python/1945" }
{ "list": [ { "filename": "spoolman/env.py", "retrieved_chunk": " \"\"\"Get the database type from environment variables.\n Returns None if no environment variable was set for the database type.\n Returns:\n Optional[DatabaseType]: The database type.\n \"\"\"\n database_type = os...
get_logging_level() == logging.DEBUG:
{ "list": [ { "filename": "spoolman/api/v1/router.py", "retrieved_chunk": " debug_mode=env.is_debug_mode(),\n automatic_backups=env.is_automatic_backup_enabled(),\n data_dir=str(env.get_data_dir().resolve()),\n backups_dir=str(env.get_backups_dir().resolve()),\n db_t...
"""SQLAlchemy database setup.""" import datetime import logging import shutil import sqlite3 from collections.abc import AsyncGenerator from os import PathLike from pathlib import Path from typing import Optional, Union from scheduler.asyncio.scheduler import Scheduler from sqlalchemy import URL from sqlalchemy.ext.a...
logger.info('No database type specified, using a default SQLite database located at "%s"', database) elif db_type is env.DatabaseType.SQLITE: if database is not None: raise ValueError("Cannot specify a database name when using SQLite.") database = str(env.get_data_dir().joinpat...
{ "context_start_lineno": 0, "file": "spoolman/database/database.py", "groundtruth_start_lineno": 33, "repository": "Donkie-Spoolman-2fcfc38", "right_context_start_lineno": 34, "task_id": "project_cc_python/1944" }
{ "list": [ { "filename": "spoolman/api/v1/router.py", "retrieved_chunk": " return models.HealthCheck(status=\"healthy\")\n# Add endpoint for triggering a db backup\n@app.post(\n \"/backup\",\n description=\"Trigger a database backup. Only applicable for SQLite databases.\",\n response_mod...
get_data_dir().joinpath("spoolman.db"))
{ "list": [ { "filename": "pubgpt/llm_parser/openai.py", "retrieved_chunk": "- The entire part after the sentence \"is associated with\"\nFor instance:\n'Yes,X,Y'\nAlso, remove the numbers list (like 1)) from the CSV\n \"\"\".strip()\n openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n response...
from typing import List, Tuple from dotenv import load_dotenv import cohere import os load_dotenv() def get_associations( document: str, pubmed_id: str, pairs: List[Tuple[str, str]] ) -> str: """ Get associations using Cohere LLM. Args: document (str): Text (abstract or full text) p...
response = ( co.generate( model="command-xlarge-nightly", prompt=prompt, max_tokens=max_tokens, temperature=temperature, ) .generations[0] .text ) with open(f"output/{pubmed_id}/cohere_results.csv", "w") as f: f.write("...
{ "context_start_lineno": 0, "file": "pubgpt/llm_parser/cohere.py", "groundtruth_start_lineno": 44, "repository": "dSupertramp-PubGPT-253ec52", "right_context_start_lineno": 45, "task_id": "project_cc_python/2049" }
{ "list": [ { "filename": "pubgpt/llm_parser/starcoder.py", "retrieved_chunk": "- The entire part after the sentence \"is associated with\"\nFor instance:\n'Yes,X,Y'\nAlso, remove the numbers list (like 1)) from the CSV\n \"\"\".strip()\n headers: dict = {\"Authorization\": f\"Bearer {os.getenv(...
Client(os.getenv("COHERE_API_KEY"))
{ "list": [ { "filename": "spoolman/main.py", "retrieved_chunk": "from fastapi.middleware.gzip import GZipMiddleware\nfrom fastapi.staticfiles import StaticFiles\nfrom scheduler.asyncio.scheduler import Scheduler\nfrom spoolman import env\nfrom spoolman.api.v1.router import app as v1_app\nfrom spoolma...
"""SQLAlchemy database setup.""" import datetime import logging import shutil import sqlite3 from collections.abc import AsyncGenerator from os import PathLike from pathlib import Path from typing import Optional, Union from scheduler.asyncio.scheduler import Scheduler from sqlalchemy import URL from sqlalchemy.ext.a...
return if "sqlite" in __db.connection_url.drivername: logger.info("Scheduling automatic database backup for midnight.") # Schedule for midnight scheduler.daily(datetime.time(hour=0, minute=0, second=0), _backup_task) # type: ignore[arg-type] async def get_db_session() -> AsyncGen...
{ "context_start_lineno": 0, "file": "spoolman/database/database.py", "groundtruth_start_lineno": 193, "repository": "Donkie-Spoolman-2fcfc38", "right_context_start_lineno": 194, "task_id": "project_cc_python/1946" }
{ "list": [ { "filename": "spoolman/main.py", "retrieved_chunk": "# Define a console logger\nconsole_handler = logging.StreamHandler()\nconsole_handler.setFormatter(logging.Formatter(\"%(name)-26s %(levelname)-8s %(message)s\"))\n# Setup the spoolman logger, which all spoolman modules will use\nroot_l...
is_automatic_backup_enabled():
{ "list": [ { "filename": "ner_train.py", "retrieved_chunk": " optimizer.zero_grad()\n else:\n model.eval()\n for batch in tqdm.tqdm(dataloader):\n ids = batch['input_ids'].to(device, dtype = torch.long)\n mask = batch['attention_mask'].to(device, dtype = torch.long)\...
import torch import os from models.BertSequence import load_bert_sequence_model from transformers import BertTokenizerFast from dataloaders.ner_conll2003 import get_labels def inference_ner(sentence, path_checkpoint, num_labels, device='cuda'): model = load_bert_sequence_model(path_checkpoint, num_labels, device) ...
logits = outputs[0] active_logits = logits.view(-1, model.module.num_labels) # shape (batch_size * seq_len, num_labels) flattened_predictions = torch.argmax(active_logits, axis=1) # shape (batch_size*seq_len,) - predictions at the token level tokens = tokenizer.convert_ids_to_tokens(ids.squeeze(...
{ "context_start_lineno": 0, "file": "ner_inference.py", "groundtruth_start_lineno": 22, "repository": "Fsoft-AIC-Class-Based-Influence-Functions-b957b78", "right_context_start_lineno": 23, "task_id": "project_cc_python/1994" }
{ "list": [ { "filename": "dataloaders/ner_conll2003.py", "retrieved_chunk": " # code based on https://huggingface.co/transformers/custom_datasets.html#tok-ner\n # create an empty array of -100 of length max_length\n # Word pieces that should be ignored have a label of -100 (which...
module.predict(input_ids=ids, attention_mask=mask)
{ "list": [ { "filename": "tuned_lens/scripts/eval_loop.py", "retrieved_chunk": " lambda x: nats_to_bpb * x.mean(0), pytree_stack(transfer_batches)\n )\n agg_transfer = pytree_map(lambda x: maybe_all_reduce(x), agg_transfer)\n if self.dist.primary:\n ...
import random import torch as th from torch.distributions import Dirichlet, kl_divergence from tuned_lens.stats import LogitStats def test_logit_stats_correctness(): """Test that `LogitStats` recovers the true Dirichlet within a small error.""" th.manual_seed(42) x = Dirichlet(th.tensor([1.0, 1.0, 1.0]...
assert kl_divergence(x, x2) < 1e-3
{ "context_start_lineno": 0, "file": "tests/test_stats.py", "groundtruth_start_lineno": 19, "repository": "FabienRoger-concistency-lenses-6500b44", "right_context_start_lineno": 20, "task_id": "project_cc_python/1980" }
{ "list": [ { "filename": "tuned_lens/scripts/eval_loop.py", "retrieved_chunk": " lambda x: nats_to_bpb * x.mean(0), pytree_stack(transfer_batches)\n )\n agg_transfer = pytree_map(lambda x: maybe_all_reduce(x), agg_transfer)\n if self.dist.primary:\n ...
mle()
{ "list": [ { "filename": "up4ros/src/up4ros/converter.py", "retrieved_chunk": "class Converter:\n def __init__(self):\n self.functions = {}\n for k in dir(self):\n v = getattr(self, k)\n if hasattr(v, \"_what\"):\n for x in v._what:\n ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
self.assertEqual(x_pb.name, "x") self.assertEqual(x_pb.value_type, "up:bool") x_up = self.pb_reader.convert(x_pb, problem) self.assertEqual(x_up.name, "x") self.assertEqual(x_up.type, shortcuts.BoolType()) def test_fluent_2(self): problem = self.problems["robot"]...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_conversion.py", "groundtruth_start_lineno": 54, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 55, "task_id": "project_cc_python/2138" }
{ "list": [ { "filename": "up4ros/src/up4ros/converter.py", "retrieved_chunk": " return f(element, *args)", "score": 28.889066560681357 }, { "filename": "up4ros/src/up4ros/ros_interface_writer.py", "retrieved_chunk": " ret = msgs.Fluent()\n ret.name = nam...
convert(x, problem)
{ "list": [ { "filename": "tests/test_model_surgery.py", "retrieved_chunk": "import pytest\nimport torch as th\nfrom transformers import PreTrainedModel, models\nfrom tuned_lens import model_surgery\ndef test_get_final_layer_norm_raises(opt_random_model: PreTrainedModel):\n opt_random_model.base_mo...
"""Provides a class for mapping transformer hidden states to logits (and vice versa).""" import copy from dataclasses import dataclass from typing import Literal, Optional, cast import torch as th from torch.distributions import Distribution from transformers import PreTrainedModel from tuned_lens import model_surger...
unembeding_matrix = model.get_output_embeddings() if not isinstance(unembeding_matrix, th.nn.Linear): # With nn.Linear we know that the unembedding matrix is .weight; # we don't want to guess incorrectly for other module classes. raise ValueError("Currently we only ...
{ "context_start_lineno": 0, "file": "tuned_lens/nn/unembed.py", "groundtruth_start_lineno": 40, "repository": "FabienRoger-concistency-lenses-6500b44", "right_context_start_lineno": 41, "task_id": "project_cc_python/1977" }
{ "list": [ { "filename": "tuned_lens/nn/lenses.py", "retrieved_chunk": " def forward(self, x: th.Tensor) -> th.Tensor:\n \"\"\"Apply the affine transformation to the input.\n Args:\n x: The input to transform.\n \"\"\"\n return x + self.bias\nclass TunedLens(...
get_final_norm(model)
{ "list": [ { "filename": "tuned_lens/scripts/train_loop.py", "retrieved_chunk": " if shift is None:\n shift = 0\n else:\n raise NotImplementedError(f\"Unknown loss {self.loss}\")\n labels = shift_labels(labels, shift)\n ...
"""Provides tools for extracting causal bases from models and ablating subspaces.""" from contextlib import contextmanager from typing import Iterable, Literal, NamedTuple, Optional, Sequence import torch as th import torch.distributed as dist import torch.nn.functional as F from tqdm.auto import trange from ..model_...
else: raise ValueError(f"Unknown mode {mode}") return u + th.einsum("ij,...j->...i", proj, dummy)
{ "context_start_lineno": 0, "file": "tuned_lens/causal/subspaces.py", "groundtruth_start_lineno": 263, "repository": "FabienRoger-concistency-lenses-6500b44", "right_context_start_lineno": 264, "task_id": "project_cc_python/1978" }
{ "list": [ { "filename": "tuned_lens/causal/ablation.py", "retrieved_chunk": " yield model\n finally:\n handle.remove()", "score": 46.71062880402537 }, { "filename": "tuned_lens/causal/ablation.py", "retrieved_chunk": " if method == \"resample\":\n ...
view_as(u) - u
{ "list": [ { "filename": "up4ros/tests/test_set_and_get_problem_service.py", "retrieved_chunk": " node_test = UP4ROSNode(init_ros_interfaces=False)\n pb_writer = ROSInterfaceWriter()\n problems = get_example_problems()\n problem = problems[\"robot\"].problem\n req = srvs.SetProblemRequ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
assert response.success assert response.message == "" Location = shortcuts.UserType("Location") robot_at = model.Fluent("robot_at_bis", shortcuts.BoolType(), l=Location) add_fluent_req = srvs.AddFluentRequest() add_fluent_req.problem_name = "problem_test_robot" add_fluent_req.fluent = pb_...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_set_and_add_fluent_service.py", "groundtruth_start_lineno": 38, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 39, "task_id": "project_cc_python/2142" }
{ "list": [ { "filename": "up4ros/tests/test_add_object_service.py", "retrieved_chunk": " assert response.success\n assert response.message == \"\"\n Location = shortcuts.UserType(\"Location\")\n upf_object = model.Object(\"l3\", Location)\n add_object_req = srvs.AddObjectRequest()\n ...
set_problem(srv)
{ "list": [ { "filename": "tests/test_core.py", "retrieved_chunk": " snippets = extract_snippets(traces, times=times, channel_locations=None, mask_radius=None, channel_indices=None, T1=T1, T2=T2)\n assert snippets.shape == (L, T, M)\ndef test_extract_snippets_in_channel_neighborhood():\n N = ...
import numpy as np import numpy.typing as npt import math import spikeinterface as si from .Scheme1SortingParameters import Scheme1SortingParameters from ..core.detect_spikes import detect_spikes from ..core.extract_snippets import extract_snippets from ..core.isosplit6_subdivision_method import isosplit6_subdivision_m...
labels = isosplit6_subdivision_method( X=features, npca_per_subdivision=sorting_parameters.npca_per_subdivision ) K = int(np.max(labels)) print(f'Found {K} clusters') print('Computing templates') templates = compute_templates(snippets=snippets, labels=labels) # K x T x M pe...
{ "context_start_lineno": 0, "file": "mountainsort5/schemes/sorting_scheme1.py", "groundtruth_start_lineno": 86, "repository": "flatironinstitute-mountainsort5-3e85076", "right_context_start_lineno": 87, "task_id": "project_cc_python/2000" }
{ "list": [ { "filename": "tests/test_core.py", "retrieved_chunk": " times = np.random.randint(T1, N - T2, size=(L,))\n neighborhood = [0, 2]\n snippets = extract_snippets_in_channel_neighborhood(\n traces=traces,\n times=times,\n neighborhood=neighborhood,\n T1=T1...
reshape((L, T * M)), npca=sorting_parameters.npca_per_channel * M)
{ "list": [ { "filename": "test/test_lever_scraper.py", "retrieved_chunk": "options.add_argument('--headless')\ndriver = webdriver.Chrome(options=options)\nfor company in company_list:\n data = company.scraper_type().getJobs(driver, company.jobs_url, company.company_name)\n for entry in data:\n ...
from selenium import webdriver from src.company_item import CompanyItem from src.scrape_recruitee import ScrapeRecruitee companies = [ CompanyItem("ramp.network", "https://metrika.recruitee.com", ScrapeRecruitee, "https://ramp.network", "Payments"), CompanyItem("tether", "https://tether.recruitee.com", Scrape...
for entry in data: print(entry) driver.close()
{ "context_start_lineno": 0, "file": "test/test_recruitee_scraper.py", "groundtruth_start_lineno": 16, "repository": "crypto-jobs-fyi-crawler-b0596e6", "right_context_start_lineno": 17, "task_id": "project_cc_python/2114" }
{ "list": [ { "filename": "test/test_lever_scraper.py", "retrieved_chunk": "options.add_argument('--headless')\ndriver = webdriver.Chrome(options=options)\nfor company in company_list:\n data = company.scraper_type().getJobs(driver, company.jobs_url, company.company_name)\n for entry in data:\n ...
scraper_type().getJobs(driver, company.jobs_url)
{ "list": [ { "filename": "up4ros/tests/test_add_object_service.py", "retrieved_chunk": "from up4ros.up4ros_node import UP4ROSNode\ndef test_add_object():\n node_test = UP4ROSNode(init_ros_interfaces=False)\n pb_writer = ROSInterfaceWriter()\n problems = get_example_problems()\n problem = ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
response = node_test.set_problem(req) assert response.success assert response.message == "" problem = node_test.problems["problem_test_robot"] goal_msg = msgs.PlanOneShotRemoteGoal() goal_msg.plan_request.problem = "problem_test_robot" def feedback_mock(feedback_msg): pb_reader =...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_remote_action.py", "groundtruth_start_lineno": 34, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 35, "task_id": "project_cc_python/2168" }
{ "list": [ { "filename": "up4ros/tests/test_add_object_service.py", "retrieved_chunk": " assert response.success\n assert response.message == \"\"\n Location = shortcuts.UserType(\"Location\")\n upf_object = model.Object(\"l3\", Location)\n add_object_req = srvs.AddObjectRequest()\n ...
convert(get_example_problems()["robot"].problem)
{ "list": [ { "filename": "up4ros/tests/test_plan_one_shot_action.py", "retrieved_chunk": " pb_reader = ROSInterfaceReader()\n upf_plan = pb_reader.convert(feedback_msg.plan_result.plan, problem)\n good_plan = \"[move(l1, l2)]\"\n assert upf_plan.__repr__() == good_plan\n ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
expected_result = msgs.PDDLPlanOneShotResult() expected_result.success = True expected_result.message = "" action_server_mock.set_succeeded.assert_called_with(expected_result) def test_plan_from_file_pddl_tt(): node_test = UP4ROSNode(init_ros_interfaces=False) # prepare the magic mock ...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_pddl_plan_one_shot_action.py", "groundtruth_start_lineno": 57, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 58, "task_id": "project_cc_python/2178" }
{ "list": [ { "filename": "up4ros/tests/test_plan_one_shot_action.py", "retrieved_chunk": " expected_result.message = \"\"\n action_server_mock.set_succeeded.assert_called_with(expected_result)", "score": 91.2405790436537 }, { "filename": "up4ros/tests/test_plan_one_shot_remo...
pddl_plan_one_shot_callback(goal_msg)
{ "list": [ { "filename": "up4ros/tests/test_pddl_plan_one_shot_action.py", "retrieved_chunk": " goal_msg.plan_request.problem = problem\n # let's mock the publish_feedback method\n reader = PDDLReader()\n upf_problem = reader.parse_problem(\n goal_msg.plan_request.domain, goal_msg....
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
good_plan = "[(Fraction(0, 1), move(leia, kitchen, bedroom), Fraction(5, 1))]" assert upf_plan.__repr__() == good_plan assert response.success assert response.message == ""
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_service.py", "groundtruth_start_lineno": 46, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 47, "task_id": "project_cc_python/2183" }
{ "list": [ { "filename": "up4ros/tests/test_pddl_plan_one_shot_action.py", "retrieved_chunk": " upf_plan = pb_reader.convert(msg.plan_result.plan, upf_problem)\n good_plan = \"[(Fraction(0, 1), move(leia, kitchen, bedroom), Fraction(5, 1))]\"\n assert upf_plan.__repr__() == good_...
convert(response.plan_result.plan, upf_problem)
{ "list": [ { "filename": "up4ros/tests/test_pddl_plan_one_shot_action.py", "retrieved_chunk": "# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permi...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
req.plan_request.mode = msgs.PDDLPlanRequest.FILE domain, problem = get_domain_and_problem( "/pddl/domain_tt.pddl", "/pddl/problem_tt_1.pddl" ) req.plan_request.domain = domain req.plan_request.problem = problem # let's mock the publish_feedback method reader = PDDLReader() up...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_service.py", "groundtruth_start_lineno": 28, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 29, "task_id": "project_cc_python/2180" }
{ "list": [ { "filename": "up4ros/tests/test_pddl_plan_one_shot_action.py", "retrieved_chunk": "def test_plan_from_file_pddl_no_tt():\n node_test = UP4ROSNode(init_ros_interfaces=False)\n # prepare the magic mock\n action_server_mock = MagicMock()\n goal_msg = msgs.PDDLPlanOneShotGoal()\n ...
PDDLPlanOneShotRequest()
{ "list": [ { "filename": "up4ros/tests/test_plan_one_shot_service.py", "retrieved_chunk": " reader = PDDLReader()\n upf_problem = reader.parse_problem(\n req.plan_request.domain, req.plan_request.problem\n )\n response = node_test.pddl_plan_one_shot(req)\n pb_reader = ROSInterfa...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
good_plans = [ "[pick(ball1, rooma, right), move(rooma, roomb), drop(ball1, roomb, right)]", "[pick(ball1, rooma, left), move(rooma, roomb), drop(ball1, roomb, left)]", ] assert upf_plan.__repr__() in good_plans action_server_mock.publish_feedback = feedback_mock ...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_pddl_plan_one_shot_action.py", "groundtruth_start_lineno": 46, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 47, "task_id": "project_cc_python/2177" }
{ "list": [ { "filename": "up4ros/tests/test_plan_one_shot_service.py", "retrieved_chunk": " assert response.message == \"\"", "score": 70.3155415446512 }, { "filename": "up4ros/scripts/example_pddl_client.py", "retrieved_chunk": " 0.1\n ) # sleep due to https:/...
convert(msg.plan_result.plan, upf_problem)
{ "list": [ { "filename": "up4ros/tests/test_plan_one_shot_action.py", "retrieved_chunk": " pb_reader = ROSInterfaceReader()\n upf_plan = pb_reader.convert(feedback_msg.plan_result.plan, problem)\n good_plan = \"[move(l1, l2)]\"\n assert upf_plan.__repr__() == good_plan\n ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
expected_result = msgs.PlanOneShotRemoteResult() expected_result.success = True expected_result.message = "" action_server_mock.set_succeeded.assert_called_with(expected_result) def test_one_shot_remote_failure(): node_test = UP4ROSNode(init_ros_interfaces=False) # prepare the magic mock ...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_remote_action.py", "groundtruth_start_lineno": 54, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 55, "task_id": "project_cc_python/2173" }
{ "list": [ { "filename": "up4ros/tests/test_plan_one_shot_action.py", "retrieved_chunk": " expected_result.message = \"\"\n action_server_mock.set_succeeded.assert_called_with(expected_result)", "score": 125.7394601935001 }, { "filename": "up4ros/tests/test_pddl_plan_one_sho...
plan_one_shot_remote_callback(goal_msg)
{ "list": [ { "filename": "up4ros/tests/test_pddl_plan_one_shot_action.py", "retrieved_chunk": " )\n goal_msg.plan_request.domain = domain\n goal_msg.plan_request.problem = problem\n # let's mock the publish_feedback method\n reader = PDDLReader()\n upf_problem = reader.parse_problem...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
pb_reader = ROSInterfaceReader() upf_plan = pb_reader.convert(response.plan_result.plan, upf_problem) good_plan = "[(Fraction(0, 1), move(leia, kitchen, bedroom), Fraction(5, 1))]" assert upf_plan.__repr__() == good_plan assert response.success assert response.message == ""
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_service.py", "groundtruth_start_lineno": 43, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 44, "task_id": "project_cc_python/2182" }
{ "list": [ { "filename": "up4ros/tests/test_pddl_plan_one_shot_action.py", "retrieved_chunk": " upf_plan = pb_reader.convert(msg.plan_result.plan, upf_problem)\n good_plan = \"[(Fraction(0, 1), move(leia, kitchen, bedroom), Fraction(5, 1))]\"\n assert upf_plan.__repr__() == good_...
pddl_plan_one_shot(req)
{ "list": [ { "filename": "up4ros/tests/test_set_and_get_problem_service.py", "retrieved_chunk": " node_test = UP4ROSNode(init_ros_interfaces=False)\n pb_writer = ROSInterfaceWriter()\n problems = get_example_problems()\n problem = problems[\"robot\"].problem\n req = srvs.SetProblemRequ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
goal_msg.plan_request.problem = "problem_test_robot" def feedback_mock(feedback_msg): pb_reader = ROSInterfaceReader() upf_plan = pb_reader.convert(feedback_msg.plan_result.plan, problem) good_plan = "[move(l1, l2)]" assert upf_plan.__repr__() == good_plan action_server_mo...
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_remote_action.py", "groundtruth_start_lineno": 41, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 42, "task_id": "project_cc_python/2171" }
{ "list": [ { "filename": "up4ros/tests/test_set_and_get_problem_service.py", "retrieved_chunk": " req = srvs.SetProblemRequest()\n req.problem_name = \"problem_test_robot\"\n req.problem = pb_writer.convert(problem)\n response = node_test.set_problem(req)\n assert not response.success\...
PlanOneShotRemoteGoal()
{ "list": [ { "filename": "nlpeer/tasks/review_score/evaluate.py", "retrieved_chunk": " tokenizer = module.get_tokenizer()\n # prepare data (loading splits from disk)\n data_module = ReviewScorePredictionDataModule(benchmark_path=config[\"dataset\"][\"benchmark_path\"],\n ...
import argparse import os import time import uuid from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping from pytorch_lightning.loggers import WandbLogger import torch import wandb from nlpeer.data import DATASETS from nlpeer.tasks.pragmatic_lab...
return module, data_module def train(model, data_module, params, logger=None, debug=False): global OUT_PATH print(f"RUN = {wandb.run.name}") chkp_dir = os.path.join(OUT_PATH, f"checkpoints/{params['dataset']['type']}/{params['model']['type']}") checkpoint_callback = ModelCheckpoint(monitor="va...
{ "context_start_lineno": 0, "file": "nlpeer/tasks/pragmatic_labeling/train.py", "groundtruth_start_lineno": 81, "repository": "UKPLab-nlpeer-f81f4bb", "right_context_start_lineno": 82, "task_id": "project_cc_python/2092" }
{ "list": [ { "filename": "nlpeer/tasks/review_score/evaluate.py", "retrieved_chunk": " DATASETS[config[\"dataset\"][\"type\"]],\n config[\"dataset\"][\"paper_version\"],\n PAPERFORMATS.IT...
setup("fit")
{ "list": [ { "filename": "up4ros/tests/test_set_and_get_problem_service.py", "retrieved_chunk": " node_test = UP4ROSNode(init_ros_interfaces=False)\n pb_writer = ROSInterfaceWriter()\n problems = get_example_problems()\n problem = problems[\"robot\"].problem\n req = srvs.SetProblemRequ...
# Copyright 2023 Magazino GmbH # Copyright 2022 Intelligent Robotics Lab # # 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...
goal_msg = msgs.PlanOneShotRemoteGoal() goal_msg.plan_request.problem = "problem_test_robot" def feedback_mock(feedback_msg): pb_reader = ROSInterfaceReader() upf_plan = pb_reader.convert(feedback_msg.plan_result.plan, problem) good_plan = "[move(l1, l2)]" assert upf_plan....
{ "context_start_lineno": 0, "file": "up4ros/tests/test_plan_one_shot_remote_action.py", "groundtruth_start_lineno": 39, "repository": "aiplan4eu-UP4ROS-59c1358", "right_context_start_lineno": 40, "task_id": "project_cc_python/2170" }
{ "list": [ { "filename": "up4ros/tests/test_set_and_get_problem_service.py", "retrieved_chunk": " req = srvs.SetProblemRequest()\n req.problem_name = \"problem_test_robot\"\n req.problem = pb_writer.convert(problem)\n response = node_test.set_problem(req)\n assert not response.success\...
problems["problem_test_robot"]
{ "list": [ { "filename": "tests/coord_test.py", "retrieved_chunk": " t = t_near * (1 - u) + t_far * u\n key, rng = random.split(rng)\n s = jax.random.uniform(key, [n])\n t_to_s, s_to_t = coord.construct_ray_warps(jnp.reciprocal, t_near, t_far)\n # Special cases for fn=reciprocal.\n ...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def integrated_pos_enc(mean, var, min_deg, max_deg): """Encode `x` with sinusoids scaled by 2^[min_deg, max_deg). Args: mean: tensor, the mean coordinates to be encoded var: tensor, the variance of the coordinates to be encoded. min_deg: int, the min degree of the encoding. max_deg: ...
{ "context_start_lineno": 0, "file": "internal/coord.py", "groundtruth_start_lineno": 180, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 181, "task_id": "project_cc_python/2225" }
{ "list": [ { "filename": "tests/coord_test.py", "retrieved_chunk": " normal_samples = random.normal(random.PRNGKey(0), (10000,))\n for mu, var in [(0, 1), (1, 3), (-2, .2), (10, 10)]:\n sin_mu = coord.expected_sin(mu, var)\n x = jnp.sin(jnp.sqrt(var) * normal_samples + mu)\n np.t...
safe_sin(mean) # large var -> small value.
{ "list": [ { "filename": "internal/coord.py", "retrieved_chunk": " return expected_sin(\n torch.cat([scaled_mean, scaled_mean + 0.5 * torch.pi], dim=-1),\n torch.cat([scaled_var] * 2, dim=-1))\ndef lift_and_diagonalize(mean, cov, basis):\n \"\"\"Project `mean` and `cov` onto basis...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
z_stable = stable_pos_enc(x, n) max_err = np.max(np.abs(z - z_stable)) print(f'PE of degree {n} has a maximum error of {max_err}') self.assertLess(max_err, tol) def test_pos_enc_matches_integrated(self): """Integrated positional encoding with a variance of zero must be pos_enc.""" min_deg = ...
{ "context_start_lineno": 0, "file": "tests/coord_test.py", "groundtruth_start_lineno": 122, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 123, "task_id": "project_cc_python/2235" }
{ "list": [ { "filename": "internal/geopoly.py", "retrieved_chunk": " elif base_shape == 'octahedron':\n verts = np.array([(0, 0, -1), (0, 0, 1), (0, -1, 0), (0, 1, 0), (-1, 0, 0),\n (1, 0, 0)])\n corners = np.array(list(itertools.product([-1, 1], repeat=3)))\n pairs = n...
pos_enc(x[:, None], 0, n, append_identity=False)
{ "list": [ { "filename": "internal/geopoly.py", "retrieved_chunk": " # Use the fact that ||x - y||^2 == ||x||^2 + ||y||^2 - 2 x^T y.\n sq_norm0 = np.sum(mat0**2, 0)\n sq_norm1 = np.sum(mat1**2, 0)\n sq_dist = sq_norm0[:, None] + sq_norm1[None, :] - 2 * mat0.T @ mat1\n sq_dist = np.maximum(0, sq_...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
basis_golden = np.array([[0.85065081, 0.00000000, 0.52573111], [0.80901699, 0.50000000, 0.30901699], [0.52573111, 0.85065081, 0.00000000], [1.00000000, 0.00000000, 0.00000000], [0.80901699, 0.5000000...
{ "context_start_lineno": 0, "file": "tests/geopoly_test.py", "groundtruth_start_lineno": 77, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 78, "task_id": "project_cc_python/2230" }
{ "list": [ { "filename": "internal/geopoly.py", "retrieved_chunk": " int_weights = []\n for i in range(v + 1):\n for j in range(v + 1 - i):\n int_weights.append((i, j, v - (i + j)))\n int_weights = np.array(int_weights)\n weights = int_weights / v # Barycentric weights.\n return weights...
generate_basis('icosahedron', 2)
{ "list": [ { "filename": "tests/ref_utils_test.py", "retrieved_chunk": " rng = random.PRNGKey(0)\n key1, key2 = random.split(rng)\n theta = random.uniform(key1, shape, minval=0.0, maxval=jnp.pi)\n phi = random.uniform(key2, shape, minval=0.0, maxval=2.0*jnp.pi)\n # Convert to Cartesian...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
z_pe = coord.pos_enc(x, min_deg, max_deg, append_identity=False) # We're using a pretty wide tolerance because IPE uses safe_sin(). np.testing.assert_allclose(z_pe, z_ipe, atol=1e-4) def test_track_linearize(self): rng = random.PRNGKey(0) batch_size = 20 for _ in range(30): # Construct...
{ "context_start_lineno": 0, "file": "tests/coord_test.py", "groundtruth_start_lineno": 136, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 137, "task_id": "project_cc_python/2236" }
{ "list": [ { "filename": "tests/ref_utils_test.py", "retrieved_chunk": " de = ref_utils.generate_dir_enc_fn(deg_view)(xyz)\n de_scipy = generate_dir_enc_fn_scipy(deg_view)(theta, phi)\n np.testing.assert_allclose(\n de, de_scipy, atol=0.02, rtol=1e6) # Only use atol.\n self.assert...
integrated_pos_enc(x, jnp.zeros_like(x), min_deg, max_deg)
{ "list": [ { "filename": "tests/render_test.py", "retrieved_chunk": " batch_size = 10\n for num_dims in [1, 2, 3]:\n key, rng = random.split(rng)\n mean = jax.random.normal(key, [batch_size, num_dims])\n key, rng = random.split(rng)\n half_cov = jax.random.normal(key, [batch...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
return cov def stable_pos_enc(x, n): """A stable pos_enc for very high degrees, courtesy of Sameer Agarwal.""" sin_x = np.sin(x) cos_x = np.cos(x) output = [] rotmat = np.array([[cos_x, -sin_x], [sin_x, cos_x]], dtype='double') for _ in range(n): output.append(rotmat[::-1, 0, :]) rotmat = np.ei...
{ "context_start_lineno": 0, "file": "tests/coord_test.py", "groundtruth_start_lineno": 29, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 30, "task_id": "project_cc_python/2231" }
{ "list": [ { "filename": "tests/image_test.py", "retrieved_chunk": "def matmul(a, b):\n \"\"\"jnp.matmul defaults to bfloat16, but this helper function doesn't.\"\"\"\n return jnp.matmul(a, b, precision=jax.lax.Precision.HIGHEST)\nclass ImageTest(absltest.TestCase):\n def test_color_correction(sel...
matmul(half_cov, jnp.moveaxis(half_cov, -1, -2))
{ "list": [ { "filename": "tests/camera_utils_test.py", "retrieved_chunk": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for camera_utils.\"\"\"\nfrom abs...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
return (np.all(np.array(x.shape) == np.array(y.shape)) and np.all(np.sum(match, axis=0) == 1) and np.all(np.sum(match, axis=1) == 1)) class GeopolyTest(absltest.TestCase): def test_compute_sq_dist_reference(self): """Test against a simple reimplementation of compute_sq_dist.""" num_p...
{ "context_start_lineno": 0, "file": "tests/geopoly_test.py", "groundtruth_start_lineno": 27, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 28, "task_id": "project_cc_python/2228" }
{ "list": [ { "filename": "tests/camera_utils_test.py", "retrieved_chunk": "class CameraUtilsTest(parameterized.TestCase):\n def test_convert_to_ndc(self):\n rng = random.PRNGKey(0)\n for _ in range(10):\n # Random pinhole camera intrinsics.\n key, rng = random.split(rng)\n focal...
compute_sq_dist(x, y), geopoly.compute_sq_dist(x, -y)) <= tol
{ "list": [ { "filename": "tests/math_test.py", "retrieved_chunk": " fp = random.normal(key, [n, d1])\n if sort:\n xp = jnp.sort(xp, axis=-1)\n fp = jnp.sort(fp, axis=-1)\n z = math.sorted_interp(x, xp, fp)\n else:\n z = math.interp(x, xp, fp)\n z_true = jnp.stack([jnp....
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
delta_tc = tc[1:] - tc[:-1] np.testing.assert_allclose( delta_tc, np.full_like(delta_tc, 1 / n), atol=1E-5, rtol=1E-5) def test_contract_is_bounded(self): n, d = 10000, 3 rng = random.PRNGKey(0) key0, key1, rng = random.split(rng, 3) x = jnp.where(random.bernoulli(key0, shape=[n, d])...
{ "context_start_lineno": 0, "file": "tests/coord_test.py", "groundtruth_start_lineno": 65, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 66, "task_id": "project_cc_python/2233" }
{ "list": [ { "filename": "tests/math_test.py", "retrieved_chunk": " absltest.main()", "score": 87.75675127160255 }, { "filename": "tests/stepfun_test.py", "retrieved_chunk": " # The interval edge near the extent should be centered around +/-0.5.\n if randomized:\n ...
contract(s_to_t(s)[:, None])[:, 0]
{ "list": [ { "filename": "internal/stepfun.py", "retrieved_chunk": " # Are the two intervals not overlapping?\n are_disjoint = (t0_lo > t1_hi) | (t1_lo > t0_hi)\n return torch.where(are_disjoint, d_disjoint, d_overlap)\ndef weighted_percentile(t, w, ps):\n \"\"\"Compute the weighted perce...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def sinebow(h): """A cyclic and uniform colormap, see http://basecase.org/env/on-rainbows.""" def f(x): return torch.sin(torch.pi * x)**2 return torch.stack([f(3 / 6 - h), f(5 / 6 - h), f(7 / 6 - h)], -1) def matte(vis, acc, dark=0.8, light=1.0, width=8): """Set non-accumulated pixels to a Photosho...
{ "context_start_lineno": 0, "file": "internal/vis.py", "groundtruth_start_lineno": 32, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 33, "task_id": "project_cc_python/2226" }
{ "list": [ { "filename": "internal/render.py", "retrieved_chunk": " ps = [5, 50, 95]\n distance_percentiles = stepfun.weighted_percentile(\n t_aug, weights_aug, ps)\n for i, p in enumerate(ps):\n s = 'median' if p == 50 else 'percentile_' + str(p)\n ...
interp(ps * acc_w[-1] / 100, acc_w, x)
{ "list": [ { "filename": "internal/stepfun.py", "retrieved_chunk": " domain=(-torch.inf, torch.inf),\n renormalize=False):\n \"\"\"Dilate (via max-pooling) a set of weights.\"\"\"\n eps = torch.finfo(w.dtype).eps\n # eps = 1e-3\n p = weight_to_p...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
vis_ws.append(stepfun.resample(dist_vis, d, w.T, use_avg=True).T) vis_rgb.append(torch.stack(vis_rs)) vis_alpha.append(torch.stack(vis_ws)) vis_rgb = torch.stack(vis_rgb, dim=1) vis_alpha = torch.stack(vis_alpha, dim=1) if renormalize: # Scale the alphas so that the lar...
{ "context_start_lineno": 0, "file": "internal/vis.py", "groundtruth_start_lineno": 139, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 140, "task_id": "project_cc_python/2227" }
{ "list": [ { "filename": "internal/render.py", "retrieved_chunk": " rendering['rgb'] = rgb\n if compute_extras:\n rendering['acc'] = acc\n if extras is not None:\n for k, v in extras.items():\n if v is not None:\n rendering[k] = (weight...
resample(dist_vis, d, r.T, use_avg=True).T)
{ "list": [ { "filename": "tests/math_test.py", "retrieved_chunk": " fp = random.normal(key, [n, d1])\n if sort:\n xp = jnp.sort(xp, axis=-1)\n fp = jnp.sort(fp, axis=-1)\n z = math.sorted_interp(x, xp, fp)\n else:\n z = math.interp(x, xp, fp)\n z_true = jnp.stack([jnp....
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
s = jnp.linspace(0, 1 - jnp.finfo(jnp.float32).eps, n + 1) tc = coord.contract(s_to_t(s)[:, None])[:, 0] delta_tc = tc[1:] - tc[:-1] np.testing.assert_allclose( delta_tc, np.full_like(delta_tc, 1 / n), atol=1E-5, rtol=1E-5) def test_contract_is_bounded(self): n, d = 10000, 3 rng = ra...
{ "context_start_lineno": 0, "file": "tests/coord_test.py", "groundtruth_start_lineno": 63, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 64, "task_id": "project_cc_python/2232" }
{ "list": [ { "filename": "tests/math_test.py", "retrieved_chunk": " absltest.main()", "score": 77.62295946528592 }, { "filename": "tests/stepfun_test.py", "retrieved_chunk": " # The interval edge near the extent should be centered around +/-0.5.\n if randomized:\n ...
construct_ray_warps(jnp.reciprocal, 1, jnp.inf)
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": "def create_study_tracker(k_splits: int, metrics: list) -> dict:\n \"\"\"\n creates a study tracker for multiple seeds\n :param k_splits: the number of seeds\n :param metrics: the metrics to create a tracker for\n :return res...
from main import neural_run from omegaconf import OmegaConf, DictConfig import ugle import argparse from ugle.logger import log import pickle from os.path import exists from os import makedirs from copy import deepcopy def run_study(study_override_cfg: DictConfig, algorithm: str, dataset: str, seeds: list): """ ...
study_results = OmegaConf.create({'dataset': dataset, 'model': algorithm, 'average_results': {}, 'results': []}) # repeat training over all seeds for idx, seed in enumerate(seeds): ...
{ "context_start_lineno": 0, "file": "model_evaluations.py", "groundtruth_start_lineno": 21, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 22, "task_id": "project_cc_python/2263" }
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " return results\ndef create_experiment_tracker(exp_cfg: DictConfig) -> list:\n \"\"\"\n creates the experiment tracker to track results\n :param exp_cfg: experiment config\n :experiment_tracker: list of results objects that ...
utils.create_study_tracker(len(seeds), study_cfg.trainer.test_metrics)
{ "list": [ { "filename": "tests/stepfun_test.py", "retrieved_chunk": " key, rng = random.split(rng)\n logits = 2 * random.normal(key, shape=(n, d))\n # Compute the distortion loss.\n w = jax.nn.softmax(logits, axis=-1)\n losses = stepfun.lossfun_distortion(t, w)\n # Compute it again...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
t_new = interp_fn(u, cw, t) return t_new def sample( t, w_logits, num_samples, single_jitter=False, deterministic_center=False, use_gpu_resampling=False ): """Piecewise-Constant PDF sampling from a step function. Args: t: [..., num_bins + 1], bin...
{ "context_start_lineno": 0, "file": "internal/stepfun.py", "groundtruth_start_lineno": 229, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 230, "task_id": "project_cc_python/2223" }
{ "list": [ { "filename": "internal/vis.py", "retrieved_chunk": " vis_alpha = torch.stack(vis_alpha, dim=1)\n if renormalize:\n # Scale the alphas so that the largest value is 1, for visualization.\n vis_alpha /= torch.max(torch.finfo(torch.float32).eps,\n ...
interp if use_gpu_resampling else math.sorted_interp
{ "list": [ { "filename": "ugle/__init__.py", "retrieved_chunk": " results = {}\n for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):\n full_name = package.__name__ + '.' + name\n results[full_name] = importlib.import_module(full_name)\n if recursive and is_...
import os from omegaconf import OmegaConf, DictConfig import numpy as np from karateclub.dataset import GraphReader import networkx as nx import zipfile import gdown from pathlib import Path import shutil import torch import copy import random import scipy.sparse as sp import plotly.graph_objects as go from typing impo...
train_adj, test_adj = split_adj(adjacency, test_split, split_scheme) return features, label, train_adj, test_adj def compute_datasets_info(dataset_names: list, visualise: bool=False): """ computes the information about dataset statistics :param dataset_names: list of datasets to look at """ ...
{ "context_start_lineno": 0, "file": "ugle/datasets.py", "groundtruth_start_lineno": 118, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 119, "task_id": "project_cc_python/2268" }
{ "list": [ { "filename": "ugle/logger.py", "retrieved_chunk": " logger.setLevel(logging.INFO)\n # Create a stream handler (console output)\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.INFO)\n file_handler = logging.FileHandler(filename= log_path + uid)\n...
debug('splitting dataset into training/testing')
{ "list": [ { "filename": "internal/camera_utils.py", "retrieved_chunk": " far: float,\n xnp: types.ModuleType) -> utils.Rays:\n \"\"\"Generates a spherical camera ray batch.\"\"\"\n theta_vals = xnp.linspace(0, 2 * xnp.pi, width + 1)\n phi_vals =...
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
de_scipy = generate_dir_enc_fn_scipy(deg_view)(theta, phi) np.testing.assert_allclose( de, de_scipy, atol=0.02, rtol=1e6) # Only use atol. self.assertFalse(jnp.any(jnp.isnan(de))) if __name__ == '__main__': absltest.main()
{ "context_start_lineno": 0, "file": "tests/ref_utils_test.py", "groundtruth_start_lineno": 77, "repository": "ingra14m-mipnerf360-pytorch-bfc1e77", "right_context_start_lineno": 78, "task_id": "project_cc_python/2241" }
{ "list": [ { "filename": "internal/camera_utils.py", "retrieved_chunk": " xnp.sin(phi) * xnp.cos(theta),\n ],\n axis=-1)\n directions = xnp.matmul(camtoworld[:3, :3], directions[..., None])[..., 0]\n dy = xnp.diff(directions[:, :-1], axis=0)\n dx = xnp.diff(directions[:-1, :...
generate_dir_enc_fn(deg_view)(xyz)
{ "list": [ { "filename": "ugle/models/sublime.py", "retrieved_chunk": " def __init__(self, nlayers, isize, k, knn_metric, i, sparse, act):\n super(MLP_learner, self).__init__()\n self.layers = nn.ModuleList()\n if nlayers == 1:\n self.layers.append(nn.Linear(isize, ...
# https://github.com/zekarias-tilahun/SelfGNN import torch import torch.nn as nn import torch.nn.functional as F from fast_pytorch_kmeans import KMeans import scipy.sparse as sp from torch_geometric.nn import GCNConv, GATConv, SAGEConv from functools import wraps import copy import ugle from ugle.trainer import ugleTra...
features, adjacency, aug_features, aug_adjacency = augmentation(features, adjacency) features = torch.FloatTensor(features) adjacency = torch.LongTensor(adjacency) aug_features = torch.FloatTensor(aug_features) aug_adjacency = torch.LongTensor(aug_adjacency) diff = abs...
{ "context_start_lineno": 0, "file": "ugle/models/selfgnn.py", "groundtruth_start_lineno": 192, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 193, "task_id": "project_cc_python/2274" }
{ "list": [ { "filename": "ugle/models/sublime.py", "retrieved_chunk": " self.input_dim = isize\n self.output_dim = isize\n self.k = k\n self.knn_metric = knn_metric\n self.non_linearity = 'relu'\n self.param_init()\n self.i = i\n self.act = act\...
datasets.Augmentations(method=self.cfg.args.aug)
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " return results\ndef create_experiment_tracker(exp_cfg: DictConfig) -> list:\n \"\"\"\n creates the experiment tracker to track results\n :param exp_cfg: experiment config\n :experiment_tracker: list of results objects that ...
from main import neural_run from omegaconf import OmegaConf, DictConfig import ugle import argparse from ugle.logger import log import pickle from os.path import exists from os import makedirs from copy import deepcopy def run_study(study_override_cfg: DictConfig, algorithm: str, dataset: str, seeds: list): """ ...
log.info(f"adding to cpu fallback test") experiments_cpu.append(experiment) # run all experiments that didn't work on gpu if experiments_cpu and exp_cfg.run_cpu_fallback: log.info(f'launching cpu fallback experiments') exp_cfg.study_override_cfg....
{ "context_start_lineno": 0, "file": "model_evaluations.py", "groundtruth_start_lineno": 142, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 143, "task_id": "project_cc_python/2266" }
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " experiment_tracker.append(OmegaConf.create(\n {'dataset': dataset,\n 'algorithm': algorithm,\n 'seeds': exp_cfg.seeds,\n ...
exception(str(e))
{ "list": [ { "filename": "ugle/models/mvgrl.py", "retrieved_chunk": " features, adj, diff_adj = processed_data\n if adj.shape[-1] < args.sample_size:\n args.sample_size = int(np.floor(adj.shape[-1] / 100.0) * 100)\n self.model = Model(args.n_features, args.hid_units, a...
# https://github.com/GRAND-Lab/SUBLIME import torch import torch.nn as nn from torch.nn import Sequential, Linear, ReLU import torch.nn.functional as F import numpy as np import copy from fast_pytorch_kmeans import KMeans from ugle.trainer import ugleTrainer EOS = 1e-10 class GCNConv_dense(nn.Module): def __init__...
anchor_adj = anchor_adj * args.tau + Adj.detach() * (1 - args.tau) processed_data = (features, anchor_adj) return loss, processed_data def test(self, processed_data): features, anchor_adj = processed_data self.model.eval() self.graph_learner.eval() wi...
{ "context_start_lineno": 0, "file": "ugle/models/sublime.py", "groundtruth_start_lineno": 326, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 327, "task_id": "project_cc_python/2273" }
{ "list": [ { "filename": "ugle/models/vgaer.py", "retrieved_chunk": " A_orig_ten, A_hat, feats, weight_tensor, norm = processed_data\n recovered = self.model.forward(A_hat, feats)\n logits = recovered[0]\n hidemb = recovered[1]\n logits = logits.clamp(min=0., max=1....
current_epoch % args.c == 0):
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " return results\ndef create_experiment_tracker(exp_cfg: DictConfig) -> list:\n \"\"\"\n creates the experiment tracker to track results\n :param exp_cfg: experiment config\n :experiment_tracker: list of results objects that ...
from main import neural_run from omegaconf import OmegaConf, DictConfig import ugle import argparse from ugle.logger import log import pickle from os.path import exists from os import makedirs from copy import deepcopy def run_study(study_override_cfg: DictConfig, algorithm: str, dataset: str, seeds: list): """ ...
log.debug(f'testing dataset: {experiment.dataset}') log.debug(f'testing algorithm: {experiment.algorithm}') if exp_cfg.study_override_cfg.trainer.retrain_on_each_dataset: if exp_num > iterations_before_fine_tuning: exp_cfg.study_overr...
{ "context_start_lineno": 0, "file": "model_evaluations.py", "groundtruth_start_lineno": 118, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 119, "task_id": "project_cc_python/2265" }
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " experiment_tracker.append(OmegaConf.create(\n {'dataset': dataset,\n 'algorithm': algorithm,\n 'seeds': exp_cfg.seeds,\n ...
debug(f'starting new experiment ... ...')
{ "list": [ { "filename": "ugle/models/cagc.py", "retrieved_chunk": "import torch.nn.functional as F\ndef knn_fast(X, k):\n X = F.normalize(X, dim=1, p=2)\n similarities = torch.mm(X, X.t())\n vals, inds = similarities.topk(k=k + 1, dim=-1)\n return inds\ndef sim(z1: torch.Tensor, z2: torc...
# https://github.com/GRAND-Lab/SUBLIME import torch import torch.nn as nn from torch.nn import Sequential, Linear, ReLU import torch.nn.functional as F import numpy as np import copy from fast_pytorch_kmeans import KMeans from ugle.trainer import ugleTrainer EOS = 1e-10 class GCNConv_dense(nn.Module): def __init__...
mask_v1, _ = get_feat_mask(features, self.cfg.args.maskfeat_rate_anchor) mask_v1 = mask_v1.to(self.device) features_v1 = features * (1 - mask_v1) else: features_v1 = copy.deepcopy(features) features_v1 = features_v1.to(self.device) z1, _ = model(...
{ "context_start_lineno": 0, "file": "ugle/models/sublime.py", "groundtruth_start_lineno": 254, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 255, "task_id": "project_cc_python/2272" }
{ "list": [ { "filename": "ugle/models/cagc.py", "retrieved_chunk": "def semi_loss(z1: torch.Tensor, z2: torch.Tensor, tau: float):\n f = lambda x: torch.exp(x / tau)\n refl_sim = f(sim(z1, z1))\n between_sim = f(sim(z1, z2))\n return -torch.log(\n between_sim.diag()\n / (ref...
cfg.args.maskfeat_rate_anchor:
{ "list": [ { "filename": "ugle/trainer.py", "retrieved_chunk": " log.info(f'Launching Trial {trial.number}')\n # if finetuning or reusing init procedure then just use default architecture sizes\n if self.cfg.trainer.finetuning_new_dataset or self.cfg.trainer.same_init...
from omegaconf import OmegaConf, open_dict, DictConfig from optuna import Study from typing import Tuple import random import torch import numpy as np import optuna import os import pickle from ugle.logger import log neural_algorithms = ['daegc', 'dgi', 'dmon', 'grace', 'mvgrl', 'selfgnn', 'sublime', 'bgrl', 'vgaer', ...
return args def assign_test_params(config: DictConfig, best_params: dict) -> DictConfig: """ assigns the best params from the hyperparameter selection and assigns test config settings :param config: original config for training :param best_params: the best hyperparameters from training :retur...
{ "context_start_lineno": 0, "file": "ugle/utils.py", "groundtruth_start_lineno": 148, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 149, "task_id": "project_cc_python/2269" }
{ "list": [ { "filename": "ugle/helper.py", "retrieved_chunk": "def make_test_performance_object(datasets, algorithms, metrics, seeds, folder):\n # get results object\n result_object = np.zeros(shape=(len(datasets), len(algorithms), len(metrics), len(seeds)))\n try:\n result_holder = g...
info(f"args.{var}={val}")
{ "list": [ { "filename": "ugle/trainer.py", "retrieved_chunk": " log.info(f'Launching Trial {trial.number}')\n # if finetuning or reusing init procedure then just use default architecture sizes\n if self.cfg.trainer.finetuning_new_dataset or self.cfg.trainer.same_init...
import ugle import ugle.utils as utils from ugle.logger import log from ugle.trainer import MyLibrarySniffingClass from omegaconf import OmegaConf, DictConfig, open_dict import argparse import psutil import time from os.path import isfile import pickle def neural_run(override_model: str = None, overrid...
start_time = time.time() # memory profiling max memory requires other class if 'memory' in Trainer.cfg.trainer.test_metrics: # train model start_mem = psutil.virtual_memory().active mythread = MyLibrarySniffingClass(Trainer.eval) mythread.start() delta_mem = 0 ...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 44, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 45, "task_id": "project_cc_python/2259" }
{ "list": [ { "filename": "ugle/trainer.py", "retrieved_chunk": " self.training_preprocessing(self.cfg.args, processed_data)\n self.model.train()\n if self.cfg.trainer.finetuning_new_dataset:\n log.info('Loading pretrained model')\n self.model.load_state_dict...
models, cfg.model), f"{cfg.model}_trainer")(cfg)
{ "list": [ { "filename": "ugle/trainer.py", "retrieved_chunk": " self.training_preprocessing(self.cfg.args, processed_data)\n self.model.train()\n if self.cfg.trainer.finetuning_new_dataset:\n log.info('Loading pretrained model')\n self.model.load_state_dict...
import ugle import ugle.utils as utils from ugle.logger import log from ugle.trainer import MyLibrarySniffingClass from omegaconf import OmegaConf, DictConfig, open_dict import argparse import psutil import time from os.path import isfile import pickle def neural_run(override_model: str = None, overrid...
previously_found = pickle.load(open(hpo_path, "rb")) cfg.previous_results = previously_found.results # if this doesn't exist then just use the default parameters else: log.info(f'loading default args') found_args = OmegaConf.load(f'ugle/configs/models/{c...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 32, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 33, "task_id": "project_cc_python/2258" }
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " if override_model:\n config.model = override_model\n config_name = config.model\n model_name = config.model\n # model_path structure edit if testing\n if config_name.__contains__('_'):\n model_name, name_ext =...
info(f'loading hpo args: {hpo_path}')
{ "list": [ { "filename": "api/apps/rss/urls.py", "retrieved_chunk": "from django.urls import re_path\nfrom .views import MainFeedListView, MainFeedRetrieveView\nurlpatterns = (\n re_path(r\"^main-feed/?$\", MainFeedListView.as_view(), name=\"rss-main-feed-list\"),\n re_path(\n r\"^main-f...
import datetime import feedparser from adrf.views import APIView as AsyncAPIView from django.core.cache import cache from feedparser import FeedParserDict from rest_framework.request import Request from rest_framework.response import Response from config import shared from .models import MainFeed class MainFeedLis...
text = await resp.text() fd: FeedParserDict = feedparser.parse(text) rss = {"channel": fd.channel, "entries": fd.entries} # setting cache cache_time = 15 * 60 - (date.minute % 15 * 60 + date.second) await cache.aset(feed_key, rss, cache_time)...
{ "context_start_lineno": 0, "file": "api/apps/rss/views.py", "groundtruth_start_lineno": 40, "repository": "memew1se-OpenRSS-f7b766b", "right_context_start_lineno": 41, "task_id": "project_cc_python/2252" }
{ "list": [ { "filename": "api/apps/rss/urls.py", "retrieved_chunk": "from django.urls import re_path\nfrom .views import MainFeedListView, MainFeedRetrieveView\nurlpatterns = (\n re_path(r\"^main-feed/?$\", MainFeedListView.as_view(), name=\"rss-main-feed-list\"),\n re_path(\n r\"^main-f...
AIOHTTP_SESSION.get(feed.url) as resp:
{ "list": [ { "filename": "ugle/trainer.py", "retrieved_chunk": " def isShutdown(self):\n return self.__has_shutdown\n ###############################\n ### User Defined Functions ####\n ###############################\n def mainloop(self):\n '''\n Expected to be ov...
import ugle import ugle.utils as utils from ugle.logger import log from ugle.trainer import MyLibrarySniffingClass from omegaconf import OmegaConf, DictConfig, open_dict import argparse import psutil import time from os.path import isfile import pickle def neural_run(override_model: str = None, overrid...
break max_memory /= 1024.0 ** 2 log.info(f"MAX Memory Usage in MB: {max_memory:.2f}") log.info(f"Max useage %: {max_percent}") results = mythread.results results['memory'] = max_memory else: # train and evaluate model results = Trainer.eval...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 66, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 67, "task_id": "project_cc_python/2261" }
{ "list": [ { "filename": "ugle/trainer.py", "retrieved_chunk": " def isShutdown(self):\n return self.__has_shutdown\n ###############################\n ### User Defined Functions ####\n ###############################\n def mainloop(self):\n '''\n Expected to be ov...
isShutdown():
{ "list": [ { "filename": "ugle/models/sublime.py", "retrieved_chunk": " def __init__(self, nlayers, isize, k, knn_metric, i, sparse, act):\n super(MLP_learner, self).__init__()\n self.layers = nn.ModuleList()\n if nlayers == 1:\n self.layers.append(nn.Linear(isize, ...
# https://github.com/zekarias-tilahun/SelfGNN import torch import torch.nn as nn import torch.nn.functional as F from fast_pytorch_kmeans import KMeans import scipy.sparse as sp from torch_geometric.nn import GCNConv, GATConv, SAGEConv from functools import wraps import copy import ugle from ugle.trainer import ugleTra...
features, adjacency, aug_features, aug_adjacency = augmentation(features, adjacency) features = torch.FloatTensor(features) adjacency = torch.LongTensor(adjacency) aug_features = torch.FloatTensor(aug_features) aug_adjacency = torch.LongTensor(aug_adjacency) diff = abs...
{ "context_start_lineno": 0, "file": "ugle/models/selfgnn.py", "groundtruth_start_lineno": 192, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 193, "task_id": "project_cc_python/2275" }
{ "list": [ { "filename": "ugle/models/sublime.py", "retrieved_chunk": " self.input_dim = isize\n self.output_dim = isize\n self.k = k\n self.knn_metric = knn_metric\n self.non_linearity = 'relu'\n self.param_init()\n self.i = i\n self.act = act\...
cfg.args.aug)
{ "list": [ { "filename": "ugle/models/mvgrl.py", "retrieved_chunk": " features, adj, diff_adj = processed_data\n if adj.shape[-1] < args.sample_size:\n args.sample_size = int(np.floor(adj.shape[-1] / 100.0) * 100)\n self.model = Model(args.n_features, args.hid_units, a...
# code insipred from https://github.com/Tiger101010/DAEGC import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.optim import Adam from fast_pytorch_kmeans import KMeans import scipy.sparse as sp import ugle from ugle.logger import log f...
# update_interval A_pred, z, Q = self.model(features, adj, M) q = Q.detach().data.cpu().numpy().argmax(1) A_pred, z, q = self.model(features, adj, M) p = target_distribution(Q.detach()) kl_loss = F.kl_div(q.log(), p, reduction='batchmean') re_loss =...
{ "context_start_lineno": 0, "file": "ugle/models/daegc.py", "groundtruth_start_lineno": 111, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 112, "task_id": "project_cc_python/2293" }
{ "list": [ { "filename": "ugle/models/mvgrl.py", "retrieved_chunk": " if adj.shape[-1] < self.cfg.args.sample_size:\n self.cfg.args.sample_size = int(np.floor(adj.shape[-1] / 100.0) * 100)\n lbl_1 = torch.ones(self.cfg.args.batch_size, self.cfg.args.sample_size * 2)\n ...
current_epoch % args.update_interval == 0:
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": "neural_algorithms = ['daegc', 'dgi', 'dmon', 'grace', 'mvgrl', 'selfgnn', 'sublime', 'bgrl', 'vgaer', 'cagc', 'igo']\ndef load_model_config(override_model: str = None, override_cfg: DictConfig = None) -> DictConfig:\n \"\"\"\n loads ...
import ugle import ugle.utils as utils from ugle.logger import log from ugle.trainer import MyLibrarySniffingClass from omegaconf import OmegaConf, DictConfig, open_dict import argparse import psutil import time from os.path import isfile import pickle def neural_run(override_model: str = None, overrid...
if override_dataset: cfg.dataset = override_dataset if cfg.trainer.load_existing_test and 'default' not in override_model: # try load the pickle file from previous study hpo_path = f"{cfg.trainer.load_hps_path}{cfg.dataset}_{cfg.model}.pkl" if isfile(hpo_path): log...
{ "context_start_lineno": 0, "file": "main.py", "groundtruth_start_lineno": 24, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 25, "task_id": "project_cc_python/2257" }
{ "list": [ { "filename": "ugle/utils.py", "retrieved_chunk": " if override_model:\n config.model = override_model\n config_name = config.model\n model_name = config.model\n # model_path structure edit if testing\n if config_name.__contains__('_'):\n model_name, name_ext =...
load_model_config(override_model=override_model, override_cfg=override_cfg)
{ "list": [ { "filename": "ugle/models/grace.py", "retrieved_chunk": " x[:, drop_mask] = 0\n return x\nclass grace_trainer(ugleTrainer):\n def preprocess_data(self, features, adjacency):\n adj_label = sp.coo_matrix(adjacency)\n adj_label = adj_label.todok()\n outwards = [...
# https://github.com/wangtong627/CAGC/ import torch import torch.nn as nn from torch_geometric.nn import GATConv from ugle.trainer import ugleTrainer import numpy as np from sklearn import cluster import scipy.sparse as sp from scipy.sparse.linalg import svds from sklearn.preprocessing import normalize import torch.nn....
self.cfg.hypersaved_args.alpha = self.cfg.args.alpha return data, adj def training_preprocessing(self, args, processed_data): activation = nn.PReLU() encoder = Encoder(args.n_features, args.num_hidden, activation, base_model=GATConv, k=args.num_layers).to...
{ "context_start_lineno": 0, "file": "ugle/models/cagc.py", "groundtruth_start_lineno": 209, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 210, "task_id": "project_cc_python/2285" }
{ "list": [ { "filename": "ugle/models/grace.py", "retrieved_chunk": " return data, adj\n def training_preprocessing(self, args, processed_data):\n activation = ({'relu': F.relu, 'prelu': nn.PReLU()})[args.activation]\n base_model = ({'GCNConv': GCNConv})[args.base_model]\n ...
cfg.args.alpha = max(0.4 - (self.cfg.args.n_clusters - 1) / 10 * 0.1, 0.1)
{ "list": [ { "filename": "ugle/helper.py", "retrieved_chunk": " return ranking_object\ndef create_result_bar_chart(dataset_name, algorithms, folder, default_algos, default_folder, ax=None):\n \"\"\"\n displays the results in matplotlib with dashed borders for original comparison on single da...
import os from omegaconf import OmegaConf, DictConfig import numpy as np from karateclub.dataset import GraphReader import networkx as nx import zipfile import gdown from pathlib import Path import shutil import torch import copy import random import scipy.sparse as sp import plotly.graph_objects as go from typing impo...
download_link_path = ugle_path + '/data/download_links.yaml' download_links = OmegaConf.load(download_link_path) url = download_links[dataset_name] dataset_path = ugle_path + f'/data/{dataset_name}' if not os.path.exists(dataset_path): os.mkdir(dataset_path) dataset_zip_path = dataset_...
{ "context_start_lineno": 0, "file": "ugle/datasets.py", "groundtruth_start_lineno": 50, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 51, "task_id": "project_cc_python/2267" }
{ "list": [ { "filename": "main.py", "retrieved_chunk": " # load model config\n cfg = utils.load_model_config(override_model=override_model, override_cfg=override_cfg)\n if override_dataset:\n cfg.dataset = override_dataset\n if cfg.trainer.load_existing_test and 'default' not in ov...
info(f'downloading {dataset_name}')
{ "list": [ { "filename": "main.py", "retrieved_chunk": " help='load best parameters available')\n parsed = parser.parse_args()\n study_cfg = OmegaConf.create({\"args\": {\"random_seed\": int(parsed.seed)},\n \"trainer\": {\"gpu\": int(pars...
from main import neural_run from omegaconf import OmegaConf, DictConfig import ugle import argparse from ugle.logger import log import pickle from os.path import exists from os import makedirs from copy import deepcopy def run_study(study_override_cfg: DictConfig, algorithm: str, dataset: str, seeds: list): """ ...
# test results stores the results of one algorithm run if ugle.utils.is_neural(algorithm): results = neural_run(override_model=algorithm, override_dataset=dataset, override_cfg=study_cfg) # save study output ...
{ "context_start_lineno": 0, "file": "model_evaluations.py", "groundtruth_start_lineno": 30, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 31, "task_id": "project_cc_python/2264" }
{ "list": [ { "filename": "main.py", "retrieved_chunk": " help='load best parameters available')\n parsed = parser.parse_args()\n study_cfg = OmegaConf.create({\"args\": {\"random_seed\": int(parsed.seed)},\n \"trainer\": {\"gpu\": int(pars...
info(f'Study -- {algorithm}:{dataset}:Seed({seed})')
{ "list": [ { "filename": "ugle/models/cagc.py", "retrieved_chunk": " decoder = Decoder(args.num_hidden, args.n_features, activation,\n base_model=GATConv, k=args.num_layers).to(self.device)\n self.model = Model(encoder, decoder, args.n_nodes, self.device).to(sel...
# https://github.com/kavehhassani/mvgrl import torch import torch.nn as nn import ugle import scipy.sparse as sp import numpy as np from fast_pytorch_kmeans import KMeans from sklearn.preprocessing import MinMaxScaler from ugle.trainer import ugleTrainer from ugle.gnn_architecture import GCN, AvgReadout, mvgrl_Discrimi...
self.cfg.args.sample_size = int(np.floor(adj.shape[-1] / 100.0) * 100) lbl_1 = torch.ones(self.cfg.args.batch_size, self.cfg.args.sample_size * 2) lbl_2 = torch.zeros(self.cfg.args.batch_size, self.cfg.args.sample_size * 2) lbl = torch.cat((lbl_1, lbl_2), 1).to(self.device) ...
{ "context_start_lineno": 0, "file": "ugle/models/mvgrl.py", "groundtruth_start_lineno": 84, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 85, "task_id": "project_cc_python/2299" }
{ "list": [ { "filename": "ugle/models/cagc.py", "retrieved_chunk": " loss_knbrs = knbrsloss(H, 10, args.n_nodes, args.tau_knbrs, self.device)\n rec_loss = torch.sum(torch.pow(data - X_, 2))\n loss_instance = instanceloss(H, CH, args.tau)\n loss_coef = torch.sum(torch.pow(C...
cfg.args.sample_size:
{ "list": [ { "filename": "ugle/models/dgi.py", "retrieved_chunk": " h_2 = self.gcn(seq2, adj, sparse=True)\n ret = self.disc(c, h_1, h_2, samp_bias1, samp_bias2)\n return ret\n # Detach the return variables\n def embed(self, seq, adj, msk):\n h_1 = self.gcn(seq, adj,...
# https://github.com/kavehhassani/mvgrl import torch import torch.nn as nn import ugle import scipy.sparse as sp import numpy as np from fast_pytorch_kmeans import KMeans from sklearn.preprocessing import MinMaxScaler from ugle.trainer import ugleTrainer from ugle.gnn_architecture import GCN, AvgReadout, mvgrl_Discrimi...
avg_degree = np.sum(adjacency) / adjacency.shape[0] epsilon = epsilons[np.argmin([abs(avg_degree - np.argwhere(diff_adj >= e).shape[0] / diff_adj.shape[0]) for e in epsilons])] diff_adj[diff_adj < epsilon] = 0.0 scaler = MinMaxScaler() scal...
{ "context_start_lineno": 0, "file": "ugle/models/mvgrl.py", "groundtruth_start_lineno": 52, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 53, "task_id": "project_cc_python/2297" }
{ "list": [ { "filename": "ugle/models/dgi.py", "retrieved_chunk": " adjacency = adjacency + sp.eye(adjacency.shape[0])\n adjacency = ugle.process.normalize_adj(adjacency)\n adj = ugle.process.sparse_mx_to_torch_sparse_tensor(adjacency)\n features = ugle.process.preprocess_...
process.compute_ppr(adjacency)
{ "list": [ { "filename": "autocontrastive_gen/modeling/auto_model.py", "retrieved_chunk": " @staticmethod\n def from_pretrained(model_name_or_path, multi_exit_config: MultiExitConfiguration, **extra_kwargs):\n # Determine the appropriate multi-head model class according to the standard m...
# # Copyright (c) 2023 IBM Corp. # 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 writi...
return model def get_tokenizer(model_name, max_seq_length=512): tokenizer_params = {'pad_token': '<|endoftext|>'} if 'gpt' in model_name else {} tokenizer = AutoTokenizer.from_pretrained(model_name, model_max_length=max_seq_length, **tokenizer_params) return tokenizer
{ "context_start_lineno": 0, "file": "autocontrastive_gen/utils.py", "groundtruth_start_lineno": 29, "repository": "IBM-auto-contrastive-generation-4874a25", "right_context_start_lineno": 30, "task_id": "project_cc_python/2301" }
{ "list": [ { "filename": "autocontrastive_gen/modeling/auto_model.py", "retrieved_chunk": " else:\n raise Exception(f'Model {model_name_or_path} of type {type(model_config)} is not supported')\n model_config.output_hidden_states = True\n if multi_exit_config.lm_head_la...
from_pretrained(model_name_or_path, multi_exit_config=multi_exit_config).to(device)
{ "list": [ { "filename": "ugle/models/grace.py", "retrieved_chunk": " x[:, drop_mask] = 0\n return x\nclass grace_trainer(ugleTrainer):\n def preprocess_data(self, features, adjacency):\n adj_label = sp.coo_matrix(adjacency)\n adj_label = adj_label.todok()\n outwards = [...
# code insipred from https://github.com/Tiger101010/DAEGC import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.optim import Adam from fast_pytorch_kmeans import KMeans import scipy.sparse as sp import ugle from ugle.logger import log f...
self.model = DAEGC(num_features=args.n_features, hidden_size=args.hidden_size, embedding_size=args.embedding_size, alpha=args.alpha, num_clusters=args.n_clusters).to( self.device) optimizer = Adam(self.model.gat.parameters(), lr=args.pre_lr, weight_decay=args.weight_de...
{ "context_start_lineno": 0, "file": "ugle/models/daegc.py", "groundtruth_start_lineno": 71, "repository": "willleeney-ugle-7cfe1b3", "right_context_start_lineno": 72, "task_id": "project_cc_python/2290" }
{ "list": [ { "filename": "ugle/models/dmon.py", "retrieved_chunk": " self.optimizers = [optimiser]\n return\n def training_epoch_iter(self, args, processed_data):\n graph, graph_normalised, features = processed_data\n loss = self.model(graph, graph_normalised, features)...
debug('creating model')
{ "list": [ { "filename": "gradio_tools/tools/prompt_generator.py", "retrieved_chunk": " \"stable diffusion and other art generation algorithms perform better. The input is a prompt text string \"\n \"and the output is a prompt text string\"\n ),\n src=\"microsoft/P...
from typing import TYPE_CHECKING, List from gradio_client.client import Job from gradio_tools.tools.gradio_tool import GradioTool if TYPE_CHECKING: import gradio as gr class DocQueryDocumentAnsweringTool(GradioTool): def __init__( self, name="DocQuery", description=( "A ...
def postprocess(self, output: str) -> str: return output def _block_input(self, gr) -> List["gr.components.Component"]: return [gr.Image(), gr.Textbox()]
{ "context_start_lineno": 0, "file": "gradio_tools/tools/document_qa.py", "groundtruth_start_lineno": 26, "repository": "freddyaboulton-gradio-tools-f0297df", "right_context_start_lineno": 27, "task_id": "project_cc_python/2368" }
{ "list": [ { "filename": "gradio_tools/tools/sam_with_clip.py", "retrieved_chunk": " image,\n query,\n predicted_iou_threshold,\n stability_score_threshold,\n clip_threshold,\n ) = query.split(\"|\")\n except...
client.submit(img.strip(), question.strip(), api_name="/predict")
{ "list": [ { "filename": "gradio_tools/tools/image_to_music.py", "retrieved_chunk": " \"A tool for creating music from images. Use this tool to create a musical \"\n \"track from an image. Input will be a path to an image file. \"\n \"The output will be an audio file ...
from typing import TYPE_CHECKING, List from gradio_client.client import Job from gradio_tools.tools.gradio_tool import GradioTool if TYPE_CHECKING: import gradio as gr class TextToVideoTool(GradioTool): def __init__( self, name="TextToVideo", description=( "A tool for cr...
def postprocess(self, output: str) -> str: return output def _block_output(self, gr) -> List["gr.components.Component"]: return [gr.Video()]
{ "context_start_lineno": 0, "file": "gradio_tools/tools/text_to_video.py", "groundtruth_start_lineno": 27, "repository": "freddyaboulton-gradio-tools-f0297df", "right_context_start_lineno": 28, "task_id": "project_cc_python/2366" }
{ "list": [ { "filename": "gradio_tools/tools/image_to_music.py", "retrieved_chunk": " return self.client.submit(\n query.strip(\"'\"), 15, \"medium\", \"loop\", None, fn_index=0\n )\n def postprocess(self, output: Union[Tuple[Any], Any]) -> str:\n return output[1] ...
client.submit(query, -1, 16, 25, fn_index=1)
{ "list": [ { "filename": "aidapter/api_hf.py", "retrieved_chunk": " #\n out = {}\n out['output'] = output_text\n return out\n# === EMBEDDING ===================================================================================\n# REF: https://huggingface.co/blog/getting-star...
from . import base2 as base import requests import json import os def hf_api_query(payload, model_id, endpoint): api_url = f"https://api-inference.huggingface.co/{endpoint}/{model_id}" headers = {'Authorization': f'Bearer {os.environ["HF_API_TOKEN"]}'} # TODO # data = json.dumps(payload) raw_resp...
brand = 'huggingface' def embed(self, inputs, **kwargs): return self.transform(inputs, **kwargs) def transform_batch(self, inputs, **kwargs): limit = kwargs.get('limit') resp = hf_api_query(inputs, self.name, 'pipeline/feature-extraction') output = [x[:limit] for x in resp...
{ "context_start_lineno": 0, "file": "aidapter/api_hf2.py", "groundtruth_start_lineno": 34, "repository": "mobarski-aidapter-48fd7a8", "right_context_start_lineno": 35, "task_id": "project_cc_python/2428" }
{ "list": [ { "filename": "aidapter/api_hf.py", "retrieved_chunk": " def transform_one(self, text, **kw):\n return self.embed_batch([text], **kw)[0]\n def embed_batch(self, texts, **kw):\n limit = kw.get('limit')\n #\n resp = hf_api_query(texts, self.name, 'pipeline/f...
BaseModelV2):