repo_name stringlengths 7 71 | file_path stringlengths 5 118 | context list | import_statement stringlengths 45 12.5k | token_num int64 641 99.4k | cropped_code stringlengths 44 17k | all_code stringlengths 43 754k | next_line stringlengths 2 330 | gold_snippet_index int64 0 68 | created_at stringlengths 25 25 | level stringclasses 9 values |
|---|---|---|---|---|---|---|---|---|---|---|
generative-skill-chaining/gsc-code | generative_skill_chaining/envs/pybullet/table/objects.py | [
{
"identifier": "body",
"path": "generative_skill_chaining/envs/pybullet/sim/body.py",
"snippet": "class Body:\nclass Link:\n def aabb(self) -> np.ndarray:\n def pose(self) -> math.Pose:\n def set_pose(self, pose: math.Pose) -> None:\n def twist(self) -> np.ndarray:\n def dof(self) -> int... | import dataclasses
import itertools
import random
import numpy as np
import pybullet as p
import spatialdyn as dyn
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union
from ctrlutils import eigen
from generative_skill_chaining.envs.pybullet.sim import body, math, shapes
from generative_skill_chaining.envs.pybullet.table import object_state
from generative_skill_chaining.envs.pybullet.table.utils import load_config
from generative_skill_chaining.envs.pybullet.table.utils import load_config | 2,762 | self.body_id, link_id, 0, 0, physicsClientId=self.physics_id
)
def enable_collisions(self) -> None:
for link_id in range(self.dof):
p.setCollisionFilterGroupMask(
self.body_id, link_id, 1, 0xFF, physicsClientId=self.physics_id
)
@property
def inertia(self) -> dyn.SpatialInertiad:
try:
return self._obj_inertia # type: ignore
except AttributeError:
pass
self._obj_inertia = super().inertia
if self._modified_axes:
self._obj_inertia = self._obj_inertia * self._T_pybullet_to_obj
T_world_to_obj = self.pose().to_eigen().inverse()
for link_id in range(self.dof):
link = body.Link(self.physics_id, self.body_id, link_id)
T_link_to_obj = T_world_to_obj * link.pose().to_eigen()
self._obj_inertia += link.inertia * T_link_to_obj
return self._obj_inertia
def state(self) -> object_state.ObjectState:
pose = self.pose()
aa = eigen.AngleAxisd(eigen.Quaterniond(pose.quat))
self._state.pos = pose.pos
self._state.aa = aa.angle * aa.axis
return self._state
def set_state(self, state: object_state.ObjectState) -> None:
self.set_pose(state.pose())
def reset(self, action_skeleton: List) -> None:
pass
@classmethod
def create(
cls,
physics_id: int,
object_type: Optional[str],
object_kwargs: Dict[str, Any] = {},
object_groups: Dict[str, "ObjectGroup"] = {},
**kwargs,
) -> "Object":
object_class = Null if object_type is None else globals()[object_type]
if issubclass(object_class, Variant):
kwargs["object_groups"] = object_groups
object_kwargs = object_kwargs.copy()
object_kwargs.update(kwargs)
return object_class(physics_id=physics_id, **object_kwargs)
def isinstance(self, class_or_tuple: Union[type, Tuple[type, ...]]) -> bool:
return isinstance(self, class_or_tuple)
def type(self) -> Type["Object"]:
return type(self)
@property
def size(self) -> np.ndarray:
raise NotImplementedError
@property
def bbox(self) -> np.ndarray:
"""Returns the bounding box in the object frame.
If the origin of the object is at its geometric center, this will be
equivalent to `(-0.5 * self.size, 0.5 * self.size)`.
Returns:
An array of shape [2, 3] (min/max, x/y/z).
"""
raise NotImplementedError
def convex_hulls(
self, world_frame: bool = True, project_2d: bool = False
) -> List[np.ndarray]:
"""Computes the object's convex hull.
These hulls will be used for rough collision checking. By default,
the vertices will be the 6 corners of the object's bounding box
(`Object.bbox`).
Args:
world_frame: Whether to transform the vertices in world frame or
leave them in object frame.
project_2d: Whether to return the 2d convex hull.
Returns:
List of arrays of shape [_, 3] or [_, 2], where each array is a
convex hull.
"""
pose = self.pose() if world_frame else None
vertices = compute_bbox_vertices(self.bbox, pose, project_2d)
return [vertices]
def aabb(self) -> np.ndarray:
"""Computes the axis-aligned bounding box from the object pose and size.
This should be more accurate than `super().aabb()`, which gets the aabb
from Pybullet. Pybullet returns an *enlarged* aabb for the object *base*
link, while this returns the exact aabb for the entire object.
Returns:
An array of shape [2, 3] (min/max, x/y/z).
"""
vertices = np.concatenate(self.convex_hulls(world_frame=True), axis=0)
xyz_min = vertices.min(axis=0)
xyz_max = vertices.max(axis=0)
return np.array([xyz_min, xyz_max])
@property
|
OBJECT_HIERARCHY = ["rack", "table", "hook", "box"]
def compute_bbox_vertices(
bbox: np.ndarray, pose: Optional[math.Pose] = None, project_2d: bool = False
) -> np.ndarray:
"""Computes the vertices of the given 3D bounding box.
Args:
bbox: Array of shape [2, 3] (min/max, x/y/z).
pose: Optional pose to transform the vertices.
project_2d: Whether to return 2D vertices or 3D vertices.
Returns:
Array of shape [6, 3] for 3D or [4, 2] for 2D.
"""
xs, ys, zs = bbox.T
if project_2d:
# 2D box with vertices in clockwise order.
vertices = np.array(
[[xs[0], ys[0]], [xs[0], ys[1]], [xs[1], ys[1]], [xs[1], ys[0]]]
)
if pose is not None:
vertices = np.concatenate(
(vertices, np.tile([zs.mean(), 1.0], (vertices.shape[0], 1))), axis=1
)
vertices = (vertices @ pose.to_eigen().matrix.T)[:, :2]
else:
# 3D box.
vertices = np.array(list(itertools.product(xs, ys, zs, [1.0])))
if pose is not None:
vertices = vertices @ pose.to_eigen().matrix.T
vertices = vertices[:, :3]
return vertices
@dataclasses.dataclass
class Object(body.Body):
name: str
is_static: bool = False
def __init__(
self, physics_id: int, body_id: int, name: str, is_static: bool = False
):
super().__init__(physics_id, body_id)
self.name = name
self.is_static = is_static
T_pybullet_to_obj = super().pose().to_eigen()
self._modified_axes = not T_pybullet_to_obj.is_approx(
eigen.Isometry3d.identity()
)
if self._modified_axes:
self._T_pybullet_to_obj = T_pybullet_to_obj
self._T_obj_to_pybullet = T_pybullet_to_obj.inverse()
self._state = object_state.ObjectState()
def pose(self) -> math.Pose:
if not self._modified_axes:
return super().pose()
return math.Pose.from_eigen(super().pose().to_eigen() * self._T_obj_to_pybullet)
def set_pose(self, pose: math.Pose) -> None:
if not self._modified_axes:
return super().set_pose(pose)
return super().set_pose(
math.Pose.from_eigen(pose.to_eigen() * self._T_pybullet_to_obj)
)
def disable_collisions(self) -> None:
for link_id in range(self.dof):
p.setCollisionFilterGroupMask(
self.body_id, link_id, 0, 0, physicsClientId=self.physics_id
)
def enable_collisions(self) -> None:
for link_id in range(self.dof):
p.setCollisionFilterGroupMask(
self.body_id, link_id, 1, 0xFF, physicsClientId=self.physics_id
)
@property
def inertia(self) -> dyn.SpatialInertiad:
try:
return self._obj_inertia # type: ignore
except AttributeError:
pass
self._obj_inertia = super().inertia
if self._modified_axes:
self._obj_inertia = self._obj_inertia * self._T_pybullet_to_obj
T_world_to_obj = self.pose().to_eigen().inverse()
for link_id in range(self.dof):
link = body.Link(self.physics_id, self.body_id, link_id)
T_link_to_obj = T_world_to_obj * link.pose().to_eigen()
self._obj_inertia += link.inertia * T_link_to_obj
return self._obj_inertia
def state(self) -> object_state.ObjectState:
pose = self.pose()
aa = eigen.AngleAxisd(eigen.Quaterniond(pose.quat))
self._state.pos = pose.pos
self._state.aa = aa.angle * aa.axis
return self._state
def set_state(self, state: object_state.ObjectState) -> None:
self.set_pose(state.pose())
def reset(self, action_skeleton: List) -> None:
pass
@classmethod
def create(
cls,
physics_id: int,
object_type: Optional[str],
object_kwargs: Dict[str, Any] = {},
object_groups: Dict[str, "ObjectGroup"] = {},
**kwargs,
) -> "Object":
object_class = Null if object_type is None else globals()[object_type]
if issubclass(object_class, Variant):
kwargs["object_groups"] = object_groups
object_kwargs = object_kwargs.copy()
object_kwargs.update(kwargs)
return object_class(physics_id=physics_id, **object_kwargs)
def isinstance(self, class_or_tuple: Union[type, Tuple[type, ...]]) -> bool:
return isinstance(self, class_or_tuple)
def type(self) -> Type["Object"]:
return type(self)
@property
def size(self) -> np.ndarray:
raise NotImplementedError
@property
def bbox(self) -> np.ndarray:
"""Returns the bounding box in the object frame.
If the origin of the object is at its geometric center, this will be
equivalent to `(-0.5 * self.size, 0.5 * self.size)`.
Returns:
An array of shape [2, 3] (min/max, x/y/z).
"""
raise NotImplementedError
def convex_hulls(
self, world_frame: bool = True, project_2d: bool = False
) -> List[np.ndarray]:
"""Computes the object's convex hull.
These hulls will be used for rough collision checking. By default,
the vertices will be the 6 corners of the object's bounding box
(`Object.bbox`).
Args:
world_frame: Whether to transform the vertices in world frame or
leave them in object frame.
project_2d: Whether to return the 2d convex hull.
Returns:
List of arrays of shape [_, 3] or [_, 2], where each array is a
convex hull.
"""
pose = self.pose() if world_frame else None
vertices = compute_bbox_vertices(self.bbox, pose, project_2d)
return [vertices]
def aabb(self) -> np.ndarray:
"""Computes the axis-aligned bounding box from the object pose and size.
This should be more accurate than `super().aabb()`, which gets the aabb
from Pybullet. Pybullet returns an *enlarged* aabb for the object *base*
link, while this returns the exact aabb for the entire object.
Returns:
An array of shape [2, 3] (min/max, x/y/z).
"""
vertices = np.concatenate(self.convex_hulls(world_frame=True), axis=0)
xyz_min = vertices.min(axis=0)
xyz_max = vertices.max(axis=0)
return np.array([xyz_min, xyz_max])
@property | def shapes(self) -> Sequence[shapes.Shape]: | 2 | 2023-10-16 00:22:40+00:00 | 4k |
ChiyuSONG/dynamics-of-instruction-tuning | evaluate/pred.py | [
{
"identifier": "Assistant",
"path": "inference.py",
"snippet": "class Assistant:\n def __init__(self, model_name_or_path):\n tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path)\n tokenizer.padding_side = \"left\"\n tokenizer.user_token_id, tokenizer.assistant_token_id... | import os
import sys
import torch
import json
import jsonlines
import copy
from pathlib import Path
from argparse import ArgumentParser
from tqdm import tqdm
from inference import Assistant
from train_sft import IGNORE_INDEX, DataCollatorForSupervisedDataset | 1,683 | sys.path.append(".")
def process(example, tokenizer):
processed = []
user = tokenizer.user_token_id
assistant = tokenizer.assistant_token_id
eot = tokenizer.eot_token_id
def tokenize(s):
return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(s.strip()))
for choice in example["choices"]:
input_ids = []
labels = []
messages = copy.deepcopy(example["messages"])[:-1]
for message in messages:
input_ids.append(user if message["role"] == "user" else assistant)
labels.append(IGNORE_INDEX)
content = tokenize(message["content"]) + [eot]
input_ids.extend(content)
labels.extend([IGNORE_INDEX] * len(content))
input_ids.append(assistant)
labels.append(IGNORE_INDEX)
content = tokenize(choice) + [eot]
input_ids.extend(content)
labels.extend(content)
input_ids = input_ids[:2048]
labels = labels[:2048]
assert len(input_ids) == len(labels)
attention_mask = [1] * len(input_ids)
processed.append({'input_ids': torch.LongTensor(input_ids), 'labels': torch.LongTensor(labels),
'attention_mask': torch.LongTensor(attention_mask)})
return processed
def main():
parser = ArgumentParser()
parser.add_argument(
"--model_name_or_path", type=str, default="runs/runs-7b/curated-160/20231017-2215/checkpoint-33"
)
parser.add_argument(
"--eval_data_path", type=str, default="data/curated/valid"
)
args = parser.parse_args()
assistant = Assistant(args.model_name_or_path)
path = Path(args.eval_data_path)
data_files = [os.path.join(path, file.name) for file in path.glob("*.json")]
for data_file in data_files:
dir_name = os.path.dirname(data_file)
file_name = os.path.basename(data_file)
input_path = os.path.join(dir_name, file_name)
base, ckpname = os.path.split(args.model_name_or_path)
base, timestamp = os.path.split(base)
base, model_type = os.path.split(base)
base, model_sz = os.path.split(base)
assert "runs-" in model_sz
model_sz = model_sz.replace("runs-", "")
output_path = os.path.join("evaluate", "pred-data", os.path.split(dir_name)[-1], model_sz, model_type, ckpname, "pred_"+file_name)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
data = []
with open(input_path, 'r', encoding='utf8') as f:
for line in f:
data.append(json.loads(line))
for sample in tqdm(data):
if sample["question_format"] == 0:
test_sample = copy.deepcopy(sample)
test_sample["messages"] = test_sample["messages"][:-1]
responses, scores = assistant.inference([test_sample])
generated_response = responses[0] # string
generated_score = scores[0].tolist() # |V|
assert "generated_response" not in sample
sample["generated_response"] = generated_response
assert "generated_score" not in sample
sample["generated_score"] = generated_score
with jsonlines.open(output_path, mode="a") as f:
f.write(sample)
elif sample["question_format"] == 1:
assert "choices" in sample
assert len(sample["choices"]) == 3
assert "generated_ppl" not in sample
tokenizer = assistant.tokenizer
model = assistant.model
processed_samples = process(sample, tokenizer)
assert len(processed_samples) == 3
| sys.path.append(".")
def process(example, tokenizer):
processed = []
user = tokenizer.user_token_id
assistant = tokenizer.assistant_token_id
eot = tokenizer.eot_token_id
def tokenize(s):
return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(s.strip()))
for choice in example["choices"]:
input_ids = []
labels = []
messages = copy.deepcopy(example["messages"])[:-1]
for message in messages:
input_ids.append(user if message["role"] == "user" else assistant)
labels.append(IGNORE_INDEX)
content = tokenize(message["content"]) + [eot]
input_ids.extend(content)
labels.extend([IGNORE_INDEX] * len(content))
input_ids.append(assistant)
labels.append(IGNORE_INDEX)
content = tokenize(choice) + [eot]
input_ids.extend(content)
labels.extend(content)
input_ids = input_ids[:2048]
labels = labels[:2048]
assert len(input_ids) == len(labels)
attention_mask = [1] * len(input_ids)
processed.append({'input_ids': torch.LongTensor(input_ids), 'labels': torch.LongTensor(labels),
'attention_mask': torch.LongTensor(attention_mask)})
return processed
def main():
parser = ArgumentParser()
parser.add_argument(
"--model_name_or_path", type=str, default="runs/runs-7b/curated-160/20231017-2215/checkpoint-33"
)
parser.add_argument(
"--eval_data_path", type=str, default="data/curated/valid"
)
args = parser.parse_args()
assistant = Assistant(args.model_name_or_path)
path = Path(args.eval_data_path)
data_files = [os.path.join(path, file.name) for file in path.glob("*.json")]
for data_file in data_files:
dir_name = os.path.dirname(data_file)
file_name = os.path.basename(data_file)
input_path = os.path.join(dir_name, file_name)
base, ckpname = os.path.split(args.model_name_or_path)
base, timestamp = os.path.split(base)
base, model_type = os.path.split(base)
base, model_sz = os.path.split(base)
assert "runs-" in model_sz
model_sz = model_sz.replace("runs-", "")
output_path = os.path.join("evaluate", "pred-data", os.path.split(dir_name)[-1], model_sz, model_type, ckpname, "pred_"+file_name)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
data = []
with open(input_path, 'r', encoding='utf8') as f:
for line in f:
data.append(json.loads(line))
for sample in tqdm(data):
if sample["question_format"] == 0:
test_sample = copy.deepcopy(sample)
test_sample["messages"] = test_sample["messages"][:-1]
responses, scores = assistant.inference([test_sample])
generated_response = responses[0] # string
generated_score = scores[0].tolist() # |V|
assert "generated_response" not in sample
sample["generated_response"] = generated_response
assert "generated_score" not in sample
sample["generated_score"] = generated_score
with jsonlines.open(output_path, mode="a") as f:
f.write(sample)
elif sample["question_format"] == 1:
assert "choices" in sample
assert len(sample["choices"]) == 3
assert "generated_ppl" not in sample
tokenizer = assistant.tokenizer
model = assistant.model
processed_samples = process(sample, tokenizer)
assert len(processed_samples) == 3 | data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer, pad_to_multiple_of=8) | 2 | 2023-10-17 07:41:58+00:00 | 4k |
akashgreninja/GreSec | backend/venv/lib/python3.10/site-packages/anyio/_core/_synchronization.py | [
{
"identifier": "cancel_shielded_checkpoint",
"path": "backend/venv/lib/python3.10/site-packages/anyio/lowlevel.py",
"snippet": "async def cancel_shielded_checkpoint() -> None:\n \"\"\"\n Allow the scheduler to switch to another task but without checking for cancellation.\n\n Equivalent to (but... | from collections import deque
from dataclasses import dataclass
from types import TracebackType
from warnings import warn
from ..lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled
from ._compat import DeprecatedAwaitable
from ._eventloop import get_asynclib
from ._exceptions import BusyResourceError, WouldBlock
from ._tasks import CancelScope
from ._testing import TaskInfo, get_current_task | 3,299 |
raise
assert self._owner_task == task
else:
try:
await cancel_shielded_checkpoint()
except BaseException:
self.release()
raise
def acquire_nowait(self) -> None:
"""
Acquire the lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
"""
task = get_current_task()
if self._owner_task == task:
raise RuntimeError("Attempted to acquire an already held Lock")
if self._owner_task is not None:
raise WouldBlock
self._owner_task = task
def release(self) -> DeprecatedAwaitable:
"""Release the lock."""
if self._owner_task != get_current_task():
raise RuntimeError("The current task is not holding this lock")
if self._waiters:
self._owner_task, event = self._waiters.popleft()
event.set()
else:
del self._owner_task
return DeprecatedAwaitable(self.release)
def locked(self) -> bool:
"""Return True if the lock is currently held."""
return self._owner_task is not None
def statistics(self) -> LockStatistics:
"""
Return statistics about the current state of this lock.
.. versionadded:: 3.0
"""
return LockStatistics(self.locked(), self._owner_task, len(self._waiters))
class Condition:
_owner_task: TaskInfo | None = None
def __init__(self, lock: Lock | None = None):
self._lock = lock or Lock()
self._waiters: deque[Event] = deque()
async def __aenter__(self) -> None:
await self.acquire()
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.release()
def _check_acquired(self) -> None:
if self._owner_task != get_current_task():
raise RuntimeError("The current task is not holding the underlying lock")
async def acquire(self) -> None:
"""Acquire the underlying lock."""
await self._lock.acquire()
self._owner_task = get_current_task()
def acquire_nowait(self) -> None:
"""
Acquire the underlying lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
"""
self._lock.acquire_nowait()
self._owner_task = get_current_task()
def release(self) -> DeprecatedAwaitable:
"""Release the underlying lock."""
self._lock.release()
return DeprecatedAwaitable(self.release)
def locked(self) -> bool:
"""Return True if the lock is set."""
return self._lock.locked()
def notify(self, n: int = 1) -> None:
"""Notify exactly n listeners."""
self._check_acquired()
for _ in range(n):
try:
event = self._waiters.popleft()
except IndexError:
break
event.set()
def notify_all(self) -> None:
"""Notify all the listeners."""
self._check_acquired()
for event in self._waiters:
event.set()
self._waiters.clear()
async def wait(self) -> None:
"""Wait for a notification."""
| from __future__ import annotations
@dataclass(frozen=True)
class EventStatistics:
"""
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait`
"""
tasks_waiting: int
@dataclass(frozen=True)
class CapacityLimiterStatistics:
"""
:ivar int borrowed_tokens: number of tokens currently borrowed by tasks
:ivar float total_tokens: total number of available tokens
:ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from this
limiter
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.CapacityLimiter.acquire` or
:meth:`~.CapacityLimiter.acquire_on_behalf_of`
"""
borrowed_tokens: int
total_tokens: float
borrowers: tuple[object, ...]
tasks_waiting: int
@dataclass(frozen=True)
class LockStatistics:
"""
:ivar bool locked: flag indicating if this lock is locked or not
:ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the lock is not
held by any task)
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire`
"""
locked: bool
owner: TaskInfo | None
tasks_waiting: int
@dataclass(frozen=True)
class ConditionStatistics:
"""
:ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait`
:ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying :class:`~.Lock`
"""
tasks_waiting: int
lock_statistics: LockStatistics
@dataclass(frozen=True)
class SemaphoreStatistics:
"""
:ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire`
"""
tasks_waiting: int
class Event:
def __new__(cls) -> Event:
return get_asynclib().Event()
def set(self) -> DeprecatedAwaitable:
"""Set the flag, notifying all listeners."""
raise NotImplementedError
def is_set(self) -> bool:
"""Return ``True`` if the flag is set, ``False`` if not."""
raise NotImplementedError
async def wait(self) -> None:
"""
Wait until the flag has been set.
If the flag has already been set when this method is called, it returns immediately.
"""
raise NotImplementedError
def statistics(self) -> EventStatistics:
"""Return statistics about the current state of this event."""
raise NotImplementedError
class Lock:
_owner_task: TaskInfo | None = None
def __init__(self) -> None:
self._waiters: deque[tuple[TaskInfo, Event]] = deque()
async def __aenter__(self) -> None:
await self.acquire()
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.release()
async def acquire(self) -> None:
"""Acquire the lock."""
await checkpoint_if_cancelled()
try:
self.acquire_nowait()
except WouldBlock:
task = get_current_task()
event = Event()
token = task, event
self._waiters.append(token)
try:
await event.wait()
except BaseException:
if not event.is_set():
self._waiters.remove(token)
elif self._owner_task == task:
self.release()
raise
assert self._owner_task == task
else:
try:
await cancel_shielded_checkpoint()
except BaseException:
self.release()
raise
def acquire_nowait(self) -> None:
"""
Acquire the lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
"""
task = get_current_task()
if self._owner_task == task:
raise RuntimeError("Attempted to acquire an already held Lock")
if self._owner_task is not None:
raise WouldBlock
self._owner_task = task
def release(self) -> DeprecatedAwaitable:
"""Release the lock."""
if self._owner_task != get_current_task():
raise RuntimeError("The current task is not holding this lock")
if self._waiters:
self._owner_task, event = self._waiters.popleft()
event.set()
else:
del self._owner_task
return DeprecatedAwaitable(self.release)
def locked(self) -> bool:
"""Return True if the lock is currently held."""
return self._owner_task is not None
def statistics(self) -> LockStatistics:
"""
Return statistics about the current state of this lock.
.. versionadded:: 3.0
"""
return LockStatistics(self.locked(), self._owner_task, len(self._waiters))
class Condition:
_owner_task: TaskInfo | None = None
def __init__(self, lock: Lock | None = None):
self._lock = lock or Lock()
self._waiters: deque[Event] = deque()
async def __aenter__(self) -> None:
await self.acquire()
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.release()
def _check_acquired(self) -> None:
if self._owner_task != get_current_task():
raise RuntimeError("The current task is not holding the underlying lock")
async def acquire(self) -> None:
"""Acquire the underlying lock."""
await self._lock.acquire()
self._owner_task = get_current_task()
def acquire_nowait(self) -> None:
"""
Acquire the underlying lock, without blocking.
:raises ~anyio.WouldBlock: if the operation would block
"""
self._lock.acquire_nowait()
self._owner_task = get_current_task()
def release(self) -> DeprecatedAwaitable:
"""Release the underlying lock."""
self._lock.release()
return DeprecatedAwaitable(self.release)
def locked(self) -> bool:
"""Return True if the lock is set."""
return self._lock.locked()
def notify(self, n: int = 1) -> None:
"""Notify exactly n listeners."""
self._check_acquired()
for _ in range(n):
try:
event = self._waiters.popleft()
except IndexError:
break
event.set()
def notify_all(self) -> None:
"""Notify all the listeners."""
self._check_acquired()
for event in self._waiters:
event.set()
self._waiters.clear()
async def wait(self) -> None:
"""Wait for a notification.""" | await checkpoint() | 1 | 2023-10-23 18:09:28+00:00 | 4k |
marmotlab/Context_Aware_Navigation | runner.py | [
{
"identifier": "PolicyNet",
"path": "model.py",
"snippet": "class PolicyNet(nn.Module):\r\n def __init__(self, input_dim, embedding_dim):\r\n super(PolicyNet, self).__init__()\r\n self.initial_embedding = nn.Linear(input_dim, embedding_dim) # layer for non-end position\r\n self.... | import torch
import ray
from model import PolicyNet, QNet
from worker import Worker
from parameter import *
| 3,250 |
class Runner(object):
def __init__(self, meta_agent_id):
self.meta_agent_id = meta_agent_id
self.device = torch.device('cuda') if USE_GPU else torch.device('cpu')
|
class Runner(object):
def __init__(self, meta_agent_id):
self.meta_agent_id = meta_agent_id
self.device = torch.device('cuda') if USE_GPU else torch.device('cpu')
| self.local_network = PolicyNet(INPUT_DIM, EMBEDDING_DIM)
| 0 | 2023-10-17 04:32:42+00:00 | 4k |
adarshxs/TokenTally | main.py | [
{
"identifier": "sidebar",
"path": "sidebar.py",
"snippet": "def sidebar():\n with st.sidebar:\n st.image(\"cutie.png\", use_column_width=True)\n st.title(\"About Token Tally\")\n st.info(\"Select your desired base model, parameters, and configuration to get an estimate of the re... | from sidebar import sidebar
from overview import display_overview
from tools.llm_cost_calculator import display_llm_cost_tool
from tools.transformer_memory_calculator import display_transformer_memory_tool
from tools.llm_recomender import display_llm_recomender_tool | 3,256 |
def main():
selected_product = sidebar()
if selected_product == "Overview":
display_overview()
elif selected_product == "LLM Cost Tool":
display_llm_cost_tool()
elif selected_product == "Transformer Memory Tool":
display_transformer_memory_tool()
elif selected_product == "LLM Model Recommendation":
|
def main():
selected_product = sidebar()
if selected_product == "Overview":
display_overview()
elif selected_product == "LLM Cost Tool":
display_llm_cost_tool()
elif selected_product == "Transformer Memory Tool":
display_transformer_memory_tool()
elif selected_product == "LLM Model Recommendation": | display_llm_recomender_tool() | 4 | 2023-10-18 06:16:47+00:00 | 4k |
WestlakeIntelligentRobotics/ConsensusLLM-code | modules/experiment/scalar_debate.py | [
{
"identifier": "Template",
"path": "modules/experiment/template.py",
"snippet": "class Template(ABC):\n \"\"\"\n A template class for designing and running experiments with multiple agents\n and rounds.\n\n This abstract class defines a template for designing experiments where \n multipl... | import numpy as np
from concurrent.futures import ThreadPoolExecutor, as_completed
from .template import Template
from ..llm.agent import Agent, GPT
from ..llm.api_key import api_keys
from ..llm.role import names
from ..prompt.scenario import agent_role, game_description, round_description
from ..prompt.form import agent_output_form
from ..prompt.personality import stubborn, suggestible
from ..visual.gen_html import gen_html
from ..visual.plot import plot_result | 2,926 | """
MIT License
Copyright (c) [2023] [Intelligent Unmanned Systems Laboratory at
Westlake University]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE, OR OTHER DEALINGS IN
THE SOFTWARE.
"""
class ScalarDebate(Template):
"""
A class representing a simulation of scalar debate between multiple agents.
This class extends the Template class and provides functionality to set up
and run a simulation where multiple agents engage in debates, taking into
account their positions, personalities, and knowledge connectivity.
Args:
args: Command-line arguments and configuration.
connectivity_matrix: Matrix defining agent knowledge connectivity.
Raises:
ValueError: If arguments are invalid or insufficient.
"""
def __init__(self, args, connectivity_matrix):
super().__init__(args)
self._n_agents = args.agents
| """
MIT License
Copyright (c) [2023] [Intelligent Unmanned Systems Laboratory at
Westlake University]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE, OR OTHER DEALINGS IN
THE SOFTWARE.
"""
class ScalarDebate(Template):
"""
A class representing a simulation of scalar debate between multiple agents.
This class extends the Template class and provides functionality to set up
and run a simulation where multiple agents engage in debates, taking into
account their positions, personalities, and knowledge connectivity.
Args:
args: Command-line arguments and configuration.
connectivity_matrix: Matrix defining agent knowledge connectivity.
Raises:
ValueError: If arguments are invalid or insufficient.
"""
def __init__(self, args, connectivity_matrix):
super().__init__(args)
self._n_agents = args.agents | self._init_input = game_description + "\n\n" + agent_output_form | 4 | 2023-10-20 07:58:07+00:00 | 4k |
LzVv123456/Contrastive-Prototypical-Prompt | train.py | [
{
"identifier": "ProtoDataset",
"path": "datasets/proto.py",
"snippet": "class ProtoDataset(Dataset):\n def __init__(self, args, prototypes, prototypes_var, classes):\n self.args = args\n self.prototypes = prototypes\n self.prototypes_var = prototypes_var\n self.classes = ... | import torch
import utils
import copy
import losses
import prototype as prot
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, RandomSampler
from tqdm import tqdm
from datasets import ProtoDataset
from prompt import ProTLearner, PromptHead | 2,648 |
class Trainer(object):
def __init__(self, args, vit_model, train_dataset, gen_proto_dataset):
super().__init__()
self.args = args
self.vit_model = vit_model
self.dataset = train_dataset
self.gen_proto_dataset = gen_proto_dataset
self.proto = []
self.proto_var = []
self.mc_proto = []
self.mc_proto_var = []
self.prototype_prompts = []
self.prompter = None
self.head = None
self.data_loader = None
def get_optimizer(self, optm, trainable_parameter):
if optm == "adamw":
optimizer = torch.optim.AdamW(trainable_parameter) # to use with ViTs
elif optm == "sgd":
optimizer = torch.optim.SGD(trainable_parameter, lr=0, momentum=0.9) # lr and wd is set by scheduler
elif optm == "adam":
optimizer = torch.optim.Adam(trainable_parameter) # to use with ViTs
else:
raise NotImplementedError
return optimizer
def init_loss_func(self, classes_up2now):
if self.args.loss == 'protocon':
if self.args.use_mc_proto:
self.loss_function = losses.ProtoConLoss(self.args, self.mc_proto, classes_up2now, self.proto_dataloader)
else:
self.loss_function = losses.ProtoConLoss(self.args, self.proto, classes_up2now, self.proto_dataloader)
elif self.args.loss == 'supcon':
self.loss_function = losses.SupConLoss(self.args)
elif self.args.loss == 'ce':
self.loss_function = nn.CrossEntropyLoss()
else:
raise NotImplementedError
def get_loss(self, output, mlp_output, target, cur_classes, ):
if self.args.loss == 'ce':
if self.args.cls_dim == self.args.task_size: # relabel
new_target = torch.zeros(target.size())
for idx, label in enumerate(cur_classes):
new_target[target == label] = idx
target = new_target.cuda().long()
loss = self.loss_function(output, target)
else:
if self.args.loss == 'supcon':
mlp_output = mlp_output.unsqueeze(dim=1)
loss = self.loss_function(mlp_output, target)
return loss
def train_discriminate(self):
|
class Trainer(object):
def __init__(self, args, vit_model, train_dataset, gen_proto_dataset):
super().__init__()
self.args = args
self.vit_model = vit_model
self.dataset = train_dataset
self.gen_proto_dataset = gen_proto_dataset
self.proto = []
self.proto_var = []
self.mc_proto = []
self.mc_proto_var = []
self.prototype_prompts = []
self.prompter = None
self.head = None
self.data_loader = None
def get_optimizer(self, optm, trainable_parameter):
if optm == "adamw":
optimizer = torch.optim.AdamW(trainable_parameter) # to use with ViTs
elif optm == "sgd":
optimizer = torch.optim.SGD(trainable_parameter, lr=0, momentum=0.9) # lr and wd is set by scheduler
elif optm == "adam":
optimizer = torch.optim.Adam(trainable_parameter) # to use with ViTs
else:
raise NotImplementedError
return optimizer
def init_loss_func(self, classes_up2now):
if self.args.loss == 'protocon':
if self.args.use_mc_proto:
self.loss_function = losses.ProtoConLoss(self.args, self.mc_proto, classes_up2now, self.proto_dataloader)
else:
self.loss_function = losses.ProtoConLoss(self.args, self.proto, classes_up2now, self.proto_dataloader)
elif self.args.loss == 'supcon':
self.loss_function = losses.SupConLoss(self.args)
elif self.args.loss == 'ce':
self.loss_function = nn.CrossEntropyLoss()
else:
raise NotImplementedError
def get_loss(self, output, mlp_output, target, cur_classes, ):
if self.args.loss == 'ce':
if self.args.cls_dim == self.args.task_size: # relabel
new_target = torch.zeros(target.size())
for idx, label in enumerate(cur_classes):
new_target[target == label] = idx
target = new_target.cuda().long()
loss = self.loss_function(output, target)
else:
if self.args.loss == 'supcon':
mlp_output = mlp_output.unsqueeze(dim=1)
loss = self.loss_function(mlp_output, target)
return loss
def train_discriminate(self): | self.prompter = ProTLearner(self.args, self.vit_model) | 1 | 2023-10-16 21:28:42+00:00 | 4k |
inngest/inngest-py | inngest/_internal/middleware_lib/log.py | [
{
"identifier": "client_lib",
"path": "inngest/_internal/client_lib.py",
"snippet": "_DEV_SERVER_EVENT_KEY = \"NO_EVENT_KEY_SET\"\nclass Inngest:\n def api_origin(self) -> str:\n def event_api_origin(self) -> str:\n def event_key(self) -> str | None:\n def signing_key(self) -> str | None:\n ... | from inngest._internal import client_lib, function, types
from .middleware import MiddlewareSync | 1,907 | from __future__ import annotations
class LoggerProxy:
_proxied_methods = (
"critical",
"debug",
"error",
"exception",
"fatal",
"info",
"log",
"warn",
"warning",
)
def __init__(self, logger: types.Logger) -> None:
self._is_enabled = False
self.logger = logger
def __getattr__(self, name: str) -> object:
if name in self._proxied_methods and not self._is_enabled:
# Return noop
return lambda *args, **kwargs: None
return getattr(self.logger, name)
def enable(self) -> None:
self._is_enabled = True
class LoggerMiddleware(MiddlewareSync):
def __init__(self, client: client_lib.Inngest) -> None:
super().__init__(client)
self.logger = LoggerProxy(client.logger)
def before_execution(self) -> None:
self.logger.enable()
def transform_input(
self,
| from __future__ import annotations
class LoggerProxy:
_proxied_methods = (
"critical",
"debug",
"error",
"exception",
"fatal",
"info",
"log",
"warn",
"warning",
)
def __init__(self, logger: types.Logger) -> None:
self._is_enabled = False
self.logger = logger
def __getattr__(self, name: str) -> object:
if name in self._proxied_methods and not self._is_enabled:
# Return noop
return lambda *args, **kwargs: None
return getattr(self.logger, name)
def enable(self) -> None:
self._is_enabled = True
class LoggerMiddleware(MiddlewareSync):
def __init__(self, client: client_lib.Inngest) -> None:
super().__init__(client)
self.logger = LoggerProxy(client.logger)
def before_execution(self) -> None:
self.logger.enable()
def transform_input(
self, | ctx: function.Context, | 1 | 2023-10-19 01:02:30+00:00 | 4k |
f0uriest/quadax | quadax/romberg.py | [
{
"identifier": "QuadratureInfo",
"path": "quadax/utils.py",
"snippet": "class QuadratureInfo(NamedTuple):\n \"\"\"Information about quadrature.\n\n Parameters\n ----------\n err : float\n Estimate of the error in the quadrature result.\n neval : int\n Number of evaluations ... | import jax
import jax.numpy as jnp
from .utils import (
QuadratureInfo,
bounded_while_loop,
errorif,
map_interval,
tanhsinh_transform,
wrap_func,
) | 2,501 | """Romberg integration aka adaptive trapezoid with Richardson extrapolation."""
def romberg(
fun,
interval,
args=(),
full_output=False,
epsabs=1.4e-8,
epsrel=1.4e-8,
divmax=20,
norm=jnp.inf,
):
"""Romberg integration of a callable function or method.
Returns the integral of `fun` (a function of one variable) over `interval`.
Good for non-smooth or piecewise smooth integrands.
Not recommended for infinite intervals, or functions with singularities.
Parameters
----------
fun : callable
Function to integrate, should have a signature of the form
``fun(x, *args)`` -> float, Array. Should be JAX transformable.
interval : array-like
Lower and upper limits of integration. Use np.inf to denote infinite intervals.
args : tuple
additional arguments passed to fun
full_output : bool, optional
If True, return the full state of the integrator. See below for more
information.
epsabs, epsrel : float
Absolute and relative tolerances. If I1 and I2 are two
successive approximations to the integral, algorithm terminates
when abs(I1-I2) < max(epsabs, epsrel*|I2|)
divmax : int, optional
Maximum order of extrapolation. Default is 20.
Total number of function evaluations will be at
most 2**divmax + 1
norm : int, callable
Norm to use for measuring error for vector valued integrands. No effect if the
integrand is scalar valued. If an int, uses p-norm of the given order, otherwise
should be callable.
Returns
-------
y : float, Array
Approximation to the integral
info : QuadratureInfo
Named tuple with the following fields:
* err : (float) Estimate of the error in the approximation.
* neval : (int) Total number of function evaluations.
* status : (int) Flag indicating reason for termination. status of 0 means
normal termination, any other value indicates a possible error. A human
readable message can be obtained by ``print(quadax.STATUS[status])``
* info : (dict or None) Other information returned by the algorithm.
Only present if ``full_output`` is True. Contains the following:
* table : (ndarray, size(dixmax+1, divmax+1, ...)) Estimate of the integral
from each level of discretization and each step of extrapolation.
Notes
-----
Due to limitations on dynamically sized arrays in JAX, this algorithm is fully
sequential and does not vectorize integrand evaluations, so may not be the most
efficient on GPU/TPU.
Also, it is currently only forward mode differentiable.
"""
errorif(
len(interval) != 2,
NotImplementedError,
"Romberg integration with breakpoints not supported",
)
_norm = norm if callable(norm) else lambda x: jnp.linalg.norm(x.flatten(), ord=norm)
# map a, b -> [-1, 1]
fun, interval = map_interval(fun, interval)
| """Romberg integration aka adaptive trapezoid with Richardson extrapolation."""
def romberg(
fun,
interval,
args=(),
full_output=False,
epsabs=1.4e-8,
epsrel=1.4e-8,
divmax=20,
norm=jnp.inf,
):
"""Romberg integration of a callable function or method.
Returns the integral of `fun` (a function of one variable) over `interval`.
Good for non-smooth or piecewise smooth integrands.
Not recommended for infinite intervals, or functions with singularities.
Parameters
----------
fun : callable
Function to integrate, should have a signature of the form
``fun(x, *args)`` -> float, Array. Should be JAX transformable.
interval : array-like
Lower and upper limits of integration. Use np.inf to denote infinite intervals.
args : tuple
additional arguments passed to fun
full_output : bool, optional
If True, return the full state of the integrator. See below for more
information.
epsabs, epsrel : float
Absolute and relative tolerances. If I1 and I2 are two
successive approximations to the integral, algorithm terminates
when abs(I1-I2) < max(epsabs, epsrel*|I2|)
divmax : int, optional
Maximum order of extrapolation. Default is 20.
Total number of function evaluations will be at
most 2**divmax + 1
norm : int, callable
Norm to use for measuring error for vector valued integrands. No effect if the
integrand is scalar valued. If an int, uses p-norm of the given order, otherwise
should be callable.
Returns
-------
y : float, Array
Approximation to the integral
info : QuadratureInfo
Named tuple with the following fields:
* err : (float) Estimate of the error in the approximation.
* neval : (int) Total number of function evaluations.
* status : (int) Flag indicating reason for termination. status of 0 means
normal termination, any other value indicates a possible error. A human
readable message can be obtained by ``print(quadax.STATUS[status])``
* info : (dict or None) Other information returned by the algorithm.
Only present if ``full_output`` is True. Contains the following:
* table : (ndarray, size(dixmax+1, divmax+1, ...)) Estimate of the integral
from each level of discretization and each step of extrapolation.
Notes
-----
Due to limitations on dynamically sized arrays in JAX, this algorithm is fully
sequential and does not vectorize integrand evaluations, so may not be the most
efficient on GPU/TPU.
Also, it is currently only forward mode differentiable.
"""
errorif(
len(interval) != 2,
NotImplementedError,
"Romberg integration with breakpoints not supported",
)
_norm = norm if callable(norm) else lambda x: jnp.linalg.norm(x.flatten(), ord=norm)
# map a, b -> [-1, 1]
fun, interval = map_interval(fun, interval) | vfunc = wrap_func(fun, args) | 5 | 2023-10-24 04:44:34+00:00 | 4k |
yixinliu233/SIGNET | main.py | [
{
"identifier": "GIN",
"path": "models.py",
"snippet": "class GIN(torch.nn.Module):\n def __init__(self, num_features, dim, num_gc_layers, pooling, readout):\n super(GIN, self).__init__()\n\n self.num_gc_layers = num_gc_layers\n self.pooling = pooling\n self.readout = read... | import torch
import numpy as np
import torch.nn as nn
import random
import warnings
from sklearn.metrics import roc_auc_score
from models import GIN, Explainer_GIN, HyperGNN, Explainer_MLP
from arguments import arg_parse
from get_data_loaders import get_data_loaders
from get_data_loaders_tuad import get_ad_split_TU, get_data_loaders_TU | 3,513 |
warnings.filterwarnings("ignore")
explainable_datasets = ['mutag', 'mnist0', 'mnist1', 'bm_mn', 'bm_ms', 'bm_mt']
class SIGNET(nn.Module):
def __init__(self, input_dim, input_dim_edge, args, device):
super(SIGNET, self).__init__()
self.device = device
self.embedding_dim = args.hidden_dim
if args.readout == 'concat':
self.embedding_dim *= args.encoder_layers
if args.explainer_model == 'mlp':
|
warnings.filterwarnings("ignore")
explainable_datasets = ['mutag', 'mnist0', 'mnist1', 'bm_mn', 'bm_ms', 'bm_mt']
class SIGNET(nn.Module):
def __init__(self, input_dim, input_dim_edge, args, device):
super(SIGNET, self).__init__()
self.device = device
self.embedding_dim = args.hidden_dim
if args.readout == 'concat':
self.embedding_dim *= args.encoder_layers
if args.explainer_model == 'mlp': | self.explainer = Explainer_MLP(input_dim, args.explainer_hidden_dim, args.explainer_layers) | 3 | 2023-10-18 04:23:35+00:00 | 4k |
smonsays/metax | metax/data/synthetic.py | [
{
"identifier": "DatasetGenerator",
"path": "metax/data/dataset/base.py",
"snippet": "class DatasetGenerator(abc.ABC):\n \"\"\"\n Abstract base class for generated datasets.\n\n Attributes:\n input_shape (tuple): The shape of the input data.\n output_dim (int): The dimensionality ... | import logging
import chex
import jax
from typing import List, Optional
from metax.data.dataset.base import DatasetGenerator
from .base import Dataloader, MetaDataset
from .dataset import family, sinusoid
from .utils import create_metadataset | 1,901 | """
Copyright (c) Simon Schug
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class SyntheticMetaDataloader(Dataloader):
def __init__(
self,
data_generator: DatasetGenerator,
num_tasks: int,
shots_train: int,
shots_test: int,
meta_batch_size: int,
mode: str,
train_test_split: bool,
rng: chex.PRNGKey,
):
super().__init__(
input_shape=data_generator.input_shape,
output_dim=data_generator.output_dim
)
self.data_generator = data_generator
self.num_tasks = num_tasks
self.shots_train = shots_train
self.shots_test = shots_test
self.meta_batch_size = meta_batch_size
self.mode = mode
self.train_test_split = train_test_split
self.fixed_rng = rng
assert train_test_split or mode == "train", "mode must be train if train_test_split is False"
assert num_tasks % meta_batch_size == 0, "num_tasks must be divisible by meta_batch_size"
self.num_steps = num_tasks // meta_batch_size
self.shots = shots_train + shots_test
# Sample data to get placeholder_input
self._sample_input = self.data_generator.sample(
self.fixed_rng, 1, self.shots_train, mode="train"
).x[0]
@property
def sample_input(self):
return self._sample_input
def __len__(self):
return self.num_steps
def __iter__(self):
for rng in jax.random.split(self.fixed_rng, self.num_steps):
dataset = self.data_generator.sample(rng, self.meta_batch_size, self.shots, mode=self.mode)
if self.train_test_split:
# Split into train and test set
yield create_metadataset(dataset, self.shots_train)
else:
# No train_test split means, meta.train == meta.test set
yield MetaDataset(train=dataset, test=dataset)
def create_synthetic_metadataset(
name,
meta_batch_size,
shots_train,
shots_test,
train_test_split,
num_tasks_train,
num_tasks_test,
num_tasks_valid,
num_tasks_ood: Optional[int] = None,
ood_sets_hot: Optional[List[int]] = None,
seed: int = 0,
**kwargs,
):
if name == "family":
data_generator = family.Family()
elif name == "harmonic":
data_generator = family.Harmonic()
elif name == "linear":
data_generator = family.Linear()
elif name == "polynomial":
data_generator = family.Polynomial()
elif name == "sawtooth":
data_generator = family.Sawtooth()
elif name == "sinusoid_family":
data_generator = family.SinusoidFamily()
elif name == "sinusoid":
| """
Copyright (c) Simon Schug
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class SyntheticMetaDataloader(Dataloader):
def __init__(
self,
data_generator: DatasetGenerator,
num_tasks: int,
shots_train: int,
shots_test: int,
meta_batch_size: int,
mode: str,
train_test_split: bool,
rng: chex.PRNGKey,
):
super().__init__(
input_shape=data_generator.input_shape,
output_dim=data_generator.output_dim
)
self.data_generator = data_generator
self.num_tasks = num_tasks
self.shots_train = shots_train
self.shots_test = shots_test
self.meta_batch_size = meta_batch_size
self.mode = mode
self.train_test_split = train_test_split
self.fixed_rng = rng
assert train_test_split or mode == "train", "mode must be train if train_test_split is False"
assert num_tasks % meta_batch_size == 0, "num_tasks must be divisible by meta_batch_size"
self.num_steps = num_tasks // meta_batch_size
self.shots = shots_train + shots_test
# Sample data to get placeholder_input
self._sample_input = self.data_generator.sample(
self.fixed_rng, 1, self.shots_train, mode="train"
).x[0]
@property
def sample_input(self):
return self._sample_input
def __len__(self):
return self.num_steps
def __iter__(self):
for rng in jax.random.split(self.fixed_rng, self.num_steps):
dataset = self.data_generator.sample(rng, self.meta_batch_size, self.shots, mode=self.mode)
if self.train_test_split:
# Split into train and test set
yield create_metadataset(dataset, self.shots_train)
else:
# No train_test split means, meta.train == meta.test set
yield MetaDataset(train=dataset, test=dataset)
def create_synthetic_metadataset(
name,
meta_batch_size,
shots_train,
shots_test,
train_test_split,
num_tasks_train,
num_tasks_test,
num_tasks_valid,
num_tasks_ood: Optional[int] = None,
ood_sets_hot: Optional[List[int]] = None,
seed: int = 0,
**kwargs,
):
if name == "family":
data_generator = family.Family()
elif name == "harmonic":
data_generator = family.Harmonic()
elif name == "linear":
data_generator = family.Linear()
elif name == "polynomial":
data_generator = family.Polynomial()
elif name == "sawtooth":
data_generator = family.Sawtooth()
elif name == "sinusoid_family":
data_generator = family.SinusoidFamily()
elif name == "sinusoid": | data_generator = sinusoid.Sinusoid() | 4 | 2023-10-19 16:36:20+00:00 | 4k |
claws-lab/XLingEval | correctness/correctness_get_gpt_answer.py | [
{
"identifier": "load_HealthQA",
"path": "dataloader/load_data.py",
"snippet": "def load_HealthQA(split: str, language: str = 'English', task: str = \"consistency\"):\n print(f\"Loading HealthQA with split {split} and Language {language} ...\")\n\n if osp.basename(os.getcwd()) == \"XLingHealth_Dat... | import os
import time
import traceback
import sys
import pandas as pd
from os import path as osp
from dataloader.load_data import load_HealthQA, load_MedicationQA, load_LiveQA
from setup import project_setup, openai_setup
from utils_chatgpt import get_response
from const import set_constants
from argparse import ArgumentParser | 2,794 |
llm_answer_list = []
for idx, row in data_df.iterrows():
retry = True
if idx%100 == 0:
print("Index: ", idx)
while retry:
try:
message_list=[{'role': 'system', 'content': f'You are Health GPT and You answer to health and medical related queries in {lang}. Your answers should be in one or more paragraphs without listing points/lists and should be in {lang}.'}]
messages = message_list.copy()
if lang=="English":
prompt = prompt = row['question']
else:
prompt = row['translated_question_'+lang]
messages.append({'role': 'user', 'content': prompt})
llm_response = get_response(open_ai_object_list[model_list_index], messages, constants['GPT_MODEL'], constants['DEPLOYMENT_ID'])
llm_answer_list.append(llm_response)
time.sleep(0.3)
retry = False
model_use_count += 1
if model_use_count%3 == 0:
model_list_index += 1
model_list_index = model_list_index%total_models_num
model_use_count = 0
except Exception as e:
print("Error at index: ", idx)
traceback.print_exc()
model_list_index += 1
model_list_index = model_list_index%total_models_num
model_use_count = 0
print("Error: ", e)
#check if the error contains the substring Request timed out: HTTPSConnectionPool or rate limit
if "Request timed out: HTTPSConnectionPool" in str(e) or "rate limit" in str(e) or "timed out" or "No Response" in str(e):
print("Sleeping for 10 seconds")
time.sleep(10)
continue
else:
if llm_response:
llm_answer_list.append(llm_response)
else:
if "This model's maximum context length is 8192 tokens" in str(e):
llm_answer_list.append("Max Context Length Exceeded")
else:
llm_answer_list.append(str(e))
print("LLM Response: ", llm_response)
retry = False
continue
data_df["llm_answer_"+lang] = llm_answer_list
return data_df
if __name__ == "__main__":
#add an argument to get the dataset path
parser = ArgumentParser()
parser.add_argument("--dataset_path", type=str, required=True)
parser.add_argument("--model", type=str, required=True)
args = parser.parse_args()
dataset_path = args.dataset_path
model = args.model
lang_list = ["English", "Hindi", "Chinese", "Spanish"]
file_name = dataset_path.split(".")[0]
#get the directory path from the dataset path
directory_path = "/".join(dataset_path.split("/")[:-1])
os.chdir(directory_path)
print("Current working directory: {}".format(os.getcwd()))
constants = set_constants(model)
print(constants)
project_setup()
open_ai_object_list = openai_setup()
total_models_num = len(open_ai_object_list)
#if dataset path ends with pkl, then use pandas read_pickle method
if dataset_path.endswith("pkl"):
data_df = pd.read_pickle(dataset_path)
else:
df_li = []
for lang in lang_list:
if "HealthQA" in args.dataset_path:
# Only consider the dev set for HealthQA
df = load_HealthQA(split="dev",
language=lang, task="correctness")
elif "MedicationQA" in args.dataset_path:
df = load_MedicationQA(language=lang, task="correctness")
elif "LiveQA" in args.dataset_path:
| sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
def get_eval(data_df, lang, open_ai_object_list, constants):
print("Lang: ", lang)
model_use_count = 0
model_list_index = 0
llm_answer_list = []
for idx, row in data_df.iterrows():
retry = True
if idx%100 == 0:
print("Index: ", idx)
while retry:
try:
message_list=[{'role': 'system', 'content': f'You are Health GPT and You answer to health and medical related queries in {lang}. Your answers should be in one or more paragraphs without listing points/lists and should be in {lang}.'}]
messages = message_list.copy()
if lang=="English":
prompt = prompt = row['question']
else:
prompt = row['translated_question_'+lang]
messages.append({'role': 'user', 'content': prompt})
llm_response = get_response(open_ai_object_list[model_list_index], messages, constants['GPT_MODEL'], constants['DEPLOYMENT_ID'])
llm_answer_list.append(llm_response)
time.sleep(0.3)
retry = False
model_use_count += 1
if model_use_count%3 == 0:
model_list_index += 1
model_list_index = model_list_index%total_models_num
model_use_count = 0
except Exception as e:
print("Error at index: ", idx)
traceback.print_exc()
model_list_index += 1
model_list_index = model_list_index%total_models_num
model_use_count = 0
print("Error: ", e)
#check if the error contains the substring Request timed out: HTTPSConnectionPool or rate limit
if "Request timed out: HTTPSConnectionPool" in str(e) or "rate limit" in str(e) or "timed out" or "No Response" in str(e):
print("Sleeping for 10 seconds")
time.sleep(10)
continue
else:
if llm_response:
llm_answer_list.append(llm_response)
else:
if "This model's maximum context length is 8192 tokens" in str(e):
llm_answer_list.append("Max Context Length Exceeded")
else:
llm_answer_list.append(str(e))
print("LLM Response: ", llm_response)
retry = False
continue
data_df["llm_answer_"+lang] = llm_answer_list
return data_df
if __name__ == "__main__":
#add an argument to get the dataset path
parser = ArgumentParser()
parser.add_argument("--dataset_path", type=str, required=True)
parser.add_argument("--model", type=str, required=True)
args = parser.parse_args()
dataset_path = args.dataset_path
model = args.model
lang_list = ["English", "Hindi", "Chinese", "Spanish"]
file_name = dataset_path.split(".")[0]
#get the directory path from the dataset path
directory_path = "/".join(dataset_path.split("/")[:-1])
os.chdir(directory_path)
print("Current working directory: {}".format(os.getcwd()))
constants = set_constants(model)
print(constants)
project_setup()
open_ai_object_list = openai_setup()
total_models_num = len(open_ai_object_list)
#if dataset path ends with pkl, then use pandas read_pickle method
if dataset_path.endswith("pkl"):
data_df = pd.read_pickle(dataset_path)
else:
df_li = []
for lang in lang_list:
if "HealthQA" in args.dataset_path:
# Only consider the dev set for HealthQA
df = load_HealthQA(split="dev",
language=lang, task="correctness")
elif "MedicationQA" in args.dataset_path:
df = load_MedicationQA(language=lang, task="correctness")
elif "LiveQA" in args.dataset_path: | df = load_LiveQA(language=lang, task="correctness") | 2 | 2023-10-18 17:35:42+00:00 | 4k |
RF-Tar-Railt/satori-python | src/satori/model.py | [
{
"identifier": "Element",
"path": "src/satori/element.py",
"snippet": "class Element:\n @classmethod\n def from_raw(cls: Type[TE], raw: RawElement) -> TE:\n _fields = {f.name for f in fields(cls)}\n attrs = {k: v for k, v in raw.attrs.items() if k in _fields}\n result = cls(*... | from dataclasses import asdict, dataclass
from datetime import datetime
from enum import IntEnum
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar
from .element import Element, transform
from .parser import parse | 2,337 | data["user"] = User.parse(raw["user"])
if "joined_at" in raw:
data["joined_at"] = datetime.fromtimestamp(int(raw["joined_at"]) / 1000)
return cls(**data)
def dump(self):
res = {}
if self.user:
res["user"] = self.user.dump()
if self.nick or self.name:
res["nick"] = self.nick or self.name
if self.avatar:
res["avatar"] = self.avatar
if self.joined_at:
res["joined_at"] = int(self.joined_at.timestamp() * 1000)
return res
@dataclass
class Role:
id: str
name: Optional[str] = None
@classmethod
def parse(cls, raw: dict):
return cls(**raw)
def dump(self):
res = {"id": self.id}
if self.name:
res["name"] = self.name
return res
class LoginStatus(IntEnum):
OFFLINE = 0
ONLINE = 1
CONNECT = 2
DISCONNECT = 3
RECONNECT = 4
@dataclass
class Login:
status: LoginStatus
user: Optional[User] = None
self_id: Optional[str] = None
platform: Optional[str] = None
@classmethod
def parse(cls, raw: dict):
data = raw.copy()
if "user" in raw:
data["user"] = User(**raw["user"])
data["status"] = LoginStatus(data["status"])
return cls(**data)
def dump(self):
res: Dict[str, Any] = {"status": self.status.value}
if self.user:
res["user"] = self.user.dump()
if self.self_id:
res["self_id"] = self.self_id
if self.platform:
res["platform"] = self.platform
return res
@dataclass
class ArgvInteraction:
name: str
arguments: list
options: Any
def dump(self):
return asdict(self)
@dataclass
class ButtonInteraction:
id: str
def dump(self):
return asdict(self)
class Opcode(IntEnum):
EVENT = 0
PING = 1
PONG = 2
IDENTIFY = 3
READY = 4
@dataclass
class Identify:
token: Optional[str] = None
sequence: Optional[int] = None
@dataclass
class Ready:
logins: List[Login]
@dataclass
class MessageObject:
id: str
content: List[Element]
channel: Optional[Channel] = None
guild: Optional[Guild] = None
member: Optional[Member] = None
user: Optional[User] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
@classmethod
def parse(cls, raw: dict):
data = {
"id": raw["id"],
|
class ChannelType(IntEnum):
TEXT = 0
VOICE = 1
CATEGORY = 2
DIRECT = 3
@dataclass
class Channel:
id: str
type: ChannelType
name: Optional[str] = None
parent_id: Optional[str] = None
@classmethod
def parse(cls, raw: dict):
data = raw.copy()
data["type"] = ChannelType(raw["type"])
return cls(**data)
def dump(self):
res = {"id": self.id, "type": self.type.value}
if self.name:
res["name"] = self.name
if self.parent_id:
res["parent_id"] = self.parent_id
return res
@dataclass
class Guild:
id: str
name: Optional[str] = None
avatar: Optional[str] = None
@classmethod
def parse(cls, raw: dict):
return cls(**raw)
def dump(self):
res = {"id": self.id}
if self.name:
res["name"] = self.name
if self.avatar:
res["avatar"] = self.avatar
return res
@dataclass
class User:
id: str
name: Optional[str] = None
nick: Optional[str] = None
avatar: Optional[str] = None
is_bot: Optional[bool] = None
@classmethod
def parse(cls, raw: dict):
return cls(**raw)
def dump(self):
res: Dict[str, Any] = {"id": self.id}
if self.name:
res["name"] = self.name
if self.nick:
res["nick"] = self.nick
if self.avatar:
res["avatar"] = self.avatar
if self.is_bot:
res["is_bot"] = self.is_bot
return res
@dataclass
class Member:
user: Optional[User] = None
nick: Optional[str] = None
name: Optional[str] = None
avatar: Optional[str] = None
joined_at: Optional[datetime] = None
@classmethod
def parse(cls, raw: dict):
data = raw.copy()
if "user" in raw:
data["user"] = User.parse(raw["user"])
if "joined_at" in raw:
data["joined_at"] = datetime.fromtimestamp(int(raw["joined_at"]) / 1000)
return cls(**data)
def dump(self):
res = {}
if self.user:
res["user"] = self.user.dump()
if self.nick or self.name:
res["nick"] = self.nick or self.name
if self.avatar:
res["avatar"] = self.avatar
if self.joined_at:
res["joined_at"] = int(self.joined_at.timestamp() * 1000)
return res
@dataclass
class Role:
id: str
name: Optional[str] = None
@classmethod
def parse(cls, raw: dict):
return cls(**raw)
def dump(self):
res = {"id": self.id}
if self.name:
res["name"] = self.name
return res
class LoginStatus(IntEnum):
OFFLINE = 0
ONLINE = 1
CONNECT = 2
DISCONNECT = 3
RECONNECT = 4
@dataclass
class Login:
status: LoginStatus
user: Optional[User] = None
self_id: Optional[str] = None
platform: Optional[str] = None
@classmethod
def parse(cls, raw: dict):
data = raw.copy()
if "user" in raw:
data["user"] = User(**raw["user"])
data["status"] = LoginStatus(data["status"])
return cls(**data)
def dump(self):
res: Dict[str, Any] = {"status": self.status.value}
if self.user:
res["user"] = self.user.dump()
if self.self_id:
res["self_id"] = self.self_id
if self.platform:
res["platform"] = self.platform
return res
@dataclass
class ArgvInteraction:
name: str
arguments: list
options: Any
def dump(self):
return asdict(self)
@dataclass
class ButtonInteraction:
id: str
def dump(self):
return asdict(self)
class Opcode(IntEnum):
EVENT = 0
PING = 1
PONG = 2
IDENTIFY = 3
READY = 4
@dataclass
class Identify:
token: Optional[str] = None
sequence: Optional[int] = None
@dataclass
class Ready:
logins: List[Login]
@dataclass
class MessageObject:
id: str
content: List[Element]
channel: Optional[Channel] = None
guild: Optional[Guild] = None
member: Optional[Member] = None
user: Optional[User] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
@classmethod
def parse(cls, raw: dict):
data = {
"id": raw["id"], | "content": transform(parse(raw["content"])), | 1 | 2023-10-18 11:09:34+00:00 | 4k |
zju3dv/nr_in_a_room | tools/check_pose.py | [
{
"identifier": "create_sphere_lookat_poses",
"path": "data_gen/data_geo_utils.py",
"snippet": "def create_sphere_lookat_poses(\n radius: float, n_poses: int, n_circles: float, up_dir=\"y\", phi_begin=20, phi_end=90\n):\n deg2rad = np.pi / 180\n # y up\n phi_list = np.linspace(phi_begin * de... | import numpy as np
import argparse
import sys
import os
import open3d as o3d
import matplotlib.pyplot as plt
from data_gen.data_geo_utils import create_sphere_lookat_poses
from tools.O3dVisualizer import O3dVisualizer
from utils.util import * | 2,689 |
sys.path.append(os.getcwd()) # noqa
# from datasets.geo_utils import observe_angle_distance
# from render_tools.render_utils import *
def spheric_pose(theta, phi, radius, height):
trans_t = lambda t: np.array(
[
[1, 0, 0, 0],
[0, 1, 0, -0.9 * t],
[0, 0, 1, t],
[0, 0, 0, 1],
]
)
rot_phi = lambda phi: np.array(
[
[1, 0, 0, 0],
[0, np.cos(phi), -np.sin(phi), 0],
[0, np.sin(phi), np.cos(phi), 0],
[0, 0, 0, 1],
]
)
rot_theta = lambda th: np.array(
[
[np.cos(th), 0, -np.sin(th), 0],
[0, 1, 0, 0],
[np.sin(th), 0, np.cos(th), 0],
[0, 0, 0, 1],
]
)
c2w = rot_theta(theta) @ rot_phi(phi) @ trans_t(radius)
c2w = np.array([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) @ c2w
c2w[2, 3] += height
return c2w[:3]
def create_spheric_poses(radius, downward_deg, height, n_poses):
"""
Create circular poses around z axis.
Inputs:
radius: the (negative) height and the radius of the circle.
Outputs:
spheric_poses: (n_poses, 3, 4) the poses in the circular path
"""
spheric_poses = []
for th in np.linspace(0, 2 * np.pi, n_poses + 1)[:-1]:
pose = np.eye(4)
pose[:3, :4] = spheric_pose(th, -(downward_deg * np.pi / 180), radius, height)
fix_rot = np.eye(4)
fix_rot[:3, :3] = np.array([1, 0, 0, 0, 0, 1, 0, -1, 0]).reshape(3, 3)
pose = fix_rot @ pose
spheric_poses += [pose] # 36 degree view downwards
return np.stack(spheric_poses, 0)
def draw_poses(visualizer, poses):
camera_centers = []
lines_pt, lines_idx, lines_color = [], [], []
idx = 0
for frame_id, pose in enumerate(poses):
Twc = pose
# for nerf_synthetic, we need some transformation
fix_rot = np.array([1, 0, 0, 0, -1, 0, 0, 0, -1]).reshape(3, 3)
Twc[:3, :3] = Twc[:3, :3] @ fix_rot
center = Twc[:3, 3]
camera_centers.append(center)
# draw axis
# RGB -> right, down, forward
axis_size = 0.1
# for .T, you can follow https://stackoverflow.com/questions/12148351/
axis_pts = (Twc[:3, :3] @ (np.eye(3) * axis_size)).T + center
lines_pt += [center, axis_pts[0, :], axis_pts[1, :], axis_pts[2, :]]
lines_idx += [
[idx * 4 + 0, idx * 4 + 1],
[idx * 4 + 0, idx * 4 + 2],
[idx * 4 + 0, idx * 4 + 3],
]
lines_color += [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
idx += 1
# draw line via cylinder, which we can control the line thickness
visualizer.add_line_set(lines_pt, lines_idx, colors=lines_color, radius=0.003)
# draw line via LineSet
# line_set = o3d.geometry.LineSet(
# points=o3d.utility.Vector3dVector(np.array(lines_pt)),
# lines=o3d.utility.Vector2iVector(np.array(lines_idx)),
# )
# line_set.colors = o3d.utility.Vector3dVector(lines_color)
# visualizer.add_o3d_geometry(line_set)
camera_centers = np.array(camera_centers)
visualizer.add_np_points(
camera_centers,
color=map_to_color(np.arange(0, len(poses)), cmap="plasma"),
size=0.01,
)
if __name__ == "__main__":
# params
parser = argparse.ArgumentParser()
# data paths
parser.add_argument("--pcd", default=None)
args = parser.parse_args()
|
sys.path.append(os.getcwd()) # noqa
# from datasets.geo_utils import observe_angle_distance
# from render_tools.render_utils import *
def spheric_pose(theta, phi, radius, height):
trans_t = lambda t: np.array(
[
[1, 0, 0, 0],
[0, 1, 0, -0.9 * t],
[0, 0, 1, t],
[0, 0, 0, 1],
]
)
rot_phi = lambda phi: np.array(
[
[1, 0, 0, 0],
[0, np.cos(phi), -np.sin(phi), 0],
[0, np.sin(phi), np.cos(phi), 0],
[0, 0, 0, 1],
]
)
rot_theta = lambda th: np.array(
[
[np.cos(th), 0, -np.sin(th), 0],
[0, 1, 0, 0],
[np.sin(th), 0, np.cos(th), 0],
[0, 0, 0, 1],
]
)
c2w = rot_theta(theta) @ rot_phi(phi) @ trans_t(radius)
c2w = np.array([[-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) @ c2w
c2w[2, 3] += height
return c2w[:3]
def create_spheric_poses(radius, downward_deg, height, n_poses):
"""
Create circular poses around z axis.
Inputs:
radius: the (negative) height and the radius of the circle.
Outputs:
spheric_poses: (n_poses, 3, 4) the poses in the circular path
"""
spheric_poses = []
for th in np.linspace(0, 2 * np.pi, n_poses + 1)[:-1]:
pose = np.eye(4)
pose[:3, :4] = spheric_pose(th, -(downward_deg * np.pi / 180), radius, height)
fix_rot = np.eye(4)
fix_rot[:3, :3] = np.array([1, 0, 0, 0, 0, 1, 0, -1, 0]).reshape(3, 3)
pose = fix_rot @ pose
spheric_poses += [pose] # 36 degree view downwards
return np.stack(spheric_poses, 0)
def draw_poses(visualizer, poses):
camera_centers = []
lines_pt, lines_idx, lines_color = [], [], []
idx = 0
for frame_id, pose in enumerate(poses):
Twc = pose
# for nerf_synthetic, we need some transformation
fix_rot = np.array([1, 0, 0, 0, -1, 0, 0, 0, -1]).reshape(3, 3)
Twc[:3, :3] = Twc[:3, :3] @ fix_rot
center = Twc[:3, 3]
camera_centers.append(center)
# draw axis
# RGB -> right, down, forward
axis_size = 0.1
# for .T, you can follow https://stackoverflow.com/questions/12148351/
axis_pts = (Twc[:3, :3] @ (np.eye(3) * axis_size)).T + center
lines_pt += [center, axis_pts[0, :], axis_pts[1, :], axis_pts[2, :]]
lines_idx += [
[idx * 4 + 0, idx * 4 + 1],
[idx * 4 + 0, idx * 4 + 2],
[idx * 4 + 0, idx * 4 + 3],
]
lines_color += [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
idx += 1
# draw line via cylinder, which we can control the line thickness
visualizer.add_line_set(lines_pt, lines_idx, colors=lines_color, radius=0.003)
# draw line via LineSet
# line_set = o3d.geometry.LineSet(
# points=o3d.utility.Vector3dVector(np.array(lines_pt)),
# lines=o3d.utility.Vector2iVector(np.array(lines_idx)),
# )
# line_set.colors = o3d.utility.Vector3dVector(lines_color)
# visualizer.add_o3d_geometry(line_set)
camera_centers = np.array(camera_centers)
visualizer.add_np_points(
camera_centers,
color=map_to_color(np.arange(0, len(poses)), cmap="plasma"),
size=0.01,
)
if __name__ == "__main__":
# params
parser = argparse.ArgumentParser()
# data paths
parser.add_argument("--pcd", default=None)
args = parser.parse_args()
| visualizer = O3dVisualizer() | 1 | 2023-10-15 08:41:29+00:00 | 4k |
ShramanPramanick/VoLTA | Multimodal_Fine_Grained/maskrcnn_benchmark/modeling/rpn/fcos.py | [
{
"identifier": "make_fcos_loss_evaluator",
"path": "Multimodal_Fine_Grained/maskrcnn_benchmark/modeling/rpn/loss.py",
"snippet": "def make_fcos_loss_evaluator(cfg):\n loss_evaluator = FCOSLossComputation(cfg)\n return loss_evaluator"
},
{
"identifier": "make_center_anchor_generator",
... | import math
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.layers import Scale, DFConv2d
from .loss import make_fcos_loss_evaluator
from .anchor_generator import make_center_anchor_generator
from .inference import make_fcos_postprocessor | 1,809 |
@registry.RPN_HEADS.register("FCOSHead")
class FCOSHead(torch.nn.Module):
def __init__(self, cfg):
super(FCOSHead, self).__init__()
# TODO: Implement the sigmoid version first.
num_classes = cfg.MODEL.FCOS.NUM_CLASSES - 1
in_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS
use_gn = cfg.MODEL.FCOS.USE_GN
use_bn = cfg.MODEL.FCOS.USE_BN
use_dcn_in_tower = cfg.MODEL.FCOS.USE_DFCONV
self.fpn_strides = cfg.MODEL.FCOS.FPN_STRIDES
self.norm_reg_targets = cfg.MODEL.FCOS.NORM_REG_TARGETS
self.centerness_on_reg = cfg.MODEL.FCOS.CENTERNESS_ON_REG
cls_tower = []
bbox_tower = []
for i in range(cfg.MODEL.FCOS.NUM_CONVS):
if use_dcn_in_tower and i == cfg.MODEL.FCOS.NUM_CONVS - 1:
conv_func = DFConv2d
else:
conv_func = nn.Conv2d
cls_tower.append(conv_func(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=True))
if use_gn:
cls_tower.append(nn.GroupNorm(32, in_channels))
if use_bn:
cls_tower.append(nn.BatchNorm2d(in_channels))
cls_tower.append(nn.ReLU())
bbox_tower.append(conv_func(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=True))
if use_gn:
bbox_tower.append(nn.GroupNorm(32, in_channels))
if use_bn:
bbox_tower.append(nn.BatchNorm2d(in_channels))
bbox_tower.append(nn.ReLU())
self.add_module("cls_tower", nn.Sequential(*cls_tower))
self.add_module("bbox_tower", nn.Sequential(*bbox_tower))
self.cls_logits = nn.Conv2d(in_channels, num_classes, kernel_size=3, stride=1, padding=1)
self.bbox_pred = nn.Conv2d(in_channels, 4, kernel_size=3, stride=1, padding=1)
self.centerness = nn.Conv2d(in_channels, 1, kernel_size=3, stride=1, padding=1)
# initialization
for modules in [self.cls_tower, self.bbox_tower, self.cls_logits, self.bbox_pred, self.centerness]:
for l in modules.modules():
if isinstance(l, nn.Conv2d):
torch.nn.init.normal_(l.weight, std=0.01)
torch.nn.init.constant_(l.bias, 0)
# initialize the bias for focal loss
prior_prob = cfg.MODEL.FCOS.PRIOR_PROB
bias_value = -math.log((1 - prior_prob) / prior_prob)
torch.nn.init.constant_(self.cls_logits.bias, bias_value)
self.scales = nn.ModuleList([Scale(init_value=1.0) for _ in range(5)])
def forward(self, x):
logits = []
bbox_reg = []
centerness = []
for l, feature in enumerate(x):
cls_tower = self.cls_tower(feature)
box_tower = self.bbox_tower(feature)
logits.append(self.cls_logits(cls_tower))
if self.centerness_on_reg:
centerness.append(self.centerness(box_tower))
else:
centerness.append(self.centerness(cls_tower))
bbox_pred = self.scales[l](self.bbox_pred(box_tower))
if self.norm_reg_targets:
bbox_pred = F.relu(bbox_pred)
if self.training:
bbox_reg.append(bbox_pred)
else:
bbox_reg.append(bbox_pred * self.fpn_strides[l])
else:
bbox_reg.append(torch.exp(bbox_pred))
return logits, bbox_reg, centerness
class FCOSModule(torch.nn.Module):
"""
Module for FCOS computation. Takes feature maps from the backbone and
FCOS outputs and losses. Only Test on FPN now.
"""
def __init__(self, cfg):
super(FCOSModule, self).__init__()
head = FCOSHead(cfg)
box_selector_train = make_fcos_postprocessor(cfg, is_train=True)
box_selector_test = make_fcos_postprocessor(cfg, is_train=False)
loss_evaluator = make_fcos_loss_evaluator(cfg)
self.cfg = cfg
self.head = head
self.box_selector_train = box_selector_train
self.box_selector_test = box_selector_test
self.loss_evaluator = loss_evaluator
self.fpn_strides = cfg.MODEL.FCOS.FPN_STRIDES
if not cfg.MODEL.RPN_ONLY:
|
@registry.RPN_HEADS.register("FCOSHead")
class FCOSHead(torch.nn.Module):
def __init__(self, cfg):
super(FCOSHead, self).__init__()
# TODO: Implement the sigmoid version first.
num_classes = cfg.MODEL.FCOS.NUM_CLASSES - 1
in_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS
use_gn = cfg.MODEL.FCOS.USE_GN
use_bn = cfg.MODEL.FCOS.USE_BN
use_dcn_in_tower = cfg.MODEL.FCOS.USE_DFCONV
self.fpn_strides = cfg.MODEL.FCOS.FPN_STRIDES
self.norm_reg_targets = cfg.MODEL.FCOS.NORM_REG_TARGETS
self.centerness_on_reg = cfg.MODEL.FCOS.CENTERNESS_ON_REG
cls_tower = []
bbox_tower = []
for i in range(cfg.MODEL.FCOS.NUM_CONVS):
if use_dcn_in_tower and i == cfg.MODEL.FCOS.NUM_CONVS - 1:
conv_func = DFConv2d
else:
conv_func = nn.Conv2d
cls_tower.append(conv_func(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=True))
if use_gn:
cls_tower.append(nn.GroupNorm(32, in_channels))
if use_bn:
cls_tower.append(nn.BatchNorm2d(in_channels))
cls_tower.append(nn.ReLU())
bbox_tower.append(conv_func(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=True))
if use_gn:
bbox_tower.append(nn.GroupNorm(32, in_channels))
if use_bn:
bbox_tower.append(nn.BatchNorm2d(in_channels))
bbox_tower.append(nn.ReLU())
self.add_module("cls_tower", nn.Sequential(*cls_tower))
self.add_module("bbox_tower", nn.Sequential(*bbox_tower))
self.cls_logits = nn.Conv2d(in_channels, num_classes, kernel_size=3, stride=1, padding=1)
self.bbox_pred = nn.Conv2d(in_channels, 4, kernel_size=3, stride=1, padding=1)
self.centerness = nn.Conv2d(in_channels, 1, kernel_size=3, stride=1, padding=1)
# initialization
for modules in [self.cls_tower, self.bbox_tower, self.cls_logits, self.bbox_pred, self.centerness]:
for l in modules.modules():
if isinstance(l, nn.Conv2d):
torch.nn.init.normal_(l.weight, std=0.01)
torch.nn.init.constant_(l.bias, 0)
# initialize the bias for focal loss
prior_prob = cfg.MODEL.FCOS.PRIOR_PROB
bias_value = -math.log((1 - prior_prob) / prior_prob)
torch.nn.init.constant_(self.cls_logits.bias, bias_value)
self.scales = nn.ModuleList([Scale(init_value=1.0) for _ in range(5)])
def forward(self, x):
logits = []
bbox_reg = []
centerness = []
for l, feature in enumerate(x):
cls_tower = self.cls_tower(feature)
box_tower = self.bbox_tower(feature)
logits.append(self.cls_logits(cls_tower))
if self.centerness_on_reg:
centerness.append(self.centerness(box_tower))
else:
centerness.append(self.centerness(cls_tower))
bbox_pred = self.scales[l](self.bbox_pred(box_tower))
if self.norm_reg_targets:
bbox_pred = F.relu(bbox_pred)
if self.training:
bbox_reg.append(bbox_pred)
else:
bbox_reg.append(bbox_pred * self.fpn_strides[l])
else:
bbox_reg.append(torch.exp(bbox_pred))
return logits, bbox_reg, centerness
class FCOSModule(torch.nn.Module):
"""
Module for FCOS computation. Takes feature maps from the backbone and
FCOS outputs and losses. Only Test on FPN now.
"""
def __init__(self, cfg):
super(FCOSModule, self).__init__()
head = FCOSHead(cfg)
box_selector_train = make_fcos_postprocessor(cfg, is_train=True)
box_selector_test = make_fcos_postprocessor(cfg, is_train=False)
loss_evaluator = make_fcos_loss_evaluator(cfg)
self.cfg = cfg
self.head = head
self.box_selector_train = box_selector_train
self.box_selector_test = box_selector_test
self.loss_evaluator = loss_evaluator
self.fpn_strides = cfg.MODEL.FCOS.FPN_STRIDES
if not cfg.MODEL.RPN_ONLY: | self.anchor_generator = make_center_anchor_generator(cfg) | 1 | 2023-10-23 04:07:08+00:00 | 4k |
earthcube-lab/textnoisr | scripts/generate_figures.py | [
{
"identifier": "CharNoiseAugmenter",
"path": "textnoisr/noise.py",
"snippet": "class CharNoiseAugmenter:\n r\"\"\"Add noise into text according to a noise level measured between 0 and 1.\n\n It will add noise to a string by modifying each character\n according to a probability and a list o... | import argparse
import logging
import sys
import time
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import pandas as pd
from pathlib import Path
from datasets import load_dataset
from evaluate import load
from nlpaug.augmenter.char import RandomCharAug
from textnoisr.noise import CharNoiseAugmenter
from textnoisr.noise_unbiasing import MAX_SWAP_LEVEL | 2,552 | """Generate figures for the documentation.
## Pre-requisites
You'll need to install the following packages:
```sh
pip install matplotlib nlpaug
```
If you don't have [Roboto](https://fonts.google.com/specimen/Roboto) installed, the
default font will be used.
## Usage
From the root of the project, run:
```sh
python scripts/generate_figures.py
```
It will download the `rotten_tomatoes` dataset and generate the figures in
`docs/images/`. For more options, see:
```sh
python scripts/generate_figures.py --help
```
"""
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
cer = load("cer")
ACTIONS = ("delete", "insert", "substitute", "swap")
STYLE_DIR = Path(__file__).parent.parent / "styles"
OUTPUT_DIR = Path(__file__).parent.parent / "docs" / "images"
DEFAULT_DATASET = "rotten_tomatoes"
DEFAULT_SPLIT = "train"
DEFAULT_N_SAMPLES = 17
def max_level(actions):
if "swap" in actions:
| """Generate figures for the documentation.
## Pre-requisites
You'll need to install the following packages:
```sh
pip install matplotlib nlpaug
```
If you don't have [Roboto](https://fonts.google.com/specimen/Roboto) installed, the
default font will be used.
## Usage
From the root of the project, run:
```sh
python scripts/generate_figures.py
```
It will download the `rotten_tomatoes` dataset and generate the figures in
`docs/images/`. For more options, see:
```sh
python scripts/generate_figures.py --help
```
"""
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
cer = load("cer")
ACTIONS = ("delete", "insert", "substitute", "swap")
STYLE_DIR = Path(__file__).parent.parent / "styles"
OUTPUT_DIR = Path(__file__).parent.parent / "docs" / "images"
DEFAULT_DATASET = "rotten_tomatoes"
DEFAULT_SPLIT = "train"
DEFAULT_N_SAMPLES = 17
def max_level(actions):
if "swap" in actions: | return MAX_SWAP_LEVEL / 1.052 - 0.005 | 1 | 2023-10-18 19:28:34+00:00 | 4k |
WenzhengZhang/Seq2seqCoref | check_align.py | [
{
"identifier": "CorefAllMetrics",
"path": "metrics.py",
"snippet": "class CorefAllMetrics(object):\n \"\"\"\n Wrapper for coreference resolution metrics.\n \"\"\"\n\n @staticmethod\n def _get_mention_to_x(clusters: List[list]) -> dict:\n mention_to_x = {}\n for cluster in c... | import os
import json
import re
import argparse
from collections import defaultdict
from metrics import CorefAllMetrics
from typing import Dict
from data import get_document_predicts, SPECIAL_IDS, parse_short_target_tokens
from transformers import T5Tokenizer
from preprocess import SPEAKER_START, SPEAKER_END, MENTION_START, \
MENTION_END, COPY
from preprocess_mark_sentence import SPECIAL_IDS as MARK_SPECIAL_IDS
from preprocess_mark_sentence import SENTENCE_START, SENTENCE_END | 2,416 |
def load_data(data_dir, tokenizer):
def load_split(split):
max_len = 4096
data_path = os.path.join(
data_dir,
f'{split}.t5-small.english.{max_len}.jsonlines')
samples = []
doc_labels = {}
with open(data_path, 'r') as f:
for line in f:
item = json.loads(line)
doc_key = item['doc_key']
doc_id = re.sub(r'_\d+$', '', doc_key)
target_seq = tokenizer.convert_tokens_to_ids(
item['target_short_sentence'])
sample = {'doc_key': doc_key,
'sentence': tokenizer.convert_tokens_to_ids(
item['sentence']),
'target_seq': target_seq,
'subtoken_map': item['subtoken_map'],
'seg_clusters': [[tuple(m) for m in c] for c in item[
'seg_clusters'] if len(c) >= 2],
'offset': item['offset']
}
doc_labels[doc_id] = [[tuple(m) for m in c] for c in item[
'gold_clusters']]
samples.append(sample)
return samples, doc_labels
samples_dev, dev_labels = load_split('dev')
samples_test, test_labels = load_split('test')
return samples_dev, samples_test, dev_labels, test_labels
def oracle_align(doc_labels, samples, tokenizer, align_mode, mark_sentence) -> \
Dict:
documents_to_chunk_data = defaultdict(list)
documents_to_chunk_gold = defaultdict(list)
predictions = {}
golds = {}
last_doc_id = re.sub(r'_\d+$', '', samples[0]['doc_key'])
for sample in samples:
doc_key = sample['doc_key']
doc_id = re.sub(r'_\d+$', '', doc_key)
# require convert to ids first
input_ids = sample['sentence']
subtoken_map = sample['subtoken_map']
offset = sample['offset']
# remove bos
predict_ids = sample['target_seq']
gold_data = sample['seg_clusters']
special_ids = MARK_SPECIAL_IDS if mark_sentence else SPECIAL_IDS
pred_data, aligned_input_ids, aligned_pred_ids = \
parse_short_target_tokens(input_ids, predict_ids,
special_ids, subtoken_map,
tokenizer,
align_mode, 2, mark_sentence)
# list of (m1,m2)
documents_to_chunk_data[doc_id].extend(pred_data)
documents_to_chunk_gold[doc_id].extend(gold_data)
if doc_id != last_doc_id:
predictions[last_doc_id] = get_document_predicts(
documents_to_chunk_data[
last_doc_id])
golds[last_doc_id] = get_document_predicts(
documents_to_chunk_gold[
last_doc_id])
last_doc_id = doc_id
# final one
predictions[last_doc_id] = get_document_predicts(
documents_to_chunk_data[last_doc_id]
)
golds[last_doc_id] = get_document_predicts(
documents_to_chunk_gold[last_doc_id]
)
# print(predictions)
predictions_list = []
labels_list = []
golds_list = []
for document_id, doc_label in doc_labels.items():
predictions_list.append(predictions[document_id])
labels_list.append(doc_label)
golds_list.append(golds[document_id])
|
def load_data(data_dir, tokenizer):
def load_split(split):
max_len = 4096
data_path = os.path.join(
data_dir,
f'{split}.t5-small.english.{max_len}.jsonlines')
samples = []
doc_labels = {}
with open(data_path, 'r') as f:
for line in f:
item = json.loads(line)
doc_key = item['doc_key']
doc_id = re.sub(r'_\d+$', '', doc_key)
target_seq = tokenizer.convert_tokens_to_ids(
item['target_short_sentence'])
sample = {'doc_key': doc_key,
'sentence': tokenizer.convert_tokens_to_ids(
item['sentence']),
'target_seq': target_seq,
'subtoken_map': item['subtoken_map'],
'seg_clusters': [[tuple(m) for m in c] for c in item[
'seg_clusters'] if len(c) >= 2],
'offset': item['offset']
}
doc_labels[doc_id] = [[tuple(m) for m in c] for c in item[
'gold_clusters']]
samples.append(sample)
return samples, doc_labels
samples_dev, dev_labels = load_split('dev')
samples_test, test_labels = load_split('test')
return samples_dev, samples_test, dev_labels, test_labels
def oracle_align(doc_labels, samples, tokenizer, align_mode, mark_sentence) -> \
Dict:
documents_to_chunk_data = defaultdict(list)
documents_to_chunk_gold = defaultdict(list)
predictions = {}
golds = {}
last_doc_id = re.sub(r'_\d+$', '', samples[0]['doc_key'])
for sample in samples:
doc_key = sample['doc_key']
doc_id = re.sub(r'_\d+$', '', doc_key)
# require convert to ids first
input_ids = sample['sentence']
subtoken_map = sample['subtoken_map']
offset = sample['offset']
# remove bos
predict_ids = sample['target_seq']
gold_data = sample['seg_clusters']
special_ids = MARK_SPECIAL_IDS if mark_sentence else SPECIAL_IDS
pred_data, aligned_input_ids, aligned_pred_ids = \
parse_short_target_tokens(input_ids, predict_ids,
special_ids, subtoken_map,
tokenizer,
align_mode, 2, mark_sentence)
# list of (m1,m2)
documents_to_chunk_data[doc_id].extend(pred_data)
documents_to_chunk_gold[doc_id].extend(gold_data)
if doc_id != last_doc_id:
predictions[last_doc_id] = get_document_predicts(
documents_to_chunk_data[
last_doc_id])
golds[last_doc_id] = get_document_predicts(
documents_to_chunk_gold[
last_doc_id])
last_doc_id = doc_id
# final one
predictions[last_doc_id] = get_document_predicts(
documents_to_chunk_data[last_doc_id]
)
golds[last_doc_id] = get_document_predicts(
documents_to_chunk_gold[last_doc_id]
)
# print(predictions)
predictions_list = []
labels_list = []
golds_list = []
for document_id, doc_label in doc_labels.items():
predictions_list.append(predictions[document_id])
labels_list.append(doc_label)
golds_list.append(golds[document_id])
| metrics = CorefAllMetrics().get_all_metrics(labels_list, | 0 | 2023-10-17 17:39:16+00:00 | 4k |
oven-lab/tuya_cloud_map_extractor | custom_components/tuya_cloud_map_extractor/config_flow.py | [
{
"identifier": "get_map",
"path": "custom_components/tuya_cloud_map_extractor/tuya_vacuum_map_extractor/main.py",
"snippet": "def get_map(\n server: str, client_id: str, secret_key: str, device_id: str, colors={}, settings={}, urls={}\n) -> Image:\n \"\"\"Downloads and parses vacuum map from tuya... | import logging
import voluptuous as vol
from typing import Any
from .tuya_vacuum_map_extractor import (
get_map,
ClientIDError,
ClientSecretError,
DeviceIDError,
ServerError,
)
from homeassistant import config_entries
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.selector import selector
from homeassistant.const import (
CONF_NAME,
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_DEVICE_ID,
)
from .const import * | 1,925 | from __future__ import annotations
CONF_SERVERS = {
CONF_SERVER_CHINA: "China",
CONF_SERVER_WEST_AMERICA: "Western America",
CONF_SERVER_EAST_AMERICA: "Eastern America",
CONF_SERVER_CENTRAL_EUROPE: "Central Europe",
CONF_SERVER_WEST_EUROPE: "Western Europe",
CONF_SERVER_INDIA: "India"
}
_LOGGER = logging.getLogger(__name__)
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 3
def __init__(self) -> None:
super().__init__()
self.map_header = {}
self._config_data = {}
async def async_step_user(self, user_input=None):
default_server = CONF_SERVER_CENTRAL_EUROPE
default_name = "Vacuum map"
default_client_id = ""
default_client_secret = ""
default_device_id = ""
errors = {}
if user_input is not None:
try:
headers, image = await validate(self.hass, user_input)
self.map_header = headers
if user_input[CONF_COLORS]:
del user_input[CONF_COLORS]
self._config_data.update(user_input)
return await self.async_step_colorconf()
del user_input[CONF_COLORS]
self._config_data.update(user_input)
data = create_entry_data(
self._config_data.copy(), self.map_header.copy()
)
return self.async_create_entry(title=data.pop(CONF_NAME), data=data)
except ClientIDError:
errors[CONF_CLIENT_ID] = "client_id"
except ClientSecretError:
errors[CONF_CLIENT_SECRET] = "client_secret"
except DeviceIDError:
errors[CONF_DEVICE_ID] = "device_id"
| from __future__ import annotations
CONF_SERVERS = {
CONF_SERVER_CHINA: "China",
CONF_SERVER_WEST_AMERICA: "Western America",
CONF_SERVER_EAST_AMERICA: "Eastern America",
CONF_SERVER_CENTRAL_EUROPE: "Central Europe",
CONF_SERVER_WEST_EUROPE: "Western Europe",
CONF_SERVER_INDIA: "India"
}
_LOGGER = logging.getLogger(__name__)
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 3
def __init__(self) -> None:
super().__init__()
self.map_header = {}
self._config_data = {}
async def async_step_user(self, user_input=None):
default_server = CONF_SERVER_CENTRAL_EUROPE
default_name = "Vacuum map"
default_client_id = ""
default_client_secret = ""
default_device_id = ""
errors = {}
if user_input is not None:
try:
headers, image = await validate(self.hass, user_input)
self.map_header = headers
if user_input[CONF_COLORS]:
del user_input[CONF_COLORS]
self._config_data.update(user_input)
return await self.async_step_colorconf()
del user_input[CONF_COLORS]
self._config_data.update(user_input)
data = create_entry_data(
self._config_data.copy(), self.map_header.copy()
)
return self.async_create_entry(title=data.pop(CONF_NAME), data=data)
except ClientIDError:
errors[CONF_CLIENT_ID] = "client_id"
except ClientSecretError:
errors[CONF_CLIENT_SECRET] = "client_secret"
except DeviceIDError:
errors[CONF_DEVICE_ID] = "device_id" | except ServerError: | 4 | 2023-10-22 10:48:25+00:00 | 4k |
mlbio-epfl/hume | hume.py | [
{
"identifier": "parse_args",
"path": "argparser.py",
"snippet": "def parse_args(args):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--phi1_path', \n type=str,\n required=True,\n help=\"Path to the embeddings in ... | import os
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import learn2learn as l2l
import numpy as np
from tqdm import tqdm
from argparser import parse_args
from activations import Sparsemax
from utils import fix_seed, get_cv_score, check_both_none_or_not_none
from metrics import cluster_acc, cluster_ari | 2,848 | else:
phi1_val = np.copy(phi1)
phi2_val = np.copy(phi2)
y_true_val = np.load(args.gt_labels_path)
assert phi1.shape[0] == phi2.shape[0]
assert phi1_val.shape[0] == phi2_val.shape[0]
assert phi1_val.shape[0] == y_true_val.shape[0]
n_train = phi1.shape[0]
d1, d2 = phi2.shape[1], phi1.shape[1]
subset_size = min(n_train, args.subset_size)
# Instantiate linear layer for the inner optimization (Equation 5)
inner_linear = nn.Linear(d1, args.k, bias=True).to(device)
inner_linear = l2l.algorithms.MAML(inner_linear, lr=args.inner_lr)
# Instantiate task encoder with orthogonal weights parametrization (Equation 3)
task_encoder = nn.Linear(d2, args.k, bias=False).to(device)
task_encoder = nn.utils.parametrizations.orthogonal(task_encoder)
all_parameters = list(task_encoder.parameters())
optimizer = torch.optim.Adam(all_parameters, lr=args.outer_lr)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer, milestones=[100, 200],
gamma=0.1 if args.anneal else 1.0
)
old_lr = args.outer_lr
tau = args.tau
sparsemax_act = Sparsemax(dim=1)
for i in tqdm(range(args.num_iters)):
optimizer.zero_grad()
mean_train_error = 0.0
mean_valid_error = 0.0
mean_valid_acc = 0.0
mean_train_acc = 0.0
mean_label_dist = 0.0
mean_sparsity = 0.0
for j in range(args.num_subsets):
# Sample X_tr and X_te
subset = np.random.choice(n_train, size=subset_size, replace=False)
subset_tr = subset[:int(subset_size * args.train_fraction)]
subset_te = subset[int(subset_size * args.train_fraction):]
phi1_tr = torch.from_numpy(phi1[subset_tr]).to(device)
phi1_te = torch.from_numpy(phi1[subset_te]).to(device)
phi2_tr = torch.from_numpy(phi2[subset_tr]).to(device)
phi2_te = torch.from_numpy(phi2[subset_te]).to(device)
# Get labels using current task encoder
task_labels_tr = sparsemax_act(task_encoder(phi1_tr) / tau)
task_labels_te = sparsemax_act(task_encoder(phi1_te) / tau)
task_labels_all = torch.cat((task_labels_tr, task_labels_te))
"""
Perform inner optimization from the random initialization or
from fixed w0 (corresponds to Cold Start BLO for Equation 5)
"""
if args.rand_init:
inner_linear.reset_parameters()
learner = inner_linear.clone()
for step in range(args.adaptation_steps):
train_error = F.cross_entropy(learner(phi2_tr), task_labels_tr)
learner.adapt(train_error)
# Compute HUME's objective (Equation 7)
label_dist = task_labels_all.mean(0)
entr = torch.special.entr(label_dist)
valid_error = F.cross_entropy(learner(phi2_te), task_labels_te)
# Accumulate gradients across args.num_subsets
(valid_error - args.H_reg * entr.sum()).backward()
# Compute training stats
mean_train_error += train_error.item()
mean_train_acc += torch.eq(
learner(phi2_tr).argmax(1),
task_labels_tr.argmax(1)
).float().mean().item()
mean_valid_error += valid_error.item()
mean_valid_acc += torch.eq(
learner(phi2_te).argmax(1),
task_labels_te.argmax(1)
).float().mean().item()
mean_label_dist += label_dist.detach().cpu().numpy()
mean_sparsity += task_labels_all[torch.arange(task_labels_all.shape[0]),
task_labels_all.argmax(1)].mean().item()
# Average gradients over args.num_subsets and update the task encoder parameters
for p in all_parameters:
p.grad.data.mul_(1.0 / args.num_subsets)
print(f"Grad norm: {torch.norm(p.grad.data).item()}")
nn.utils.clip_grad_norm_(task_encoder.parameters(), 1.0)
optimizer.step()
scheduler.step()
# Anneal step size and temperature
if scheduler.get_last_lr()[0] != old_lr:
print("Annealed Learning rate")
old_lr = scheduler.get_last_lr()[0]
print("Annealed Temperature")
tau = tau / 10
print()
# Print train stats
print("Train stats:")
print(f"Mean TrainError {mean_train_error / args.num_subsets}")
print(f"Mean ValidError {mean_valid_error / args.num_subsets}")
print(f"Mean TrainAcc {mean_train_acc / args.num_subsets}")
print(f"Mean ValidAcc {mean_valid_acc / args.num_subsets}")
print(f"Mean Sparsity {mean_sparsity / args.num_subsets}")
print("Mean Label Dist:", mean_label_dist / args.num_subsets)
print()
# Print val stats
out_all_val = task_encoder(torch.from_numpy(phi1_val).to(device))
preds_all_val = torch.argmax(out_all_val, dim=1).detach().cpu().numpy()
print("Val metrics:")
print("Num found clusters:", len(np.unique(preds_all_val)))
|
def run(args=None):
args = parse_args(args)
device = torch.device(args.device)
fix_seed(args.seed)
if not os.path.exists(args.exp_path):
os.makedirs(args.exp_path)
phi1 = np.load(args.phi1_path).astype(np.float32)
phi2 = np.load(args.phi2_path).astype(np.float32)
assert check_both_none_or_not_none(args.phi1_path_val, args.phi2_path_val)
if args.phi1_path_val is not None:
phi1_val = np.load(args.phi1_path_val).astype(np.float32)
phi2_val = np.load(args.phi2_path_val).astype(np.float32)
else:
phi1_val = np.copy(phi1)
phi2_val = np.copy(phi2)
y_true_val = np.load(args.gt_labels_path)
assert phi1.shape[0] == phi2.shape[0]
assert phi1_val.shape[0] == phi2_val.shape[0]
assert phi1_val.shape[0] == y_true_val.shape[0]
n_train = phi1.shape[0]
d1, d2 = phi2.shape[1], phi1.shape[1]
subset_size = min(n_train, args.subset_size)
# Instantiate linear layer for the inner optimization (Equation 5)
inner_linear = nn.Linear(d1, args.k, bias=True).to(device)
inner_linear = l2l.algorithms.MAML(inner_linear, lr=args.inner_lr)
# Instantiate task encoder with orthogonal weights parametrization (Equation 3)
task_encoder = nn.Linear(d2, args.k, bias=False).to(device)
task_encoder = nn.utils.parametrizations.orthogonal(task_encoder)
all_parameters = list(task_encoder.parameters())
optimizer = torch.optim.Adam(all_parameters, lr=args.outer_lr)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer, milestones=[100, 200],
gamma=0.1 if args.anneal else 1.0
)
old_lr = args.outer_lr
tau = args.tau
sparsemax_act = Sparsemax(dim=1)
for i in tqdm(range(args.num_iters)):
optimizer.zero_grad()
mean_train_error = 0.0
mean_valid_error = 0.0
mean_valid_acc = 0.0
mean_train_acc = 0.0
mean_label_dist = 0.0
mean_sparsity = 0.0
for j in range(args.num_subsets):
# Sample X_tr and X_te
subset = np.random.choice(n_train, size=subset_size, replace=False)
subset_tr = subset[:int(subset_size * args.train_fraction)]
subset_te = subset[int(subset_size * args.train_fraction):]
phi1_tr = torch.from_numpy(phi1[subset_tr]).to(device)
phi1_te = torch.from_numpy(phi1[subset_te]).to(device)
phi2_tr = torch.from_numpy(phi2[subset_tr]).to(device)
phi2_te = torch.from_numpy(phi2[subset_te]).to(device)
# Get labels using current task encoder
task_labels_tr = sparsemax_act(task_encoder(phi1_tr) / tau)
task_labels_te = sparsemax_act(task_encoder(phi1_te) / tau)
task_labels_all = torch.cat((task_labels_tr, task_labels_te))
"""
Perform inner optimization from the random initialization or
from fixed w0 (corresponds to Cold Start BLO for Equation 5)
"""
if args.rand_init:
inner_linear.reset_parameters()
learner = inner_linear.clone()
for step in range(args.adaptation_steps):
train_error = F.cross_entropy(learner(phi2_tr), task_labels_tr)
learner.adapt(train_error)
# Compute HUME's objective (Equation 7)
label_dist = task_labels_all.mean(0)
entr = torch.special.entr(label_dist)
valid_error = F.cross_entropy(learner(phi2_te), task_labels_te)
# Accumulate gradients across args.num_subsets
(valid_error - args.H_reg * entr.sum()).backward()
# Compute training stats
mean_train_error += train_error.item()
mean_train_acc += torch.eq(
learner(phi2_tr).argmax(1),
task_labels_tr.argmax(1)
).float().mean().item()
mean_valid_error += valid_error.item()
mean_valid_acc += torch.eq(
learner(phi2_te).argmax(1),
task_labels_te.argmax(1)
).float().mean().item()
mean_label_dist += label_dist.detach().cpu().numpy()
mean_sparsity += task_labels_all[torch.arange(task_labels_all.shape[0]),
task_labels_all.argmax(1)].mean().item()
# Average gradients over args.num_subsets and update the task encoder parameters
for p in all_parameters:
p.grad.data.mul_(1.0 / args.num_subsets)
print(f"Grad norm: {torch.norm(p.grad.data).item()}")
nn.utils.clip_grad_norm_(task_encoder.parameters(), 1.0)
optimizer.step()
scheduler.step()
# Anneal step size and temperature
if scheduler.get_last_lr()[0] != old_lr:
print("Annealed Learning rate")
old_lr = scheduler.get_last_lr()[0]
print("Annealed Temperature")
tau = tau / 10
print()
# Print train stats
print("Train stats:")
print(f"Mean TrainError {mean_train_error / args.num_subsets}")
print(f"Mean ValidError {mean_valid_error / args.num_subsets}")
print(f"Mean TrainAcc {mean_train_acc / args.num_subsets}")
print(f"Mean ValidAcc {mean_valid_acc / args.num_subsets}")
print(f"Mean Sparsity {mean_sparsity / args.num_subsets}")
print("Mean Label Dist:", mean_label_dist / args.num_subsets)
print()
# Print val stats
out_all_val = task_encoder(torch.from_numpy(phi1_val).to(device))
preds_all_val = torch.argmax(out_all_val, dim=1).detach().cpu().numpy()
print("Val metrics:")
print("Num found clusters:", len(np.unique(preds_all_val))) | print(f"Cluster ACC epoch {i}:", cluster_acc(preds_all_val, y_true_val)) | 5 | 2023-10-20 15:32:06+00:00 | 4k |
lwaekfjlk/TRAMS | utils/src.py | [
{
"identifier": "TransfoXLLMHeadModel",
"path": "utils/modeling_transfo_xl.py",
"snippet": "_CHECKPOINT_FOR_DOC = \"transfo-xl-wt103\"\n_CONFIG_FOR_DOC = \"TransfoXLConfig\"\n_TOKENIZER_FOR_DOC = \"TransfoXLTokenizer\"\nTRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"transfo-xl-wt103\",\n # See a... | import os
import logging
import wandb
import torch
import sys
from torch.nn.parallel import DistributedDataParallel
from torch.optim import Adam
from utils.modeling_transfo_xl import TransfoXLLMHeadModel, TransfoXLConfig
from torch.optim.lr_scheduler import ExponentialLR, LambdaLR
from transformers import get_linear_schedule_with_warmup, get_cosine_schedule_with_warmup
from data_utils import get_lm_corpus
from earlystopping import EarlyStopper | 3,306 |
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
class Trainer(object):
def __init__(self, args):
super().__init__()
self.args = args
self.set_tool()
self.set_dist()
self.set_seed()
self.train_iter, self.valid_iter, self.test_iter = self.prepare_data()
self.model = self.get_model(use_checkpoint=self.args.use_checkpoint)
self.optimizer = Adam(params=self.model.parameters(), lr=self.args.lr)
self.scheduler = self.get_scheduler()
self.earlystopper = EarlyStopper(args, self.logger)
def avg_rank(self, scalar):
if self.args.local_rank == -1:
return scalar
scalar_t = torch.tensor(
scalar,
dtype=torch.float,
device=self.device
) / torch.distributed.get_world_size()
torch.distributed.all_reduce(
scalar_t,
op=torch.distributed.ReduceOp.SUM
)
return scalar_t.item()
def set_tool(self):
if self.args.local_rank in [-1, 0]:
os.environ['WANDB_API_KEY'] = '972035264241fb0f6cc3cab51a5d82f47ca713db'
#wandb.init(project="LTDecoder", name=self.args.timestamp, config=self.args, dir='./tmp')
wandb.init(mode='disabled')
self.logger = logging.getLogger(__file__)
def set_dist(self):
self.args.distributed = self.args.local_rank != -1
logging.basicConfig(
level=logging.INFO
if self.args.local_rank in [-1, 0]
else logging.WARN
)
if self.args.distributed:
self.device = torch.device("cuda", self.args.local_rank)
torch.distributed.init_process_group(
backend="nccl",
init_method="env://"
)
else:
self.device = torch.device(
'cuda' if torch.cuda.is_available() else 'cpu'
)
def set_seed(self):
if self.args.distributed:
rank = torch.distributed.get_rank()
torch.manual_seed(self.args.seed_id + rank_id)
torch.cuda.manual_seed(self.args.seed_id + rank_id)
torch.cuda.manual_seed_all(self.args.seed_id + rank_id)
else:
torch.manual_seed(self.args.seed_id)
torch.cuda.manual_seed(self.args.seed_id)
torch.cuda.manual_seed_all(self.args.seed_id)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def log(self, str):
if self.args.local_rank in [-1, 0]:
self.logger.info(str)
def wandb_log(self, dict):
if self.args.local_rank in [-1, 0]:
wandb.log(dict)
def judge_earlystopping(self, metric, model, optimizer, metric_direction='small'):
if self.args.local_rank in [-1, 0]:
self.earlystopper(metric, model, optimizer, metric_direction)
return self.earlystopper.early_stop
else:
return
def get_config(self):
# adaptive softmax / embedding
cutoffs, tie_projs = [], [False]
if self.args.adaptive:
assert self.args.dataset in ['wt103']
if self.args.dataset == 'wt103':
cutoffs = [20000, 40000, 200000]
tie_projs += [True] * len(cutoffs)
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
class Trainer(object):
def __init__(self, args):
super().__init__()
self.args = args
self.set_tool()
self.set_dist()
self.set_seed()
self.train_iter, self.valid_iter, self.test_iter = self.prepare_data()
self.model = self.get_model(use_checkpoint=self.args.use_checkpoint)
self.optimizer = Adam(params=self.model.parameters(), lr=self.args.lr)
self.scheduler = self.get_scheduler()
self.earlystopper = EarlyStopper(args, self.logger)
def avg_rank(self, scalar):
if self.args.local_rank == -1:
return scalar
scalar_t = torch.tensor(
scalar,
dtype=torch.float,
device=self.device
) / torch.distributed.get_world_size()
torch.distributed.all_reduce(
scalar_t,
op=torch.distributed.ReduceOp.SUM
)
return scalar_t.item()
def set_tool(self):
if self.args.local_rank in [-1, 0]:
os.environ['WANDB_API_KEY'] = '972035264241fb0f6cc3cab51a5d82f47ca713db'
#wandb.init(project="LTDecoder", name=self.args.timestamp, config=self.args, dir='./tmp')
wandb.init(mode='disabled')
self.logger = logging.getLogger(__file__)
def set_dist(self):
self.args.distributed = self.args.local_rank != -1
logging.basicConfig(
level=logging.INFO
if self.args.local_rank in [-1, 0]
else logging.WARN
)
if self.args.distributed:
self.device = torch.device("cuda", self.args.local_rank)
torch.distributed.init_process_group(
backend="nccl",
init_method="env://"
)
else:
self.device = torch.device(
'cuda' if torch.cuda.is_available() else 'cpu'
)
def set_seed(self):
if self.args.distributed:
rank = torch.distributed.get_rank()
torch.manual_seed(self.args.seed_id + rank_id)
torch.cuda.manual_seed(self.args.seed_id + rank_id)
torch.cuda.manual_seed_all(self.args.seed_id + rank_id)
else:
torch.manual_seed(self.args.seed_id)
torch.cuda.manual_seed(self.args.seed_id)
torch.cuda.manual_seed_all(self.args.seed_id)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def log(self, str):
if self.args.local_rank in [-1, 0]:
self.logger.info(str)
def wandb_log(self, dict):
if self.args.local_rank in [-1, 0]:
wandb.log(dict)
def judge_earlystopping(self, metric, model, optimizer, metric_direction='small'):
if self.args.local_rank in [-1, 0]:
self.earlystopper(metric, model, optimizer, metric_direction)
return self.earlystopper.early_stop
else:
return
def get_config(self):
# adaptive softmax / embedding
cutoffs, tie_projs = [], [False]
if self.args.adaptive:
assert self.args.dataset in ['wt103']
if self.args.dataset == 'wt103':
cutoffs = [20000, 40000, 200000]
tie_projs += [True] * len(cutoffs)
| config = TransfoXLConfig( | 0 | 2023-10-19 00:49:29+00:00 | 4k |
npgrosser/autowired | autowired/_container.py | [
{
"identifier": "component_scan",
"path": "autowired/_component_scan.py",
"snippet": "def component_scan(root_module: ModuleType) -> Iterable[ClassComponentInfo]:\n scanner = ClassScanner(root_module)\n component_infos = (get_component_info(cls) for cls in scanner.get_classes())\n return (c for... | import dataclasses
import inspect
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
from types import FunctionType, ModuleType
from typing import (
Type,
Callable,
Any,
List,
Optional,
Union,
Generic,
Dict,
TypeVar,
)
from ._component_scan import component_scan
from ._exceptions import (
MissingTypeAnnotation,
AmbiguousDependencyException,
IllegalAutoWireType,
InstantiationError,
UnresolvableDependencyException,
AutowiredException,
)
from ._logging import logger
from ._typing_utils import is_subtype, get_sequence_type | 2,707 | @staticmethod
def from_supplier(
supplier: Callable[[], _T],
type: Optional[Type[_T]] = None,
name: Optional[str] = None,
) -> "Provider[_T]":
"""
Creates a provider from the given supplier function.
:param supplier: The supplier function. Will be called every time self.get_instance(...) is called.
:param type: The type of the component this provider provides.
If None, the return type of the supplier function is used, or if supplier is a class,
the class itself is used.
:param name: The name of the provider. If None, the type name of the supplier is used (snake case).
:return: The newly created provider
"""
if type is None:
# if getter is a class, use the class as a type
if inspect.isclass(supplier):
type = supplier
else:
type = inspect.signature(supplier).return_annotation
if type == inspect.Signature.empty:
raise MissingTypeAnnotation(
f"Failed to determine type of {supplier.__name__}. "
)
if name is None:
name = _camel_to_snake(type.__name__)
return _SimpleProvider(name, type, supplier)
@staticmethod
def from_class(cls, container: "Container", transient: bool) -> "Provider[_T]":
def supplier():
return container.autowire(cls)
if not transient:
supplier = _cached(supplier)
return _SimpleProvider(_camel_to_snake(cls.__name__), cls, supplier)
def _cached(supplier: Callable[[], _T]) -> Callable[[], _T]:
cached = False
result = None
def wrapper():
nonlocal cached
nonlocal result
if not cached:
result = supplier()
cached = True
return result
return wrapper
@dataclass(frozen=True)
class _SimpleProvider(Provider[_T]):
name: str
type: Type[_T]
getter: Callable[[], _T] = dataclasses.field(repr=False)
def get_instance(self, dependency: Dependency, container: "Container") -> _T:
return self.getter()
def get_name(self) -> str:
return self.name
def satisfies(self, dependency: Dependency) -> bool:
return is_subtype(self.type, dependency.type)
_illegal_autowiredType_modules = ["builtins", "typing", "dataclasses", "abc", "object"]
def _is_illegal_type(t: Type[_T]) -> bool:
return t.__module__.split(".")[0] in _illegal_autowiredType_modules
class Container:
"""
A container for resolving and storing dependencies.
"""
_providers: List[Provider]
def __init__(self):
self._providers = []
def get_providers(self, dependency: Optional[Dependency] = None) -> List[Provider]:
"""
Returns all providers that match the given dependency specification.
:param dependency: Optional dependency specification, if None, all providers are returned
:return:
"""
if dependency is None:
return list(self._providers)
else:
return [p for p in self._providers if p.satisfies(dependency)]
def get_provider(self, dependency: Dependency) -> Optional[Provider]:
"""
Returns an existing provider that matches the given dependency specification.
:param dependency:
:return:
:raises AmbiguousDependencyException: If multiple matching providers are found and there is no name match
"""
candidates = self.get_providers(dependency)
if len(candidates) == 1:
return candidates[0]
if len(candidates) > 1:
by_name = _group_by(lambda obj: obj.name, candidates)
if dependency.name in by_name and len(by_name[dependency.name]) == 1:
return by_name[dependency.name][0]
else:
|
_T = TypeVar("_T")
@dataclass(frozen=True)
class Dependency(Generic[_T]):
"""
A dependency specification.
"""
name: str
type: Type[_T]
required: bool = True
default_factory: Optional[Callable[[], _T]] = None
class Provider(ABC, Generic[_T]):
@abstractmethod
def get_instance(
self, dependency: Dependency, container: "Container"
) -> _T: # pragma: no cover
"""
Returns an instance that satisfies the given dependency specification.
:param dependency: The dependency specification.
:param container: The container that is currently resolving the dependency.
:return: An instance that satisfies the given dependency specification
"""
...
@abstractmethod
def get_name(self) -> str: # pragma: no cover
"""
Returns the name of the provider.
Used by the container to resolve ambiguous dependencies.
If a container contains multiple dependencies that satisfy the same dependency specification,
the name of the dependency is compared to the provider name to try to resolve the ambiguity.
:return: The name of the provider
"""
...
@abstractmethod
def satisfies(self, dependency: Dependency) -> bool: # pragma: no cover
"""
Returns whether this provider satisfies the given dependency specification.
:param dependency: The dependency specification.
:return: Whether this provider satisfies the given dependency specification
"""
...
@staticmethod
def from_instance(instance: _T, name: Optional[str] = None) -> "Provider[_T]":
"""
Creates a singleton provider from the given instance.
:param instance: The instance. Will always be returned by self.get_instance(...)
:param name: The name of the provider. If None, the type name of the instance is used (snake case).
:return: The newly created provider
"""
if name is None:
name = _camel_to_snake(type(instance).__name__)
return _SimpleProvider(name, type(instance), lambda: instance)
# noinspection PyShadowingBuiltins
@staticmethod
def from_supplier(
supplier: Callable[[], _T],
type: Optional[Type[_T]] = None,
name: Optional[str] = None,
) -> "Provider[_T]":
"""
Creates a provider from the given supplier function.
:param supplier: The supplier function. Will be called every time self.get_instance(...) is called.
:param type: The type of the component this provider provides.
If None, the return type of the supplier function is used, or if supplier is a class,
the class itself is used.
:param name: The name of the provider. If None, the type name of the supplier is used (snake case).
:return: The newly created provider
"""
if type is None:
# if getter is a class, use the class as a type
if inspect.isclass(supplier):
type = supplier
else:
type = inspect.signature(supplier).return_annotation
if type == inspect.Signature.empty:
raise MissingTypeAnnotation(
f"Failed to determine type of {supplier.__name__}. "
)
if name is None:
name = _camel_to_snake(type.__name__)
return _SimpleProvider(name, type, supplier)
@staticmethod
def from_class(cls, container: "Container", transient: bool) -> "Provider[_T]":
def supplier():
return container.autowire(cls)
if not transient:
supplier = _cached(supplier)
return _SimpleProvider(_camel_to_snake(cls.__name__), cls, supplier)
def _cached(supplier: Callable[[], _T]) -> Callable[[], _T]:
cached = False
result = None
def wrapper():
nonlocal cached
nonlocal result
if not cached:
result = supplier()
cached = True
return result
return wrapper
@dataclass(frozen=True)
class _SimpleProvider(Provider[_T]):
name: str
type: Type[_T]
getter: Callable[[], _T] = dataclasses.field(repr=False)
def get_instance(self, dependency: Dependency, container: "Container") -> _T:
return self.getter()
def get_name(self) -> str:
return self.name
def satisfies(self, dependency: Dependency) -> bool:
return is_subtype(self.type, dependency.type)
_illegal_autowiredType_modules = ["builtins", "typing", "dataclasses", "abc", "object"]
def _is_illegal_type(t: Type[_T]) -> bool:
return t.__module__.split(".")[0] in _illegal_autowiredType_modules
class Container:
"""
A container for resolving and storing dependencies.
"""
_providers: List[Provider]
def __init__(self):
self._providers = []
def get_providers(self, dependency: Optional[Dependency] = None) -> List[Provider]:
"""
Returns all providers that match the given dependency specification.
:param dependency: Optional dependency specification, if None, all providers are returned
:return:
"""
if dependency is None:
return list(self._providers)
else:
return [p for p in self._providers if p.satisfies(dependency)]
def get_provider(self, dependency: Dependency) -> Optional[Provider]:
"""
Returns an existing provider that matches the given dependency specification.
:param dependency:
:return:
:raises AmbiguousDependencyException: If multiple matching providers are found and there is no name match
"""
candidates = self.get_providers(dependency)
if len(candidates) == 1:
return candidates[0]
if len(candidates) > 1:
by_name = _group_by(lambda obj: obj.name, candidates)
if dependency.name in by_name and len(by_name[dependency.name]) == 1:
return by_name[dependency.name][0]
else: | raise AmbiguousDependencyException( | 2 | 2023-10-16 09:22:20+00:00 | 4k |
chenxn2020/GOSE | GOSEfinetune/data/datasets/xfun.py | [
{
"identifier": "load_image",
"path": "GOSEfinetune/data/utils.py",
"snippet": "def load_image(image_path):\n image = read_image(image_path, format=\"BGR\")\n h = image.shape[0]\n w = image.shape[1]\n img_trans = TransformList([ResizeTransform(h=h, w=w, new_h=224, new_w=224)])\n image = t... | import json
import logging
import os
import datasets
from GOSEfinetune.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox
from transformers import AutoTokenizer | 2,050 | "relations": datasets.Sequence(
{
"head": datasets.Value("int64"),
"tail": datasets.Value("int64"),
"start_index": datasets.Value("int64"),
"end_index": datasets.Value("int64"),
}
),
}
),
supervised_keys=None,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# urls_to_download = {
# "train": [f"{_URL}{self.config.lang}.train.json", f"{_URL}{self.config.lang}.train.zip"],
# "val": [f"{_URL}{self.config.lang}.val.json", f"{_URL}{self.config.lang}.val.zip"],
# # "test": [f"{_URL}{self.config.lang}.test.json", f"{_URL}{self.config.lang}.test.zip"],
# }
# downloaded_files = dl_manager.download_and_extract(urls_to_download)
# train_files_for_many_langs = [downloaded_files["train"]]
# val_files_for_many_langs = [downloaded_files["val"]]
# # test_files_for_many_langs = [downloaded_files["test"]]
self.fewshot = False
self.fewshot_num = 32
self.fewshot_time = 5 #32 1
print(f'=========================fewshot_num {self.fewshot_num}========================')
print(f'=========================fewshot_time {self.fewshot_time}========================')
if not self.fewshot:
file_dir = 'xfund&funsd/'
else:
file_dir = f'fewshot_dataset/xfund&funsd_fewshot{self.fewshot_num}_{self.fewshot_time}/'
print('asdfasdasdff')
print(file_dir)
train_files_for_many_langs = [[file_dir+f"{self.config.lang}.train.json", file_dir+f"{self.config.lang}"]]
val_files_for_many_langs = [[file_dir+f"{self.config.lang}.val.json", file_dir+f"{self.config.lang}"]]
if self.config.additional_langs:
additional_langs = self.config.additional_langs.split("+")
if "all" in additional_langs:
additional_langs = [lang for lang in _LANG if lang != self.config.lang]
for lang in additional_langs:
# urls_to_download = {"train": [f"{_URL}{lang}.train.json", f"{_URL}{lang}.train.zip"]}
# additional_downloaded_files = dl_manager.download_and_extract(urls_to_download)
# train_files_for_many_langs.append(additional_downloaded_files["train"])
train_files_for_many_langs.append([file_dir+f"{lang}.train.json", file_dir+f"{lang}"])
logger.info(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})")
logger.info(f"Evaluating on {self.config.lang}")
logger.info(f"Testing on {self.config.lang}")
print(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})")
print(f"Evaluating on {self.config.lang}")
print(f"Testing on {self.config.lang}")
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": train_files_for_many_langs}),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION, gen_kwargs={"filepaths": val_files_for_many_langs}
),
# datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepaths": test_files_for_many_langs}),
]
def _generate_examples(self, filepaths):
for filepath in filepaths:
logger.info("Generating examples from = %s", filepath)
with open(filepath[0], "r") as f:
data = json.load(f)
for doc in data["documents"]:
doc["img"]["fpath"] = os.path.join(filepath[1], doc["img"]["fname"])
image, size = load_image(doc["img"]["fpath"])
document = doc["document"]
tokenized_doc = {"input_ids": [], "bbox": [], "labels": []}
entities = []
relations = []
id2label = {}
entity_id_to_index_map = {}
empty_entity = set()
for line in document:
if len(line["text"]) == 0:
empty_entity.add(line["id"])
continue
id2label[line["id"]] = line["label"]
relations.extend([tuple(sorted(l)) for l in line["linking"]])
if '/en' in filepath[0]:
tokenized_inputs = self.tokenizer(
' '.join([q['text'].replace(u'\uf703','') for q in line['words']]),
add_special_tokens=False,
return_offsets_mapping=True,
return_attention_mask=False,
)
else:
tokenized_inputs = self.tokenizer(
line["text"],
add_special_tokens=False,
return_offsets_mapping=True,
return_attention_mask=False,
)
text_length = 0
ocr_length = 0
bbox = []
last_box = None
for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
if token_id == 6:
bbox.append(None)
continue
text_length += offset[1] - offset[0]
tmp_box = []
while ocr_length < text_length:
ocr_word = line["words"].pop(0)
ocr_length += len(
self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip())
)
tmp_box.append(simplify_bbox(line["box"]))
if len(tmp_box) == 0:
tmp_box = last_box
| # Lint as: python3
_URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/"
_LANG = ["zh", "de", "es", "fr", "en", "it", "ja", "pt"]
logger = logging.getLogger(__name__)
class XFUNConfig(datasets.BuilderConfig):
"""BuilderConfig for XFUN."""
def __init__(self, lang, additional_langs=None, **kwargs):
"""
Args:
lang: string, language for the input text
**kwargs: keyword arguments forwarded to super.
"""
super(XFUNConfig, self).__init__(**kwargs)
self.lang = lang
self.additional_langs = additional_langs
class XFUN(datasets.GeneratorBasedBuilder):
"""XFUN dataset."""
BUILDER_CONFIGS = [XFUNConfig(name=f"xfun.{lang}", lang=lang) for lang in _LANG]
tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
def __init__(self, data_dir, **kwargs):
super(XFUN, self).__init__(**kwargs)
def _info(self):
return datasets.DatasetInfo(
features=datasets.Features(
{
"id": datasets.Value("string"),
"input_ids": datasets.Sequence(datasets.Value("int64")),
"bbox": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
"labels": datasets.Sequence(
datasets.ClassLabel(
names=["O", "B-QUESTION", "B-ANSWER", "B-HEADER", "I-ANSWER", "I-QUESTION", "I-HEADER"]
)
),
"image": datasets.Array3D(shape=(3, 224, 224), dtype="uint8"),
"entities": datasets.Sequence(
{
"start": datasets.Value("int64"),
"end": datasets.Value("int64"),
"label": datasets.ClassLabel(names=["HEADER", "QUESTION", "ANSWER"]),
}
),
"relations": datasets.Sequence(
{
"head": datasets.Value("int64"),
"tail": datasets.Value("int64"),
"start_index": datasets.Value("int64"),
"end_index": datasets.Value("int64"),
}
),
}
),
supervised_keys=None,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# urls_to_download = {
# "train": [f"{_URL}{self.config.lang}.train.json", f"{_URL}{self.config.lang}.train.zip"],
# "val": [f"{_URL}{self.config.lang}.val.json", f"{_URL}{self.config.lang}.val.zip"],
# # "test": [f"{_URL}{self.config.lang}.test.json", f"{_URL}{self.config.lang}.test.zip"],
# }
# downloaded_files = dl_manager.download_and_extract(urls_to_download)
# train_files_for_many_langs = [downloaded_files["train"]]
# val_files_for_many_langs = [downloaded_files["val"]]
# # test_files_for_many_langs = [downloaded_files["test"]]
self.fewshot = False
self.fewshot_num = 32
self.fewshot_time = 5 #32 1
print(f'=========================fewshot_num {self.fewshot_num}========================')
print(f'=========================fewshot_time {self.fewshot_time}========================')
if not self.fewshot:
file_dir = 'xfund&funsd/'
else:
file_dir = f'fewshot_dataset/xfund&funsd_fewshot{self.fewshot_num}_{self.fewshot_time}/'
print('asdfasdasdff')
print(file_dir)
train_files_for_many_langs = [[file_dir+f"{self.config.lang}.train.json", file_dir+f"{self.config.lang}"]]
val_files_for_many_langs = [[file_dir+f"{self.config.lang}.val.json", file_dir+f"{self.config.lang}"]]
if self.config.additional_langs:
additional_langs = self.config.additional_langs.split("+")
if "all" in additional_langs:
additional_langs = [lang for lang in _LANG if lang != self.config.lang]
for lang in additional_langs:
# urls_to_download = {"train": [f"{_URL}{lang}.train.json", f"{_URL}{lang}.train.zip"]}
# additional_downloaded_files = dl_manager.download_and_extract(urls_to_download)
# train_files_for_many_langs.append(additional_downloaded_files["train"])
train_files_for_many_langs.append([file_dir+f"{lang}.train.json", file_dir+f"{lang}"])
logger.info(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})")
logger.info(f"Evaluating on {self.config.lang}")
logger.info(f"Testing on {self.config.lang}")
print(f"Training on {self.config.lang} with additional langs({self.config.additional_langs})")
print(f"Evaluating on {self.config.lang}")
print(f"Testing on {self.config.lang}")
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": train_files_for_many_langs}),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION, gen_kwargs={"filepaths": val_files_for_many_langs}
),
# datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepaths": test_files_for_many_langs}),
]
def _generate_examples(self, filepaths):
for filepath in filepaths:
logger.info("Generating examples from = %s", filepath)
with open(filepath[0], "r") as f:
data = json.load(f)
for doc in data["documents"]:
doc["img"]["fpath"] = os.path.join(filepath[1], doc["img"]["fname"])
image, size = load_image(doc["img"]["fpath"])
document = doc["document"]
tokenized_doc = {"input_ids": [], "bbox": [], "labels": []}
entities = []
relations = []
id2label = {}
entity_id_to_index_map = {}
empty_entity = set()
for line in document:
if len(line["text"]) == 0:
empty_entity.add(line["id"])
continue
id2label[line["id"]] = line["label"]
relations.extend([tuple(sorted(l)) for l in line["linking"]])
if '/en' in filepath[0]:
tokenized_inputs = self.tokenizer(
' '.join([q['text'].replace(u'\uf703','') for q in line['words']]),
add_special_tokens=False,
return_offsets_mapping=True,
return_attention_mask=False,
)
else:
tokenized_inputs = self.tokenizer(
line["text"],
add_special_tokens=False,
return_offsets_mapping=True,
return_attention_mask=False,
)
text_length = 0
ocr_length = 0
bbox = []
last_box = None
for token_id, offset in zip(tokenized_inputs["input_ids"], tokenized_inputs["offset_mapping"]):
if token_id == 6:
bbox.append(None)
continue
text_length += offset[1] - offset[0]
tmp_box = []
while ocr_length < text_length:
ocr_word = line["words"].pop(0)
ocr_length += len(
self.tokenizer._tokenizer.normalizer.normalize_str(ocr_word["text"].strip())
)
tmp_box.append(simplify_bbox(line["box"]))
if len(tmp_box) == 0:
tmp_box = last_box | bbox.append(normalize_bbox(merge_bbox(tmp_box), size)) | 1 | 2023-10-19 14:36:32+00:00 | 4k |
mklissa/dceo | dopamine/jax/agents/rainbow/rainbow_agent.py | [
{
"identifier": "losses",
"path": "dopamine/jax/losses.py",
"snippet": "def huber_loss(targets: jnp.array,\n predictions: jnp.array,\n delta: float = 1.0) -> jnp.ndarray:\ndef mse_loss(targets: jnp.array, predictions: jnp.array) -> jnp.ndarray:\ndef softmax_cross_entropy_loss... | import functools
import gin
import jax
import jax.numpy as jnp
import numpy as onp
import optax
import tensorflow as tf
from dopamine.jax import losses
from dopamine.jax import networks
from dopamine.jax.agents.dqn import dqn_agent
from dopamine.metrics import statistics_instance
from dopamine.replay_memory import prioritized_replay_buffer | 3,135 | def loss_fn(params, target, loss_multipliers):
def q_online(state):
return network_def.apply(params, state, support)
logits = jax.vmap(q_online)(states).logits
# Fetch the logits for its selected action. We use vmap to perform this
# indexing across the batch.
chosen_action_logits = jax.vmap(lambda x, y: x[y])(logits, actions)
loss = jax.vmap(losses.softmax_cross_entropy_loss_with_logits)(
target,
chosen_action_logits)
mean_loss = jnp.mean(loss_multipliers * loss)
return mean_loss, loss
def q_target(state):
return network_def.apply(target_params, state, support)
grad_fn = jax.value_and_grad(loss_fn, has_aux=True)
target = target_distribution(q_target,
next_states,
rewards,
terminals,
support,
cumulative_gamma)
# Get the unweighted loss without taking its mean for updating priorities.
(mean_loss, loss), grad = grad_fn(online_params, target, loss_weights)
updates, optimizer_state = optimizer.update(grad, optimizer_state,
params=online_params)
online_params = optax.apply_updates(online_params, updates)
return optimizer_state, online_params, loss, mean_loss
@functools.partial(jax.vmap, in_axes=(None, 0, 0, 0, None, None))
def target_distribution(target_network, next_states, rewards, terminals,
support, cumulative_gamma):
"""Builds the C51 target distribution as per Bellemare et al. (2017).
First, we compute the support of the Bellman target, r + gamma Z'. Where Z'
is the support of the next state distribution:
* Evenly spaced in [-vmax, vmax] if the current state is nonterminal;
* 0 otherwise (duplicated num_atoms times).
Second, we compute the next-state probabilities, corresponding to the action
with highest expected value.
Finally we project the Bellman target (support + probabilities) onto the
original support.
Args:
target_network: Jax Module used for the target network.
next_states: numpy array of batched next states.
rewards: numpy array of batched rewards.
terminals: numpy array of batched terminals.
support: support for the distribution.
cumulative_gamma: float, cumulative gamma to use.
Returns:
The target distribution from the replay.
"""
is_terminal_multiplier = 1. - terminals.astype(jnp.float32)
# Incorporate terminal state to discount factor.
gamma_with_terminal = cumulative_gamma * is_terminal_multiplier
target_support = rewards + gamma_with_terminal * support
next_state_target_outputs = target_network(next_states)
q_values = jnp.squeeze(next_state_target_outputs.q_values)
next_qt_argmax = jnp.argmax(q_values)
probabilities = jnp.squeeze(next_state_target_outputs.probabilities)
next_probabilities = probabilities[next_qt_argmax]
return jax.lax.stop_gradient(
project_distribution(target_support, next_probabilities, support))
@functools.partial(jax.jit, static_argnums=(0, 4, 5, 6, 7, 8, 10, 11))
def select_action(network_def, params, state, rng, num_actions, eval_mode,
epsilon_eval, epsilon_train, epsilon_decay_period,
training_steps, min_replay_history, epsilon_fn, support):
"""Select an action from the set of available actions.
Chooses an action randomly with probability self._calculate_epsilon(), and
otherwise acts greedily according to the current Q-value estimates.
Args:
network_def: Linen Module to use for inference.
params: Linen params (frozen dict) to use for inference.
state: input state to use for inference.
rng: Jax random number generator.
num_actions: int, number of actions (static_argnum).
eval_mode: bool, whether we are in eval mode (static_argnum).
epsilon_eval: float, epsilon value to use in eval mode (static_argnum).
epsilon_train: float, epsilon value to use in train mode (static_argnum).
epsilon_decay_period: float, decay period for epsilon value for certain
epsilon functions, such as linearly_decaying_epsilon, (static_argnum).
training_steps: int, number of training steps so far.
min_replay_history: int, minimum number of steps in replay buffer
(static_argnum).
epsilon_fn: function used to calculate epsilon value (static_argnum).
support: support for the distribution.
Returns:
rng: Jax random number generator.
action: int, the selected action.
"""
epsilon = jnp.where(eval_mode,
epsilon_eval,
epsilon_fn(epsilon_decay_period,
training_steps,
min_replay_history,
epsilon_train))
rng, rng1, rng2 = jax.random.split(rng, num=3)
p = jax.random.uniform(rng1)
return rng, jnp.where(
p <= epsilon,
jax.random.randint(rng2, (), 0, num_actions),
jnp.argmax(network_def.apply(params, state, support).q_values))
@gin.configurable
| # coding=utf-8
# Copyright 2018 The Dopamine Authors.
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compact implementation of a simplified Rainbow agent in Jax.
Specifically, we implement the following components from Rainbow:
* n-step updates;
* prioritized replay; and
* distributional RL.
These three components were found to significantly impact the performance of
the Atari game-playing agent.
Furthermore, our implementation does away with some minor hyperparameter
choices. Specifically, we
* keep the beta exponent fixed at beta=0.5, rather than increase it linearly;
* remove the alpha parameter, which was set to alpha=0.5 throughout the paper.
Details in "Rainbow: Combining Improvements in Deep Reinforcement Learning" by
Hessel et al. (2018).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
@functools.partial(jax.jit, static_argnums=(0, 3, 12))
def train(network_def, online_params, target_params, optimizer, optimizer_state,
states, actions, next_states, rewards, terminals, loss_weights,
support, cumulative_gamma):
"""Run a training step."""
def loss_fn(params, target, loss_multipliers):
def q_online(state):
return network_def.apply(params, state, support)
logits = jax.vmap(q_online)(states).logits
# Fetch the logits for its selected action. We use vmap to perform this
# indexing across the batch.
chosen_action_logits = jax.vmap(lambda x, y: x[y])(logits, actions)
loss = jax.vmap(losses.softmax_cross_entropy_loss_with_logits)(
target,
chosen_action_logits)
mean_loss = jnp.mean(loss_multipliers * loss)
return mean_loss, loss
def q_target(state):
return network_def.apply(target_params, state, support)
grad_fn = jax.value_and_grad(loss_fn, has_aux=True)
target = target_distribution(q_target,
next_states,
rewards,
terminals,
support,
cumulative_gamma)
# Get the unweighted loss without taking its mean for updating priorities.
(mean_loss, loss), grad = grad_fn(online_params, target, loss_weights)
updates, optimizer_state = optimizer.update(grad, optimizer_state,
params=online_params)
online_params = optax.apply_updates(online_params, updates)
return optimizer_state, online_params, loss, mean_loss
@functools.partial(jax.vmap, in_axes=(None, 0, 0, 0, None, None))
def target_distribution(target_network, next_states, rewards, terminals,
support, cumulative_gamma):
"""Builds the C51 target distribution as per Bellemare et al. (2017).
First, we compute the support of the Bellman target, r + gamma Z'. Where Z'
is the support of the next state distribution:
* Evenly spaced in [-vmax, vmax] if the current state is nonterminal;
* 0 otherwise (duplicated num_atoms times).
Second, we compute the next-state probabilities, corresponding to the action
with highest expected value.
Finally we project the Bellman target (support + probabilities) onto the
original support.
Args:
target_network: Jax Module used for the target network.
next_states: numpy array of batched next states.
rewards: numpy array of batched rewards.
terminals: numpy array of batched terminals.
support: support for the distribution.
cumulative_gamma: float, cumulative gamma to use.
Returns:
The target distribution from the replay.
"""
is_terminal_multiplier = 1. - terminals.astype(jnp.float32)
# Incorporate terminal state to discount factor.
gamma_with_terminal = cumulative_gamma * is_terminal_multiplier
target_support = rewards + gamma_with_terminal * support
next_state_target_outputs = target_network(next_states)
q_values = jnp.squeeze(next_state_target_outputs.q_values)
next_qt_argmax = jnp.argmax(q_values)
probabilities = jnp.squeeze(next_state_target_outputs.probabilities)
next_probabilities = probabilities[next_qt_argmax]
return jax.lax.stop_gradient(
project_distribution(target_support, next_probabilities, support))
@functools.partial(jax.jit, static_argnums=(0, 4, 5, 6, 7, 8, 10, 11))
def select_action(network_def, params, state, rng, num_actions, eval_mode,
epsilon_eval, epsilon_train, epsilon_decay_period,
training_steps, min_replay_history, epsilon_fn, support):
"""Select an action from the set of available actions.
Chooses an action randomly with probability self._calculate_epsilon(), and
otherwise acts greedily according to the current Q-value estimates.
Args:
network_def: Linen Module to use for inference.
params: Linen params (frozen dict) to use for inference.
state: input state to use for inference.
rng: Jax random number generator.
num_actions: int, number of actions (static_argnum).
eval_mode: bool, whether we are in eval mode (static_argnum).
epsilon_eval: float, epsilon value to use in eval mode (static_argnum).
epsilon_train: float, epsilon value to use in train mode (static_argnum).
epsilon_decay_period: float, decay period for epsilon value for certain
epsilon functions, such as linearly_decaying_epsilon, (static_argnum).
training_steps: int, number of training steps so far.
min_replay_history: int, minimum number of steps in replay buffer
(static_argnum).
epsilon_fn: function used to calculate epsilon value (static_argnum).
support: support for the distribution.
Returns:
rng: Jax random number generator.
action: int, the selected action.
"""
epsilon = jnp.where(eval_mode,
epsilon_eval,
epsilon_fn(epsilon_decay_period,
training_steps,
min_replay_history,
epsilon_train))
rng, rng1, rng2 = jax.random.split(rng, num=3)
p = jax.random.uniform(rng1)
return rng, jnp.where(
p <= epsilon,
jax.random.randint(rng2, (), 0, num_actions),
jnp.argmax(network_def.apply(params, state, support).q_values))
@gin.configurable | class JaxRainbowAgent(dqn_agent.JaxDQNAgent): | 2 | 2023-10-15 22:14:16+00:00 | 4k |
keepfoolisher/My-DocTr-Plus | GeoTr.py | [
{
"identifier": "BasicEncoder",
"path": "extractor.py",
"snippet": "class BasicEncoder(nn.Module):\n def __init__(self, output_dim=128, norm_fn='batch'):\n super(BasicEncoder, self).__init__()\n self.norm_fn = norm_fn\n\n if self.norm_fn == 'group':\n self.norm1 = nn.G... | from extractor import BasicEncoder
from position_encoding import build_position_encoding
from torch import nn, Tensor
from typing import Optional
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import copy | 3,037 | bs, c, h, w = imgf.shape
imgf = imgf.flatten(2).permute(2, 0, 1)
# query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
pos = pos.flatten(2).permute(2, 0, 1)
for layer in self.layers:
query_embed = layer(query_embed, [imgf], pos=pos, memory_pos=[pos, pos])
query_embed = query_embed.permute(1, 2, 0).reshape(bs, c, h, w)
return query_embed
class TransEncoder(nn.Module):
def __init__(self, num_attn_layers, hidden_dim=128):
super(TransEncoder, self).__init__()
attn_layer = attnLayer(hidden_dim)
self.layers = _get_clones(attn_layer, num_attn_layers)
self.position_embedding = build_position_encoding(hidden_dim)
def forward(self, imgf):
pos = self.position_embedding(torch.ones(imgf.shape[0], imgf.shape[2], imgf.shape[3]).bool().cuda()) # torch.Size([1, 128, 36, 36])
bs, c, h, w = imgf.shape
imgf = imgf.flatten(2).permute(2, 0, 1)
pos = pos.flatten(2).permute(2, 0, 1)
for layer in self.layers:
imgf = layer(imgf, [imgf], pos=pos, memory_pos=[pos, pos])
imgf = imgf.permute(1, 2, 0).reshape(bs, c, h, w)
return imgf
class FlowHead(nn.Module):
def __init__(self, input_dim=128, hidden_dim=256):
super(FlowHead, self).__init__()
self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1)
self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
return self.conv2(self.relu(self.conv1(x)))
class UpdateBlock(nn.Module):
def __init__(self, hidden_dim=128):
super(UpdateBlock, self).__init__()
self.flow_head = FlowHead(hidden_dim, hidden_dim=256)
self.mask = nn.Sequential(
nn.Conv2d(hidden_dim, 256, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 64*9, 1, padding=0))
def forward(self, imgf, coords1):
mask = .25 * self.mask(imgf) # scale mask to balence gradients
dflow = self.flow_head(imgf)
coords1 = coords1 + dflow
return mask, coords1
def coords_grid(batch, ht, wd):
coords = torch.meshgrid(torch.arange(ht), torch.arange(wd))
coords = torch.stack(coords[::-1], dim=0).float()
return coords[None].repeat(batch, 1, 1, 1)
def upflow8(flow, mode='bilinear'):
new_size = (8 * flow.shape[2], 8 * flow.shape[3])
return 8 * F.interpolate(flow, size=new_size, mode=mode, align_corners=True)
class OverlapPatchEmbed(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
self.num_patches = self.H * self.W
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,
padding=(patch_size[0] // 2, patch_size[1] // 2))
self.norm = nn.LayerNorm(embed_dim)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
elif isinstance(m, nn.Conv2d):
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
fan_out //= m.groups
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
if m.bias is not None:
m.bias.data.zero_()
def forward(self, x):
x = self.proj(x)
_, _, H, W = x.shape
x = x.flatten(2).transpose(1, 2)
x = self.norm(x)
return x, H, W
class GeoTr(nn.Module):
def __init__(self):
super(GeoTr, self).__init__()
self.hidden_dim = hdim = 256
|
class attnLayer(nn.Module):
def __init__(self, d_model, nhead=8, dim_feedforward=2048, dropout=0.1,
activation="relu", normalize_before=False):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn_list = nn.ModuleList([copy.deepcopy(nn.MultiheadAttention(d_model, nhead, dropout=dropout)) for i in range(2)])
# Implementation of Feedforward model
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2_list = nn.ModuleList([copy.deepcopy(nn.LayerNorm(d_model)) for i in range(2)])
self.norm3 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2_list = nn.ModuleList([copy.deepcopy(nn.Dropout(dropout)) for i in range(2)])
self.dropout3 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, tgt, memory_list, tgt_mask=None, memory_mask=None,
tgt_key_padding_mask=None, memory_key_padding_mask=None,
pos=None, memory_pos=None):
q = k = self.with_pos_embed(tgt, pos)
tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
for memory, multihead_attn, norm2, dropout2, m_pos in zip(memory_list, self.multihead_attn_list, self.norm2_list, self.dropout2_list, memory_pos):
tgt2 = multihead_attn(query=self.with_pos_embed(tgt, pos),
key=self.with_pos_embed(memory, m_pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + dropout2(tgt2)
tgt = norm2(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
tgt = tgt + self.dropout3(tgt2)
tgt = self.norm3(tgt)
return tgt
def forward_pre(self, tgt, memory, tgt_mask=None, memory_mask=None,
tgt_key_padding_mask=None, memory_key_padding_mask=None,
pos=None, memory_pos=None):
tgt2 = self.norm1(tgt)
q = k = self.with_pos_embed(tgt2, pos)
tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout1(tgt2)
tgt2 = self.norm2(tgt)
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, pos),
key=self.with_pos_embed(memory, memory_pos),
value=memory, attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + self.dropout2(tgt2)
tgt2 = self.norm3(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
tgt = tgt + self.dropout3(tgt2)
return tgt
def forward(self, tgt, memory_list, tgt_mask=None, memory_mask=None,
tgt_key_padding_mask=None, memory_key_padding_mask=None,
pos=None, memory_pos=None):
if self.normalize_before:
return self.forward_pre(tgt, memory_list, tgt_mask, memory_mask,
tgt_key_padding_mask, memory_key_padding_mask, pos, memory_pos)
return self.forward_post(tgt, memory_list, tgt_mask, memory_mask,
tgt_key_padding_mask, memory_key_padding_mask, pos, memory_pos)
def _get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
class TransDecoder(nn.Module):
def __init__(self, num_attn_layers, hidden_dim=128):
super(TransDecoder, self).__init__()
attn_layer = attnLayer(hidden_dim)
self.layers = _get_clones(attn_layer, num_attn_layers)
self.position_embedding = build_position_encoding(hidden_dim)
def forward(self, imgf, query_embed):
pos = self.position_embedding(torch.ones(imgf.shape[0], imgf.shape[2], imgf.shape[3]).bool().cuda()) # torch.Size([1, 128, 36, 36])
bs, c, h, w = imgf.shape
imgf = imgf.flatten(2).permute(2, 0, 1)
# query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
pos = pos.flatten(2).permute(2, 0, 1)
for layer in self.layers:
query_embed = layer(query_embed, [imgf], pos=pos, memory_pos=[pos, pos])
query_embed = query_embed.permute(1, 2, 0).reshape(bs, c, h, w)
return query_embed
class TransEncoder(nn.Module):
def __init__(self, num_attn_layers, hidden_dim=128):
super(TransEncoder, self).__init__()
attn_layer = attnLayer(hidden_dim)
self.layers = _get_clones(attn_layer, num_attn_layers)
self.position_embedding = build_position_encoding(hidden_dim)
def forward(self, imgf):
pos = self.position_embedding(torch.ones(imgf.shape[0], imgf.shape[2], imgf.shape[3]).bool().cuda()) # torch.Size([1, 128, 36, 36])
bs, c, h, w = imgf.shape
imgf = imgf.flatten(2).permute(2, 0, 1)
pos = pos.flatten(2).permute(2, 0, 1)
for layer in self.layers:
imgf = layer(imgf, [imgf], pos=pos, memory_pos=[pos, pos])
imgf = imgf.permute(1, 2, 0).reshape(bs, c, h, w)
return imgf
class FlowHead(nn.Module):
def __init__(self, input_dim=128, hidden_dim=256):
super(FlowHead, self).__init__()
self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1)
self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
return self.conv2(self.relu(self.conv1(x)))
class UpdateBlock(nn.Module):
def __init__(self, hidden_dim=128):
super(UpdateBlock, self).__init__()
self.flow_head = FlowHead(hidden_dim, hidden_dim=256)
self.mask = nn.Sequential(
nn.Conv2d(hidden_dim, 256, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 64*9, 1, padding=0))
def forward(self, imgf, coords1):
mask = .25 * self.mask(imgf) # scale mask to balence gradients
dflow = self.flow_head(imgf)
coords1 = coords1 + dflow
return mask, coords1
def coords_grid(batch, ht, wd):
coords = torch.meshgrid(torch.arange(ht), torch.arange(wd))
coords = torch.stack(coords[::-1], dim=0).float()
return coords[None].repeat(batch, 1, 1, 1)
def upflow8(flow, mode='bilinear'):
new_size = (8 * flow.shape[2], 8 * flow.shape[3])
return 8 * F.interpolate(flow, size=new_size, mode=mode, align_corners=True)
class OverlapPatchEmbed(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
self.num_patches = self.H * self.W
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,
padding=(patch_size[0] // 2, patch_size[1] // 2))
self.norm = nn.LayerNorm(embed_dim)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
elif isinstance(m, nn.Conv2d):
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
fan_out //= m.groups
m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
if m.bias is not None:
m.bias.data.zero_()
def forward(self, x):
x = self.proj(x)
_, _, H, W = x.shape
x = x.flatten(2).transpose(1, 2)
x = self.norm(x)
return x, H, W
class GeoTr(nn.Module):
def __init__(self):
super(GeoTr, self).__init__()
self.hidden_dim = hdim = 256
| self.fnet = BasicEncoder(output_dim=hdim, norm_fn='instance') | 0 | 2023-10-17 11:06:30+00:00 | 4k |
zzbuzzard/stable-diffusion-infinite-scroll | sd_scroll.py | [
{
"identifier": "next_image",
"path": "util.py",
"snippet": "def next_image(pipe, image, base_size, prompt, shiftx, shifty, pipe_args):\n \"\"\"Given an image, uses inpainting to produce the next image (which overlaps with the previous image)\"\"\"\n assert image.size == (base_size, base_size)\n\n... | import torch
import numpy as np
import tkinter as tk
import time
import random
import argparse
import util
from diffusers import StableDiffusionInpaintPipeline
from PIL import Image
from multiprocessing import Process, Queue
from util import next_image
from slider import Slider | 2,006 |
parser = util.get_argparser()
parser.add_argument("-spd", "--speed", default=1., type=float,
help="Speed multiplier (between 0 and 1). A value of 1 causes images to be generated as fast as "
"possible. A value less than 1 leads to intentional breaks between generations to stop your "
"GPU exploding")
def draw_loop(queue, shiftx, shifty):
"""Repeatedly tells the slider to move, and notifies it when new images become available."""
queue.get() # wait from signal from update_loop to start
print("Starting draw")
start = time.time()
prev = start
while True:
if not queue.empty():
image, speed = queue.get()
slider.update(image, shiftx, shifty, speed)
t = time.time()
slider.move(t - prev)
prev = t
root.update()
def generate_loop(queue, start_image, prompts, pipe_args, shiftx, shifty, model, base_size, attn_slicing, speed_mul=1):
"""
Repeatedly computes new images to display using SD, and adds them to the queue.
If speed_mul < 1, we wait between generations to reduce GPU usage intensity.
"""
assert 0 < speed_mul <= 1
print("Loading SD...")
pipe = StableDiffusionInpaintPipeline.from_pretrained(
model,
revision="fp16",
torch_dtype=torch.float16,
)
pipe.safety_checker = None # A single black image causes a lot of problems for this scroller
pipe = pipe.to("cuda")
if attn_slicing:
pipe.enable_attention_slicing()
print("Loaded.")
if start_image is None:
prompt = random.choice(prompts)
print(f"No init image provided: generating from prompt '{prompt}'")
start_image = util.generate_image_with_inpainting_pipeline(pipe, prompt, base_size, pipe_args)
queue.put(0) # draw_loops waits for this to signal it should begin
front = start_image
while True:
prompt = random.choice(prompts)
print(f"Using prompt '{prompt}'")
start = time.time()
|
parser = util.get_argparser()
parser.add_argument("-spd", "--speed", default=1., type=float,
help="Speed multiplier (between 0 and 1). A value of 1 causes images to be generated as fast as "
"possible. A value less than 1 leads to intentional breaks between generations to stop your "
"GPU exploding")
def draw_loop(queue, shiftx, shifty):
"""Repeatedly tells the slider to move, and notifies it when new images become available."""
queue.get() # wait from signal from update_loop to start
print("Starting draw")
start = time.time()
prev = start
while True:
if not queue.empty():
image, speed = queue.get()
slider.update(image, shiftx, shifty, speed)
t = time.time()
slider.move(t - prev)
prev = t
root.update()
def generate_loop(queue, start_image, prompts, pipe_args, shiftx, shifty, model, base_size, attn_slicing, speed_mul=1):
"""
Repeatedly computes new images to display using SD, and adds them to the queue.
If speed_mul < 1, we wait between generations to reduce GPU usage intensity.
"""
assert 0 < speed_mul <= 1
print("Loading SD...")
pipe = StableDiffusionInpaintPipeline.from_pretrained(
model,
revision="fp16",
torch_dtype=torch.float16,
)
pipe.safety_checker = None # A single black image causes a lot of problems for this scroller
pipe = pipe.to("cuda")
if attn_slicing:
pipe.enable_attention_slicing()
print("Loaded.")
if start_image is None:
prompt = random.choice(prompts)
print(f"No init image provided: generating from prompt '{prompt}'")
start_image = util.generate_image_with_inpainting_pipeline(pipe, prompt, base_size, pipe_args)
queue.put(0) # draw_loops waits for this to signal it should begin
front = start_image
while True:
prompt = random.choice(prompts)
print(f"Using prompt '{prompt}'")
start = time.time() | front = next_image(pipe, image=front, base_size=base_size, prompt=prompt, shiftx=shiftx, shifty=shifty, | 0 | 2023-10-15 14:43:52+00:00 | 4k |
MaxDude132/django-register-field | tests/models.py | [
{
"identifier": "Register",
"path": "django_register/base.py",
"snippet": "class Register:\n def __init__(self):\n self._key_to_class = {}\n self._class_to_key = {}\n\n def register(self, klass, db_key=None):\n if db_key is None:\n try:\n db_key = kla... | from dataclasses import dataclass
from django.db import models
from django_register import Register, RegisterChoices, RegisterField | 1,625 | # Standard libraries
# Django
# django_register
@dataclass(unsafe_hash=True)
class CountryInfo:
population: int
capital: str
class CountryChoices(RegisterChoices):
CANADA = CountryInfo(population=37_742_154, capital="Ottawa")
FRANCE = CountryInfo(population=65_273_511, capital="Paris")
GERMANY = CountryInfo(population=83_783_942, capital="Berlin")
UNITED_STATES = CountryInfo(population=331_900_000, capital="Washington")
@dataclass(unsafe_hash=True)
class ContinentInfo:
label: str
@dataclass(unsafe_hash=True)
class FoodInfo:
verbose_name: str
food_register = Register()
food_register.register(FoodInfo("Pizza"), db_key="pizza")
@dataclass(unsafe_hash=True)
class CarCompanies:
verbose_name: str
cars_register = Register()
class ContinentChoices(RegisterChoices):
AMERICA = ContinentInfo(label="America")
EUROPE = ContinentInfo(label="Europe")
class City(models.Model):
label = models.CharField(max_length=50)
| # Standard libraries
# Django
# django_register
@dataclass(unsafe_hash=True)
class CountryInfo:
population: int
capital: str
class CountryChoices(RegisterChoices):
CANADA = CountryInfo(population=37_742_154, capital="Ottawa")
FRANCE = CountryInfo(population=65_273_511, capital="Paris")
GERMANY = CountryInfo(population=83_783_942, capital="Berlin")
UNITED_STATES = CountryInfo(population=331_900_000, capital="Washington")
@dataclass(unsafe_hash=True)
class ContinentInfo:
label: str
@dataclass(unsafe_hash=True)
class FoodInfo:
verbose_name: str
food_register = Register()
food_register.register(FoodInfo("Pizza"), db_key="pizza")
@dataclass(unsafe_hash=True)
class CarCompanies:
verbose_name: str
cars_register = Register()
class ContinentChoices(RegisterChoices):
AMERICA = ContinentInfo(label="America")
EUROPE = ContinentInfo(label="Europe")
class City(models.Model):
label = models.CharField(max_length=50) | country = RegisterField( | 2 | 2023-10-23 18:11:08+00:00 | 4k |
hsouri/bob-classification | timm_dataset.py | [
{
"identifier": "INAT2019",
"path": "datasets/inat_loader.py",
"snippet": "class INAT2019(data.Dataset):\n def __init__(self, root, mode='train', year=\"2019\", transform=None):\n # load annotations\n ann_file = os.path.join(root, f\"{mode}{year}.json\")\n with open(ann_file) as ... | from datasets.transfer_cls_datasets import *
from timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset
from wilds import get_dataset
from datasets.inat_loader import INAT2019, INAT2021
import wilds
import torchvision.transforms as transforms | 2,833 |
transfer_datasets = {
'flower102': 'Flower102',
'aircraft': 'Aircraft',
# 'birdsnap': 'Birdsnap',
'dtd': 'DTD',
'voc2007': 'VOC2007',
'pets': 'Pets',
'sun397': 'SUN397',
'cars': 'Cars',
'food101': 'Food101',
'caltech101': 'Caltech101',
'cifar10': 'Cifar10',
'cifar100': 'Cifar100',
'eurosat': 'eurosat'
}
wilds_group_list = {
'iwildcam': 'location',
'fmow': 'region',
'globalwheat': 'location',
'camelyon17': 'hospital',
'poverty': 'batch',
}
num_classes = {
"inat2021": 10000,
"inat2019": 1010,
"imagenet": 1000,
"cifar10": 10,
"cifar100": 100,
"flower102": 102,
"aircraft": 100,
"eurosat": 10,
"semiimagenet": 1000,
}
def create_other_dataset(
name,
root,
split='validation',
search_split=True,
class_map=None,
load_bytes=False,
is_training=False,
download=False,
batch_size=None,
seed=42,
repeats=0,
group=None,
domain=None,
json_path=None,
n_shot=None,
**kwargs
):
""" Dataset for transfer learning and wilds
Args:
name: dataset name, empty is okay for folder based datasets
root: root folder of dataset (all)
split: dataset split (all)
search_split: search for split specific child fold from root so one can specify
`imagenet/` instead of `/imagenet/val`, etc on cmd line / config. (folder, torch/folder)
class_map: specify class -> index mapping via text file or dict (folder)
load_bytes: load data, return images as undecoded bytes (folder)
download: download dataset if not present and supported (HFDS, TFDS, torch)
is_training: create dataset in train mode, this is different from the split.
For Iterable / TDFS it enables shuffle, ignored for other datasets. (TFDS, WDS)
batch_size: batch size hint for (TFDS, WDS)
seed: seed for iterable datasets (TFDS, WDS)
repeats: dataset repeats per iteration i.e. epoch (TFDS, WDS)
group: whether to specific a domain in wilds
domain: which specific domain is used in wilds
json_path: json file (of train/val split)
n_shot: if integer: n_shot samples per class; if float: means the percentage
**kwargs: other args to pass to dataset
Returns:
Dataset object
"""
name = name.lower()
if name in transfer_datasets:
ds = get_transfer_datasets(name, root, 'train' if split=='train' else 'val', n_shot=n_shot, json_path=json_path)
elif name in wilds.supported_datasets:
dataset = get_dataset(dataset=name, download=False, root_dir=root, debug=True)
if group is not None:
group = wilds_group_list[name]
ds = dataset.get_subset(split, group=group, domain=domain)
elif name == 'inat2019':
ds = INAT2019(root, mode='train' if split=='train' else 'val')
elif name == 'inat2021':
# root: /fs/vulcan-datasets/inat_comp_2021
|
transfer_datasets = {
'flower102': 'Flower102',
'aircraft': 'Aircraft',
# 'birdsnap': 'Birdsnap',
'dtd': 'DTD',
'voc2007': 'VOC2007',
'pets': 'Pets',
'sun397': 'SUN397',
'cars': 'Cars',
'food101': 'Food101',
'caltech101': 'Caltech101',
'cifar10': 'Cifar10',
'cifar100': 'Cifar100',
'eurosat': 'eurosat'
}
wilds_group_list = {
'iwildcam': 'location',
'fmow': 'region',
'globalwheat': 'location',
'camelyon17': 'hospital',
'poverty': 'batch',
}
num_classes = {
"inat2021": 10000,
"inat2019": 1010,
"imagenet": 1000,
"cifar10": 10,
"cifar100": 100,
"flower102": 102,
"aircraft": 100,
"eurosat": 10,
"semiimagenet": 1000,
}
def create_other_dataset(
name,
root,
split='validation',
search_split=True,
class_map=None,
load_bytes=False,
is_training=False,
download=False,
batch_size=None,
seed=42,
repeats=0,
group=None,
domain=None,
json_path=None,
n_shot=None,
**kwargs
):
""" Dataset for transfer learning and wilds
Args:
name: dataset name, empty is okay for folder based datasets
root: root folder of dataset (all)
split: dataset split (all)
search_split: search for split specific child fold from root so one can specify
`imagenet/` instead of `/imagenet/val`, etc on cmd line / config. (folder, torch/folder)
class_map: specify class -> index mapping via text file or dict (folder)
load_bytes: load data, return images as undecoded bytes (folder)
download: download dataset if not present and supported (HFDS, TFDS, torch)
is_training: create dataset in train mode, this is different from the split.
For Iterable / TDFS it enables shuffle, ignored for other datasets. (TFDS, WDS)
batch_size: batch size hint for (TFDS, WDS)
seed: seed for iterable datasets (TFDS, WDS)
repeats: dataset repeats per iteration i.e. epoch (TFDS, WDS)
group: whether to specific a domain in wilds
domain: which specific domain is used in wilds
json_path: json file (of train/val split)
n_shot: if integer: n_shot samples per class; if float: means the percentage
**kwargs: other args to pass to dataset
Returns:
Dataset object
"""
name = name.lower()
if name in transfer_datasets:
ds = get_transfer_datasets(name, root, 'train' if split=='train' else 'val', n_shot=n_shot, json_path=json_path)
elif name in wilds.supported_datasets:
dataset = get_dataset(dataset=name, download=False, root_dir=root, debug=True)
if group is not None:
group = wilds_group_list[name]
ds = dataset.get_subset(split, group=group, domain=domain)
elif name == 'inat2019':
ds = INAT2019(root, mode='train' if split=='train' else 'val')
elif name == 'inat2021':
# root: /fs/vulcan-datasets/inat_comp_2021 | ds = INAT2021(root, | 1 | 2023-10-20 16:28:17+00:00 | 4k |
Salz0/telegram_flea | main.py | [
{
"identifier": "User",
"path": "models.py",
"snippet": "class User(BaseModel):\n \"\"\"\n The model for the Telegram user.\n\n This model stores all the information about the user.\n It is also used to store all the authentication-related information.\n \"\"\"\n\n id = fields.BigIntFi... | import os
import aiogram
from asyncio import gather
from pathlib import Path
from aiogram import types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.i18n import I18nMiddleware
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import CommandStart
from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.types.callback_query import CallbackQuery
from dotenv import load_dotenv
from models import User, Message
from po_compile import compile_all_languages
from utils import tortoise_orm
from utils.data_validation import validate_photo_as_document
from utils.generalization import create_message_instance
from utils.loguru_logging import logger
from utils.redis_storage import redis_storage
from keyboards import (
start_keyboard,
sell_keyboard,
cancel_listing_keyboard,
moderator_keyboard,
empty_inline_keyboard,
) | 2,177 |
load_dotenv()
compile_all_languages()
bot = aiogram.Bot(os.environ["TELEGRAM_BOT_TOKEN"])
dp = aiogram.Dispatcher(bot, storage=MemoryStorage())
BASE_DIR = Path(__file__).parent
LOCALES_DIR = BASE_DIR / "locales"
BOT_LANGUAGE = os.environ.get("BOT_LANGUAGE")
i18n = I18nMiddleware("bot", LOCALES_DIR, default="en")
dp.middleware.setup(i18n)
if BOT_LANGUAGE not in i18n.locales:
logger.warning("language is not supported")
BOT_LANGUAGE = "en"
# Define states
class SellItem(StatesGroup):
waiting_description = State()
waiting_for_price = State()
waiting_for_photo = State()
@dp.message_handler(CommandStart(), state="*")
async def start(message: types.Message):
user_dict = message.from_user.to_python()
await User.get_or_create(
id=message.from_user.id,
username=user_dict.get("username"),
first_name=user_dict.get("first_name"),
last_name=user_dict.get("last_name"),
is_bot=message.from_user.is_bot,
phone_number=user_dict.get("phone_number"),
language_code=message.from_user.language_code,
start_payload=message.get_args(),
)
await message.answer(
i18n.gettext("bot.start_message", locale=BOT_LANGUAGE),
reply_markup=start_keyboard, # Attach the reply keyboard here
)
@dp.message_handler(
lambda message: message.text.lower()
== i18n.gettext("bot.sell_keyboard_cancel", locale=BOT_LANGUAGE).lower(),
state="*",
)
async def cancel(message: types.Message, state: FSMContext):
await gather(
state.finish(),
create_message_instance(message),
message.reply(
i18n.gettext("bot.sell_keyboard_canceled", locale=BOT_LANGUAGE),
reply_markup=start_keyboard, # Switch back to the start keyboard
),
)
@dp.message_handler(
lambda message: message.text == i18n.gettext("bot.start_keyboard_help", locale=BOT_LANGUAGE),
state="*",
)
async def help_command(message: aiogram.types.Message):
support_username = os.environ.get("SUPPORT_USERNAME")
# Assuming `get_or_create_user` is a function that handles User instances.
help_text = i18n.gettext("bot.help_message", locale=BOT_LANGUAGE).format(
support_username=support_username
)
await gather(
create_message_instance(message),
message.reply(help_text, reply_markup=start_keyboard),
)
@dp.message_handler(
lambda message: message.text == i18n.gettext("bot.start_keyboard_sell", locale=BOT_LANGUAGE),
state="*",
)
async def enter_sell(message: aiogram.types.Message):
await SellItem.waiting_description.set(),
await gather(
create_message_instance(message),
message.reply(
i18n.gettext("bot.enter_sell_description", locale=BOT_LANGUAGE),
|
load_dotenv()
compile_all_languages()
bot = aiogram.Bot(os.environ["TELEGRAM_BOT_TOKEN"])
dp = aiogram.Dispatcher(bot, storage=MemoryStorage())
BASE_DIR = Path(__file__).parent
LOCALES_DIR = BASE_DIR / "locales"
BOT_LANGUAGE = os.environ.get("BOT_LANGUAGE")
i18n = I18nMiddleware("bot", LOCALES_DIR, default="en")
dp.middleware.setup(i18n)
if BOT_LANGUAGE not in i18n.locales:
logger.warning("language is not supported")
BOT_LANGUAGE = "en"
# Define states
class SellItem(StatesGroup):
waiting_description = State()
waiting_for_price = State()
waiting_for_photo = State()
@dp.message_handler(CommandStart(), state="*")
async def start(message: types.Message):
user_dict = message.from_user.to_python()
await User.get_or_create(
id=message.from_user.id,
username=user_dict.get("username"),
first_name=user_dict.get("first_name"),
last_name=user_dict.get("last_name"),
is_bot=message.from_user.is_bot,
phone_number=user_dict.get("phone_number"),
language_code=message.from_user.language_code,
start_payload=message.get_args(),
)
await message.answer(
i18n.gettext("bot.start_message", locale=BOT_LANGUAGE),
reply_markup=start_keyboard, # Attach the reply keyboard here
)
@dp.message_handler(
lambda message: message.text.lower()
== i18n.gettext("bot.sell_keyboard_cancel", locale=BOT_LANGUAGE).lower(),
state="*",
)
async def cancel(message: types.Message, state: FSMContext):
await gather(
state.finish(),
create_message_instance(message),
message.reply(
i18n.gettext("bot.sell_keyboard_canceled", locale=BOT_LANGUAGE),
reply_markup=start_keyboard, # Switch back to the start keyboard
),
)
@dp.message_handler(
lambda message: message.text == i18n.gettext("bot.start_keyboard_help", locale=BOT_LANGUAGE),
state="*",
)
async def help_command(message: aiogram.types.Message):
support_username = os.environ.get("SUPPORT_USERNAME")
# Assuming `get_or_create_user` is a function that handles User instances.
help_text = i18n.gettext("bot.help_message", locale=BOT_LANGUAGE).format(
support_username=support_username
)
await gather(
create_message_instance(message),
message.reply(help_text, reply_markup=start_keyboard),
)
@dp.message_handler(
lambda message: message.text == i18n.gettext("bot.start_keyboard_sell", locale=BOT_LANGUAGE),
state="*",
)
async def enter_sell(message: aiogram.types.Message):
await SellItem.waiting_description.set(),
await gather(
create_message_instance(message),
message.reply(
i18n.gettext("bot.enter_sell_description", locale=BOT_LANGUAGE), | reply_markup=sell_keyboard, | 8 | 2023-10-19 17:28:55+00:00 | 4k |
RobertCsordas/moe_layer | triton_src/moe_layer/moe_layer_simple.py | [
{
"identifier": "cvmm",
"path": "triton_src/moe_layer/cvmm.py",
"snippet": "def cvmm(x: torch.Tensor, sel: Union[torch.Tensor, CVMMSel], keys: torch.Tensor):\n if not isinstance(sel, CVMMSel):\n sel = cvmm_prepare_sel(sel, keys.shape[0])\n\n return CVMM.apply(x, sel.sel_index, sel.sel, keys... | import torch
import torch.distributed
import torch.nn.functional as F
import math
from typing import Tuple, List, Optional
from .cvmm import cvmm, cvmm_prepare_sel2, CVMMSel | 1,944 | activation_after_topk: bool = False,
activation=F.relu,
bias: bool = False, v_dim: Optional[int] = None,
sinkhorn_n_iters: int = 3, expert_dropout: float = 0.0,
weight_std_scale: float = 1.0):
super().__init__()
self.k_dim = dmodel
self.v_dim = v_dim if v_dim is not None else dmodel
self.n_experts = n_experts
self.expert_size = expert_size
self.size = self.n_experts * self.expert_size
self.dropout = dropout
self.selection_mode = selection_mode
self.k_vec_dim = self.k_dim
self.n_heads = k
self.activation_after_topk = activation_after_topk
self.activation = activation
self.sinkhorn_n_iters = sinkhorn_n_iters
self.expert_dropout = expert_dropout
if self.selection_mode not in {"softmax", "sigmoid", "sinkmoid"}:
raise ValueError(f"Unknown selection mode {self.selection_mode}")
self.keys = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim, self.expert_size))
self.values = torch.nn.Parameter(torch.empty(self.n_experts, self.expert_size, self.v_dim))
self.expert_sel = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim))
torch.nn.init.normal_(self.keys, std=dmodel ** -0.5 * weight_std_scale)
torch.nn.init.normal_(self.values, std=self.size ** -0.5 * weight_std_scale)
torch.nn.init.normal_(self.expert_sel, std=self.k_vec_dim ** -0.5 * weight_std_scale)
if bias:
self.bias = torch.nn.Parameter(torch.zeros(self.n_experts, self.expert_size))
self.o_bias = torch.nn.Parameter(torch.zeros(self.v_dim))
else:
self.bias = None
self.o_bias = None
self.renorm_keep_std(self.expert_sel, dim=1)
def renorm_keep_std(self, weight: torch.Tensor, dim: int = 0):
with torch.no_grad():
std = weight.std()
weight.div_(weight.norm(dim=dim, keepdim=True))
weight.mul_(std / weight.std())
def entropy_reg(self, sel: torch.Tensor) -> float:
# Everything is done in log scale
sel = sel.flatten(0, -2)
sel = F.log_softmax(sel, dim=-1)
sel = log_mean(sel, -2)
return - entropy_l(sel).mean()
def compute_scores(self, input: torch.Tensor, index: CVMMSel) -> torch.Tensor:
scores = cvmm(input, index, self.keys)
if self.bias is not None:
scores = scores + self.bias[index.raw_sel]
scores = self.activation(scores)
if self.dropout > 0:
# Standard dropout on the "up-projected scores"
scores = F.dropout(scores, self.dropout, training=self.training)
return scores
def sel_activation(self, sel: torch.Tensor) -> torch.Tensor:
if self.selection_mode == "sinkmoid":
if self.training:
with torch.no_grad():
sel = self.sinkhorn_unnorm(sel)
else:
sel = torch.sigmoid(sel)
elif self.selection_mode == "sigmoid":
sel = torch.sigmoid(sel)
elif self.selection_mode == "softmax":
sel = F.softmax(sel, dim=-1)
else:
assert False
return sel
def sinkhorn_unnorm(self, x: torch.Tensor) -> torch.Tensor:
# Based on https://arxiv.org/abs/2202.01169. Unnormalized verison
A, B = x.shape[-2:]
a = torch.zeros_like(x[..., 0, :])
b = torch.zeros_like(x[..., 0])
for _ in range(self.sinkhorn_n_iters):
b = math.log(A) - (x - a[..., None, :]).logsumexp(-1)
if torch.distributed.is_initialized():
a = math.log(B) - dist_logsumexp(x - b[..., None], -2)
else:
a = math.log(B) - (x - b[..., None]).logsumexp(-2)
return (a[..., None, :] + b[..., None] + x).exp()
def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# Selection score calculation
sel = sel_raw = F.linear(input, self.expert_sel, None)
reg_loss = self.entropy_reg(sel_raw)
# Selection activation and topk
if (not self.activation_after_topk) or (self.selection_mode == "sinkmoid"):
# Sinkhorn should be always applied before top-k
sel = self.sel_activation(sel)
if self.training and self.expert_dropout > 0:
mask = torch.rand_like(sel) < self.expert_dropout
sel = sel.masked_fill(mask, float("-inf"))
sel_val, sel_index = sel.topk(self.n_heads, dim=-1, sorted=False)
if self.activation_after_topk or (self.selection_mode == "sinkmoid"):
sel_val = torch.gather(sel_raw, -1, sel_index)
# for sinkmoid, the score is always calculated by a sigmoid
sel_val = torch.sigmoid(sel_val) if self.selection_mode == "sinkmoid" else self.sel_activation(sel_val)
# Preprocess the selection indices. They will be needed for both layers and save some time
|
def dist_logsumexp(x: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor:
# Calculate numerically stable distributed logsumexp
xmax = x.max(dim=dim, keepdim=True).values
torch.distributed.all_reduce(xmax, op=torch.distributed.ReduceOp.MAX)
xe = (x - xmax).exp().sum(dim=dim, keepdim=True)
torch.distributed.all_reduce(xe, op=torch.distributed.ReduceOp.SUM)
res = (xmax + xe.log())
if not keepdim:
res = res.squeeze(dim)
return res
def log_mean(x: torch.Tensor, dim: int = 0):
if torch.distributed.is_initialized():
xlse = dist_logsumexp(x, dim=dim)
# Normalize
n = torch.tensor(x.shape[dim]).to(x.device)
torch.distributed.all_reduce(n, op=torch.distributed.ReduceOp.SUM)
return xlse - n.log()
else:
return x.logsumexp(dim) - math.log(x.shape[dim])
def entropy_l(l: torch.Tensor) -> torch.Tensor:
return - (l * l.exp()).sum(-1)
class MoE(torch.nn.Module):
def __init__(self, dmodel: int, n_experts: int, expert_size: int, k: int,
dropout: float = 0, selection_mode: str = "sigmoid",
activation_after_topk: bool = False,
activation=F.relu,
bias: bool = False, v_dim: Optional[int] = None,
sinkhorn_n_iters: int = 3, expert_dropout: float = 0.0,
weight_std_scale: float = 1.0):
super().__init__()
self.k_dim = dmodel
self.v_dim = v_dim if v_dim is not None else dmodel
self.n_experts = n_experts
self.expert_size = expert_size
self.size = self.n_experts * self.expert_size
self.dropout = dropout
self.selection_mode = selection_mode
self.k_vec_dim = self.k_dim
self.n_heads = k
self.activation_after_topk = activation_after_topk
self.activation = activation
self.sinkhorn_n_iters = sinkhorn_n_iters
self.expert_dropout = expert_dropout
if self.selection_mode not in {"softmax", "sigmoid", "sinkmoid"}:
raise ValueError(f"Unknown selection mode {self.selection_mode}")
self.keys = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim, self.expert_size))
self.values = torch.nn.Parameter(torch.empty(self.n_experts, self.expert_size, self.v_dim))
self.expert_sel = torch.nn.Parameter(torch.empty(self.n_experts, self.k_vec_dim))
torch.nn.init.normal_(self.keys, std=dmodel ** -0.5 * weight_std_scale)
torch.nn.init.normal_(self.values, std=self.size ** -0.5 * weight_std_scale)
torch.nn.init.normal_(self.expert_sel, std=self.k_vec_dim ** -0.5 * weight_std_scale)
if bias:
self.bias = torch.nn.Parameter(torch.zeros(self.n_experts, self.expert_size))
self.o_bias = torch.nn.Parameter(torch.zeros(self.v_dim))
else:
self.bias = None
self.o_bias = None
self.renorm_keep_std(self.expert_sel, dim=1)
def renorm_keep_std(self, weight: torch.Tensor, dim: int = 0):
with torch.no_grad():
std = weight.std()
weight.div_(weight.norm(dim=dim, keepdim=True))
weight.mul_(std / weight.std())
def entropy_reg(self, sel: torch.Tensor) -> float:
# Everything is done in log scale
sel = sel.flatten(0, -2)
sel = F.log_softmax(sel, dim=-1)
sel = log_mean(sel, -2)
return - entropy_l(sel).mean()
def compute_scores(self, input: torch.Tensor, index: CVMMSel) -> torch.Tensor:
scores = cvmm(input, index, self.keys)
if self.bias is not None:
scores = scores + self.bias[index.raw_sel]
scores = self.activation(scores)
if self.dropout > 0:
# Standard dropout on the "up-projected scores"
scores = F.dropout(scores, self.dropout, training=self.training)
return scores
def sel_activation(self, sel: torch.Tensor) -> torch.Tensor:
if self.selection_mode == "sinkmoid":
if self.training:
with torch.no_grad():
sel = self.sinkhorn_unnorm(sel)
else:
sel = torch.sigmoid(sel)
elif self.selection_mode == "sigmoid":
sel = torch.sigmoid(sel)
elif self.selection_mode == "softmax":
sel = F.softmax(sel, dim=-1)
else:
assert False
return sel
def sinkhorn_unnorm(self, x: torch.Tensor) -> torch.Tensor:
# Based on https://arxiv.org/abs/2202.01169. Unnormalized verison
A, B = x.shape[-2:]
a = torch.zeros_like(x[..., 0, :])
b = torch.zeros_like(x[..., 0])
for _ in range(self.sinkhorn_n_iters):
b = math.log(A) - (x - a[..., None, :]).logsumexp(-1)
if torch.distributed.is_initialized():
a = math.log(B) - dist_logsumexp(x - b[..., None], -2)
else:
a = math.log(B) - (x - b[..., None]).logsumexp(-2)
return (a[..., None, :] + b[..., None] + x).exp()
def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# Selection score calculation
sel = sel_raw = F.linear(input, self.expert_sel, None)
reg_loss = self.entropy_reg(sel_raw)
# Selection activation and topk
if (not self.activation_after_topk) or (self.selection_mode == "sinkmoid"):
# Sinkhorn should be always applied before top-k
sel = self.sel_activation(sel)
if self.training and self.expert_dropout > 0:
mask = torch.rand_like(sel) < self.expert_dropout
sel = sel.masked_fill(mask, float("-inf"))
sel_val, sel_index = sel.topk(self.n_heads, dim=-1, sorted=False)
if self.activation_after_topk or (self.selection_mode == "sinkmoid"):
sel_val = torch.gather(sel_raw, -1, sel_index)
# for sinkmoid, the score is always calculated by a sigmoid
sel_val = torch.sigmoid(sel_val) if self.selection_mode == "sinkmoid" else self.sel_activation(sel_val)
# Preprocess the selection indices. They will be needed for both layers and save some time | sel_indices = cvmm_prepare_sel2(sel_index.int()) | 1 | 2023-10-16 11:00:47+00:00 | 4k |
BurgerBurgerBurger/AA | model.py | [
{
"identifier": "process_long_input",
"path": "long_seq.py",
"snippet": "def process_long_input(model, input_ids, attention_mask, start_tokens, end_tokens):\n # Split the input to 2 overlapping chunks. Now BERT can encode inputs of which the length are up to 1024.\n n, c = input_ids.size()\n st... | import torch
import torch.nn as nn
import torch.nn.functional as F
from opt_einsum import contract
from long_seq import process_long_input
from losses import ATLoss
from graph import AttentionGCNLayer | 2,125 |
class DocREModel(nn.Module):
def __init__(self, args, config, model, tokenizer,
emb_size=768, block_size=64, num_labels=-1,
max_sent_num=25, evi_thresh=0.2):
super().__init__()
self.config = config
self.model = model
self.tokenizer = tokenizer
self.hidden_size = config.hidden_size
|
class DocREModel(nn.Module):
def __init__(self, args, config, model, tokenizer,
emb_size=768, block_size=64, num_labels=-1,
max_sent_num=25, evi_thresh=0.2):
super().__init__()
self.config = config
self.model = model
self.tokenizer = tokenizer
self.hidden_size = config.hidden_size
| self.loss_fnt = ATLoss() | 1 | 2023-10-20 05:53:25+00:00 | 4k |
hnesk/flipper-raw-rfid | tests/test_rifl_file.py | [
{
"identifier": "Rifl",
"path": "flipper_raw_rfid/rifl.py",
"snippet": "class Rifl:\n \"\"\"\n A raw rfid file from flipper (xyz.ask.raw or xyz.psk.raw)\n\n \"\"\"\n header: RiflHeader\n \"\"\" The header of the file \"\"\"\n\n pulse_and_durations: npt.NDArray[numpy.int64] = None\n ... | from io import BytesIO
from pathlib import Path
from unittest import TestCase
from numpy.testing import assert_array_equal
from flipper_raw_rfid.rifl import Rifl, RiflHeader
import numpy | 1,690 |
TEST_BASE_PATH = Path(__file__).parent.absolute()
class RiflFileTest(TestCase):
example_bytes = bytes.fromhex('f101a903ae028506a604fb05bb028706ad04b90404c403')
example_ints = [241, 425, 302, 773, 550, 763, 315, 775, 557, 569, 4, 452]
def test_header_to_bytes_and_back(self):
|
TEST_BASE_PATH = Path(__file__).parent.absolute()
class RiflFileTest(TestCase):
example_bytes = bytes.fromhex('f101a903ae028506a604fb05bb028706ad04b90404c403')
example_ints = [241, 425, 302, 773, 550, 763, 315, 775, 557, 569, 4, 452]
def test_header_to_bytes_and_back(self): | header = RiflHeader(1, 125_000, 0.5, 2048) | 1 | 2023-10-20 13:06:00+00:00 | 4k |
xingchenshanyao/YOLOP-E | lib/dataset/DemoDataset.py | [
{
"identifier": "clean_str",
"path": "lib/utils/utils.py",
"snippet": "def clean_str(s):\n # Cleans a string by replacing special characters with underscore _\n return re.sub(pattern=\"[|@#!¡·$€%&()=?¿^*;:,¨´><+]\", repl=\"_\", string=s)"
},
{
"identifier": "letterbox_for_img",
"path":... | import glob
import os
import random
import shutil
import time
import cv2
import math
import numpy as np
import torch
from pathlib import Path
from threading import Thread
from PIL import Image, ExifTags
from torch.utils.data import Dataset
from tqdm import tqdm
from ..utils import letterbox_for_img, clean_str | 1,794 |
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv']
class LoadImages: # for inference
def __init__(self, path, img_size=640):
p = str(Path(path)) # os-agnostic
p = os.path.abspath(p) # absolute path
if '*' in p:
files = sorted(glob.glob(p, recursive=True)) # glob
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
elif os.path.isfile(p):
files = [p] # files
else:
raise Exception('ERROR: %s does not exist' % p)
images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = 'images'
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, 'No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s' % \
(p, img_formats, vid_formats)
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
h0, w0 = img0.shape[:2]
self.frame += 1
print('\n video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nf, self.frame, self.nframes, path), end='')
else:
# Read image
self.count += 1
img0 = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # BGR
#img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)
assert img0 is not None, 'Image Not Found ' + path
print('image %g/%g %s: \n' % (self.count, self.nf, path), end='')
h0, w0 = img0.shape[:2]
# Padded resize # 填充尺寸,640*360*3 -> 640*384*3
img, ratio, pad = letterbox_for_img(img0, new_shape=self.img_size, auto=True)
h, w = img.shape[:2] # h = 384, w = 640
shapes = (h0, w0), ((h / h0, w / w0), pad)
# Convert
#img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
# cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image
return path, img, img0, self.cap, shapes
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf # number of files
class LoadStreams: # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=640, auto=True):
self.mode = 'stream'
self.img_size = img_size
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
|
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv']
class LoadImages: # for inference
def __init__(self, path, img_size=640):
p = str(Path(path)) # os-agnostic
p = os.path.abspath(p) # absolute path
if '*' in p:
files = sorted(glob.glob(p, recursive=True)) # glob
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
elif os.path.isfile(p):
files = [p] # files
else:
raise Exception('ERROR: %s does not exist' % p)
images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = 'images'
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, 'No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s' % \
(p, img_formats, vid_formats)
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
h0, w0 = img0.shape[:2]
self.frame += 1
print('\n video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nf, self.frame, self.nframes, path), end='')
else:
# Read image
self.count += 1
img0 = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) # BGR
#img0 = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)
assert img0 is not None, 'Image Not Found ' + path
print('image %g/%g %s: \n' % (self.count, self.nf, path), end='')
h0, w0 = img0.shape[:2]
# Padded resize # 填充尺寸,640*360*3 -> 640*384*3
img, ratio, pad = letterbox_for_img(img0, new_shape=self.img_size, auto=True)
h, w = img.shape[:2] # h = 384, w = 640
shapes = (h0, w0), ((h / h0, w / w0), pad)
# Convert
#img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
# cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image
return path, img, img0, self.cap, shapes
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf # number of files
class LoadStreams: # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=640, auto=True):
self.mode = 'stream'
self.img_size = img_size
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n | self.sources = [clean_str(x) for x in sources] # clean source names for later | 0 | 2023-10-24 02:08:25+00:00 | 4k |
giulio98/functional-diffusion-processes | src/functional_diffusion_processes/models/base_maml.py | [
{
"identifier": "clip_learning_rates",
"path": "src/functional_diffusion_processes/utils/common.py",
"snippet": "def clip_learning_rates(params):\n \"\"\"Clip the learning rates to the range [0, 1].\n\n Args:\n params: A dictionary of parameters.\n\n Returns:\n A dictionary contai... | import abc
import logging
import flax.linen as nn
import hydra
import jax
import jax.numpy as jnp
import optax
from functools import partial
from typing import Any, Callable, Mapping, Optional, Tuple, TypeVar
from flax.core import FrozenDict, unfreeze
from omegaconf import DictConfig
from ..utils.common import clip_learning_rates, make_coordinates, merge_learning_rates, separate_learning_rates | 3,321 | ) -> Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]:
"""Apply the (outer) forward pass and update the model parameters.
Args:
rng (jax.random.PRNGKey): Random key.
params (Params): Initial model parameters.
batch_input (jnp.ndarray): Input tensor to the model.
batch_corrupted (jnp.ndarray): Corrupted version of the output tensor.
psm (jnp.ndarray): Power special matrix.
Returns:
Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]: A tuple containing a new random key, the model output, and the inner loss.
"""
params_adapted, loss_inner = update_inner_fn(params, batch_input, batch_corrupted, psm)
model_output = jax.vmap(self.apply)(params_adapted, batch_input)
return rng, model_output, loss_inner
return apply_forward
def make_update_inner_fn(
self, optimizer_inner: optax.GradientTransformation, n_steps: int
) -> Callable[[Params, jnp.ndarray, jnp.ndarray, jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]]:
"""Create a function to update model parameters for inner optimization.
This method creates a function that performs the inner optimization updates
during the meta-training phase, which is a key component of the MAML algorithm.
Args:
optimizer_inner (optax.GradientTransformation): The optimizer used for inner optimization.
n_steps (int): The number of optimization steps.
Returns:
Callable[..., Tuple[jnp.ndarray, jnp.ndarray]]: Function to update model parameters for inner optimization.
"""
@partial(jax.vmap, in_axes=0)
@partial(jax.grad, has_aux=True)
def loss_inner_fn(params_i: Params, batch_input: T, y_corrupted: T, psm: T) -> T:
"""Computes the loss for inner optimization.
This inner method computes the loss for inner optimization by comparing
the model's output against the corrupted batch using mean square error.
The method is vectorized using JAX's vmap function for efficiency.
Args:
params_i (Params): Model parameters.
batch_input (T): Input batch.
y_corrupted (T): Corrupted batch.
psm (T): Power special matrix.
Returns:
T: Loss value.
"""
c = y_corrupted.shape[-1]
model_output = self.apply(params_i, batch_input)
if len(psm.shape) == 3:
model_output_freq = jnp.fft.fft2(model_output.reshape(*psm.shape[:-1], c), norm="ortho", axes=(0, 1))
y_corrupted_freq = jnp.fft.fft2(y_corrupted.reshape(*psm.shape[:-1], c), norm="ortho", axes=(0, 1))
else:
model_output_freq = jnp.fft.fft(model_output.reshape(*psm.shape[:-1], c), norm="ortho", axis=0)
y_corrupted_freq = jnp.fft.fft(y_corrupted.reshape(*psm.shape[:-1], c), norm="ortho", axis=0)
mse = mean_square_error(
y_corrupted_freq.reshape(-1, c),
model_output_freq.reshape(-1, c),
psm.reshape(-1, 1),
)
loss: jnp.ndarray = jnp.mean(mse)
return loss, loss
def apply_inner_forward(
params: Params, batch_input: jnp.ndarray, batch_corrupted: jnp.ndarray, psm: jnp.ndarray
):
"""Applies inner forward pass for updating model parameters.
Args:
params (Params): Model parameters.
batch_input (jnp.ndarray): Input batch.
batch_corrupted (jnp.ndarray): Corrupted batch.
psm (jnp.ndarray): Power special matrix.
Returns:
Tuple[jnp.ndarray, jnp.ndarray]: Updated model parameters and inner loss.
"""
def inner_opt_loop(
carry: Tuple[Params, jnp.ndarray, int, Any, jnp.ndarray], _: None
) -> Tuple[Tuple[Params, jnp.ndarray, int, Any, jnp.ndarray], None]:
"""Inner optimization loop for updating model parameters.
Args:
carry (Tuple[Params, jnp.ndarray, int, optax.OptState, jnp.ndarray]): Tuple containing model parameters,
loss vector, iteration index, optimizer state, and corrupted batch.
_ (None): A throwaway variable as no second argument is used in this function.
Returns:
Tuple[Params, jnp.ndarray, int, optax.OptState, jnp.ndarray]: Updated tuple with new model parameters,
updated loss vector, incremented iteration index, updated optimizer state, and corrupted batch.
"""
params_i, loss_inner_vec, it, opt_inner_state_params, batch_corrupted_i = carry
grad_params, (loss) = loss_inner_fn(params_i, batch_input, batch_corrupted_i, psm)
loss_inner_vec = loss_inner_vec.at[it].set(jnp.mean(loss))
if self.model_config.use_dense_lr:
# separate learning rates from grad_params
grad_params_true, _ = separate_learning_rates(unfreeze(grad_params))
# separate learning rates from params_i
params_i_true, learning_rates = separate_learning_rates(unfreeze(params_i))
# calculate updates using meta-sgd
updates_params = jax.tree_map(
lambda g, lr: -jnp.clip(lr, 0, 1) * g,
grad_params_true,
learning_rates,
)
# merge updates_params and learning_rates
|
Params = FrozenDict[str, Any]
T = TypeVar("T")
pylogger = logging.getLogger(__name__)
@partial(jax.vmap, in_axes=0)
def mean_square_error(y_corrupted: jnp.ndarray, y_reconstructed: jnp.ndarray, y_psm: jnp.ndarray) -> jnp.ndarray:
"""Calculate the mean squared error between the predicted and actual values of a batch.
Args:
y_corrupted (jnp.ndarray): The actual y perturbed, with shape (output_size,).
y_reconstructed (jnp.ndarray): The predicted y, with shape (output_size,).
y_psm (jnp.ndarray): The Power special matrix, with shape (1,).
Returns:
jnp.ndarray: The mean squared error for each y, with shape (1,).
"""
return jnp.sum(jnp.square(jnp.abs(y_corrupted * y_psm - y_reconstructed * y_psm)))
class BaseMAML(nn.Module, abc.ABC):
"""Abstract model class for implementing Model-Agnostic Meta-Learning (MAML).
The Model-Agnostic Meta-Learning (MAML) algorithm is designed to train models
in a manner that they can be fine-tuned for new tasks with a small number of examples.
This implementation is based on the MAML algorithm introduced in the paper
"Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks"
(https://arxiv.org/abs/1703.03400).
Attributes:
model_config (DictConfig): Configuration dictionary for the model.
optimizer_inner (optax.GradientTransformation): Inner optimizer configuration.
inner_steps (int): Number of inner optimization steps.
Methods:
__call__(self, inputs: jnp.ndarray) -> jnp.ndarray: Implement the forward pass of the model.
initialize_model(self, rng: jax.random.PRNGKey, batch_input: jnp.ndarray) -> FrozenDict[str, Mapping[str, Any]]: Initialize the model with dummy inputs.
initialize_input(self, shape: Tuple[int, ...]) -> jnp.ndarray: Create input tensor for the model based on the specified shape.
make_update_params_fn(self) -> Callable[..., Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]]: Create a function to update the model parameters.
make_update_inner_fn(self, optimizer_inner: optax.GradientTransformation, n_steps: int) -> Callable[..., Tuple[jnp.ndarray, jnp.ndarray]]: Create a function to update model parameters for inner optimization.
make_predict_fn(self) -> Callable[..., jnp.ndarray]: Creates a function for making predictions with the model.
"""
model_config: DictConfig
optimizer_inner: optax.GradientTransformation
inner_steps: int
@abc.abstractmethod
@nn.compact
def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray:
"""Implement the forward pass of the model.
Args:
inputs (jnp.ndarray): Input tensor to the model.
Returns:
jnp.ndarray: Output tensor from the model.
Raises:
NotImplementedError: If this method is not overridden by a derived class.
"""
raise NotImplementedError(f"{self.__class__.__name__} must implement the __call__ method.")
def initialize_model(self, rng: jax.random.PRNGKey, batch_input: jnp.ndarray) -> FrozenDict[str, Mapping[str, Any]]:
"""Initialize the model with dummy inputs.
This method initializes the model parameters by passing a batch of dummy inputs
through the model. This is a common practice to infer the dimensions of the model's
parameters.
Args:
rng (jax.random.PRNGKey): A random key for generating initial model parameters.
batch_input (jnp.ndarray): A batch of dummy inputs for initializing the model.
Returns:
FrozenDict[str, Mapping[str, Any]]: The initialized model parameters.
"""
self.optimizer_inner = hydra.utils.instantiate(self.optimizer_inner)
return self.init(rng, batch_input)
def initialize_input(self, shape: Tuple[int, ...]) -> jnp.ndarray:
"""Create input tensor for the model based on the specified shape.
Args:
shape (Tuple[int, ...]): Shape of the input tensor.
Returns:
jnp.ndarray: Initialized input tensor.
"""
batch_size = shape[0]
num_channels = shape[-1]
grid_size = shape[1:-1]
if not self.model_config.y_input:
num_channels = None
coordinates = make_coordinates(batch_size, grid_size, num_channels)
return coordinates
def make_update_params_fn(self) -> Callable[..., Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]]:
"""Create a function to update the model parameters.
This method creates a function that performs the forward pass of the model
and updates the model parameters.
Returns:
Callable[..., Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]]: Function to update model parameters.
"""
update_inner_fn = self.make_update_inner_fn(
optimizer_inner=self.optimizer_inner,
n_steps=self.inner_steps,
)
def apply_forward(
rng: jax.random.PRNGKey,
params: Params,
batch_input: jnp.ndarray,
batch_corrupted: jnp.ndarray,
psm: jnp.ndarray,
) -> Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]:
"""Apply the (outer) forward pass and update the model parameters.
Args:
rng (jax.random.PRNGKey): Random key.
params (Params): Initial model parameters.
batch_input (jnp.ndarray): Input tensor to the model.
batch_corrupted (jnp.ndarray): Corrupted version of the output tensor.
psm (jnp.ndarray): Power special matrix.
Returns:
Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]: A tuple containing a new random key, the model output, and the inner loss.
"""
params_adapted, loss_inner = update_inner_fn(params, batch_input, batch_corrupted, psm)
model_output = jax.vmap(self.apply)(params_adapted, batch_input)
return rng, model_output, loss_inner
return apply_forward
def make_update_inner_fn(
self, optimizer_inner: optax.GradientTransformation, n_steps: int
) -> Callable[[Params, jnp.ndarray, jnp.ndarray, jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]]:
"""Create a function to update model parameters for inner optimization.
This method creates a function that performs the inner optimization updates
during the meta-training phase, which is a key component of the MAML algorithm.
Args:
optimizer_inner (optax.GradientTransformation): The optimizer used for inner optimization.
n_steps (int): The number of optimization steps.
Returns:
Callable[..., Tuple[jnp.ndarray, jnp.ndarray]]: Function to update model parameters for inner optimization.
"""
@partial(jax.vmap, in_axes=0)
@partial(jax.grad, has_aux=True)
def loss_inner_fn(params_i: Params, batch_input: T, y_corrupted: T, psm: T) -> T:
"""Computes the loss for inner optimization.
This inner method computes the loss for inner optimization by comparing
the model's output against the corrupted batch using mean square error.
The method is vectorized using JAX's vmap function for efficiency.
Args:
params_i (Params): Model parameters.
batch_input (T): Input batch.
y_corrupted (T): Corrupted batch.
psm (T): Power special matrix.
Returns:
T: Loss value.
"""
c = y_corrupted.shape[-1]
model_output = self.apply(params_i, batch_input)
if len(psm.shape) == 3:
model_output_freq = jnp.fft.fft2(model_output.reshape(*psm.shape[:-1], c), norm="ortho", axes=(0, 1))
y_corrupted_freq = jnp.fft.fft2(y_corrupted.reshape(*psm.shape[:-1], c), norm="ortho", axes=(0, 1))
else:
model_output_freq = jnp.fft.fft(model_output.reshape(*psm.shape[:-1], c), norm="ortho", axis=0)
y_corrupted_freq = jnp.fft.fft(y_corrupted.reshape(*psm.shape[:-1], c), norm="ortho", axis=0)
mse = mean_square_error(
y_corrupted_freq.reshape(-1, c),
model_output_freq.reshape(-1, c),
psm.reshape(-1, 1),
)
loss: jnp.ndarray = jnp.mean(mse)
return loss, loss
def apply_inner_forward(
params: Params, batch_input: jnp.ndarray, batch_corrupted: jnp.ndarray, psm: jnp.ndarray
):
"""Applies inner forward pass for updating model parameters.
Args:
params (Params): Model parameters.
batch_input (jnp.ndarray): Input batch.
batch_corrupted (jnp.ndarray): Corrupted batch.
psm (jnp.ndarray): Power special matrix.
Returns:
Tuple[jnp.ndarray, jnp.ndarray]: Updated model parameters and inner loss.
"""
def inner_opt_loop(
carry: Tuple[Params, jnp.ndarray, int, Any, jnp.ndarray], _: None
) -> Tuple[Tuple[Params, jnp.ndarray, int, Any, jnp.ndarray], None]:
"""Inner optimization loop for updating model parameters.
Args:
carry (Tuple[Params, jnp.ndarray, int, optax.OptState, jnp.ndarray]): Tuple containing model parameters,
loss vector, iteration index, optimizer state, and corrupted batch.
_ (None): A throwaway variable as no second argument is used in this function.
Returns:
Tuple[Params, jnp.ndarray, int, optax.OptState, jnp.ndarray]: Updated tuple with new model parameters,
updated loss vector, incremented iteration index, updated optimizer state, and corrupted batch.
"""
params_i, loss_inner_vec, it, opt_inner_state_params, batch_corrupted_i = carry
grad_params, (loss) = loss_inner_fn(params_i, batch_input, batch_corrupted_i, psm)
loss_inner_vec = loss_inner_vec.at[it].set(jnp.mean(loss))
if self.model_config.use_dense_lr:
# separate learning rates from grad_params
grad_params_true, _ = separate_learning_rates(unfreeze(grad_params))
# separate learning rates from params_i
params_i_true, learning_rates = separate_learning_rates(unfreeze(params_i))
# calculate updates using meta-sgd
updates_params = jax.tree_map(
lambda g, lr: -jnp.clip(lr, 0, 1) * g,
grad_params_true,
learning_rates,
)
# merge updates_params and learning_rates | merged_updates = merge_learning_rates(unfreeze(updates_params), unfreeze(learning_rates)) | 2 | 2023-10-24 22:01:35+00:00 | 4k |
godisboy0/nonebot-adapter-wcf | adapters/wechatferry/eventconverter.py | [
{
"identifier": "Event",
"path": "adapters/wechatferry/event.py",
"snippet": "class Sender (OnebotSender):\nclass PrivateMessageEvent (OnebotPrivateMessageEvent):\nclass GroupMessageEvent (OnebotGroupMessageEvent):\nclass TTT(BaseModel):\nclass TTTB(TTT):"
},
{
"identifier": "MessageSegment",
... | from wcferry import Wcf, WxMsg
from .event import Event, PrivateMessageEvent, GroupMessageEvent, Sender
from .message import MessageSegment, Message
from .type import WxType
from .utils import logger
from nonebot.utils import escape_tag
from .sqldb import database
from .msg_converters import convert_to_bot_msg
from .config import AdapterConfig
from nonebot import get_driver
from .debug_helper import send_to_root
import re
import os | 2,572 | """
onebot11标准要求:https://github.com/botuniverse/onebot-11/blob/master/README.md
onebot11 message segment 类型: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md
"""
adapter_config = AdapterConfig.parse_obj(get_driver().config)
async def echo_root_msg_as_json_file(msg: WxMsg, wcf: Wcf = None):
root_user = adapter_config.root_user
echo_root_msg = adapter_config.echo_root_msg
if msg.sender != root_user or not echo_root_msg or msg._is_group:
return
send_to_root(msg, wcf, root_user)
def __get_mention_list(req: WxMsg) -> list[str]:
if req.xml is not None:
pattern = r'<atuserlist>(.*?)</atuserlist>'
match = re.search(pattern, req.xml)
if match:
atuserlist = match.group(1)
return [user_id for user_id in atuserlist.split(',')]
return []
async def convert_to_event(msg: WxMsg, login_wx_id: str, wcf: Wcf, db: database) -> Event:
"""Converts a wechatferry event to a nonebot event."""
logger.debug(f"Converting message to event: {escape_tag(str(msg))}")
if not msg or msg.type == WxType.WX_MSG_HEARTBEAT:
return None
await echo_root_msg_as_json_file(msg, wcf)
args = {}
| """
onebot11标准要求:https://github.com/botuniverse/onebot-11/blob/master/README.md
onebot11 message segment 类型: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md
"""
adapter_config = AdapterConfig.parse_obj(get_driver().config)
async def echo_root_msg_as_json_file(msg: WxMsg, wcf: Wcf = None):
root_user = adapter_config.root_user
echo_root_msg = adapter_config.echo_root_msg
if msg.sender != root_user or not echo_root_msg or msg._is_group:
return
send_to_root(msg, wcf, root_user)
def __get_mention_list(req: WxMsg) -> list[str]:
if req.xml is not None:
pattern = r'<atuserlist>(.*?)</atuserlist>'
match = re.search(pattern, req.xml)
if match:
atuserlist = match.group(1)
return [user_id for user_id in atuserlist.split(',')]
return []
async def convert_to_event(msg: WxMsg, login_wx_id: str, wcf: Wcf, db: database) -> Event:
"""Converts a wechatferry event to a nonebot event."""
logger.debug(f"Converting message to event: {escape_tag(str(msg))}")
if not msg or msg.type == WxType.WX_MSG_HEARTBEAT:
return None
await echo_root_msg_as_json_file(msg, wcf)
args = {} | onebot_msg: Message = await convert_to_bot_msg(msg, login_wx_id, wcf, db) | 5 | 2023-10-22 10:52:27+00:00 | 4k |
R1999RC-official/Reverse1999ResonanceCalculator | python/python_env/Lib/site-packages/pip/_vendor/urllib3/util/retry.py | [
{
"identifier": "ConnectTimeoutError",
"path": "python/python_env/Lib/site-packages/pip/_vendor/urllib3/exceptions.py",
"snippet": "class ConnectTimeoutError(TimeoutError):\n \"\"\"Raised when a socket timeout occurs while connecting to a server\"\"\"\n\n pass"
},
{
"identifier": "InvalidH... | import email
import logging
import re
import time
import warnings
from collections import namedtuple
from itertools import takewhile
from ..exceptions import (
ConnectTimeoutError,
InvalidHeader,
MaxRetryError,
ProtocolError,
ProxyError,
ReadTimeoutError,
ResponseError,
)
from ..packages import six | 2,191 | from __future__ import absolute_import
log = logging.getLogger(__name__)
# Data structure for representing the metadata of requests that result in a retry.
RequestHistory = namedtuple(
"RequestHistory", ["method", "url", "error", "status", "redirect_location"]
)
# TODO: In v2 we can remove this sentinel and metaclass with deprecated options.
_Default = object()
class _RetryMeta(type):
@property
def DEFAULT_METHOD_WHITELIST(cls):
warnings.warn(
"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
DeprecationWarning,
)
return cls.DEFAULT_ALLOWED_METHODS
@DEFAULT_METHOD_WHITELIST.setter
def DEFAULT_METHOD_WHITELIST(cls, value):
warnings.warn(
"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
DeprecationWarning,
)
cls.DEFAULT_ALLOWED_METHODS = value
@property
def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):
warnings.warn(
"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
DeprecationWarning,
)
return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT
@DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter
def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):
warnings.warn(
"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
DeprecationWarning,
)
cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value
@property
def BACKOFF_MAX(cls):
warnings.warn(
"Using 'Retry.BACKOFF_MAX' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",
DeprecationWarning,
)
return cls.DEFAULT_BACKOFF_MAX
@BACKOFF_MAX.setter
def BACKOFF_MAX(cls, value):
warnings.warn(
"Using 'Retry.BACKOFF_MAX' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",
DeprecationWarning,
)
cls.DEFAULT_BACKOFF_MAX = value
| from __future__ import absolute_import
log = logging.getLogger(__name__)
# Data structure for representing the metadata of requests that result in a retry.
RequestHistory = namedtuple(
"RequestHistory", ["method", "url", "error", "status", "redirect_location"]
)
# TODO: In v2 we can remove this sentinel and metaclass with deprecated options.
_Default = object()
class _RetryMeta(type):
@property
def DEFAULT_METHOD_WHITELIST(cls):
warnings.warn(
"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
DeprecationWarning,
)
return cls.DEFAULT_ALLOWED_METHODS
@DEFAULT_METHOD_WHITELIST.setter
def DEFAULT_METHOD_WHITELIST(cls, value):
warnings.warn(
"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
DeprecationWarning,
)
cls.DEFAULT_ALLOWED_METHODS = value
@property
def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):
warnings.warn(
"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
DeprecationWarning,
)
return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT
@DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter
def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):
warnings.warn(
"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
DeprecationWarning,
)
cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value
@property
def BACKOFF_MAX(cls):
warnings.warn(
"Using 'Retry.BACKOFF_MAX' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",
DeprecationWarning,
)
return cls.DEFAULT_BACKOFF_MAX
@BACKOFF_MAX.setter
def BACKOFF_MAX(cls, value):
warnings.warn(
"Using 'Retry.BACKOFF_MAX' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",
DeprecationWarning,
)
cls.DEFAULT_BACKOFF_MAX = value
| @six.add_metaclass(_RetryMeta) | 7 | 2023-10-24 06:48:58+00:00 | 4k |
mentpy/mentpy | mentpy/operators/controlled_ment.py | [
{
"identifier": "PauliX",
"path": "mentpy/operators/gates.py",
"snippet": "CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\nSWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])\n U = unitary_group.rvs(2**n_qubits)\n U = U / np.power(detU, 1 / (2**n_qu... | from typing import Optional, Union, Callable
from .gates import PauliX, PauliY, PauliZ
from .ment import Ment, MentOutcome
import numpy as np
import warnings | 2,653 | # Copyright 2023 Luis Mantilla
#
# Licensed under the Apache License, Version 2.0.
# See <http://www.apache.org/licenses/LICENSE-2.0> for details.
"""Controlled measurement operator."""
class ControlMent(Ment):
def __init__(
self,
| # Copyright 2023 Luis Mantilla
#
# Licensed under the Apache License, Version 2.0.
# See <http://www.apache.org/licenses/LICENSE-2.0> for details.
"""Controlled measurement operator."""
class ControlMent(Ment):
def __init__(
self, | condition: Optional[Union[bool, MentOutcome]] = None, | 2 | 2023-10-18 18:29:42+00:00 | 4k |
rnag/cert-hero | tests/integration/test_cert_hero.py | [
{
"identifier": "cert_please",
"path": "cert_hero/cert_hero.py",
"snippet": "def cert_please(hostname: str,\n context: ssl.SSLContext = None,\n user_agent: str | None = _DEFAULT_USER_AGENT,\n default_encoding='latin-1',\n ) -> CertHero[str, str... | import json
from cert_hero import cert_please, certs_please, set_expired | 3,566 |
def test_cert_please():
cert = cert_please('google.com')
print('Cert is Valid Till:', cert.not_after_date.isoformat())
# To get the output as a JSON string, use `str(cert)` or remove `!r` from below
print(f'Cert -> \n{cert!r}')
assert cert['Subject Name']['Common Name'] == '*.google.com'
|
def test_cert_please():
cert = cert_please('google.com')
print('Cert is Valid Till:', cert.not_after_date.isoformat())
# To get the output as a JSON string, use `str(cert)` or remove `!r` from below
print(f'Cert -> \n{cert!r}')
assert cert['Subject Name']['Common Name'] == '*.google.com'
| set_expired(cert) | 2 | 2023-10-16 19:02:05+00:00 | 4k |
KosinskiLab/pyTME | tme/tests/test_parser.py | [
{
"identifier": "Parser",
"path": "tme/parser.py",
"snippet": "class Parser(ABC):\n \"\"\"\n Base class for structure file parsers.\n\n Classes inheriting from :py:class:`Parser` need to define\n a ``parse_input`` method that accepts a list of lines and returns a\n dictionary representati... | import pytest
from tme.parser import Parser, PDBParser | 1,807 |
class TestParser:
def setup_method(self):
self.pdb_file = "./tme/tests/data/Structures/5khe.pdb"
def teardown_method(self):
self.pdb_file = None
def test_initialize_parser_error(self):
with pytest.raises(TypeError):
|
class TestParser:
def setup_method(self):
self.pdb_file = "./tme/tests/data/Structures/5khe.pdb"
def teardown_method(self):
self.pdb_file = None
def test_initialize_parser_error(self):
with pytest.raises(TypeError): | _ = Parser(self.pdb_file) | 0 | 2023-10-20 13:46:01+00:00 | 4k |
hookla/DreamTeamGPT | dream_team_gpt/meeting.py | [
{
"identifier": "Chairman",
"path": "dream_team_gpt/agents/chairman.py",
"snippet": "class Chairman(Agent):\n def __init__(self, client_factory: Callable, executives: list[SME], name: str = \"Chairman\"):\n # Construct the user_prompt string with details of the executives\n self.user_pr... | from dataclasses import dataclass, field
from pathlib import Path
from textwrap import dedent
from loguru import logger
from dream_team_gpt.agents import SME, Chairman
from dream_team_gpt.agents.idea_refiner import IdeaRefiner
from dream_team_gpt.clients import AIClientConfig, AIClientType, Models, ai_client_factory
from dream_team_gpt.constants import DEFAULT_SME_DICT, NO_COMMENT
from dream_team_gpt.utils import parse_yaml_config, print_with_wrap
import os | 1,897 |
@dataclass
class Transcript(str):
idea: str
refined_idea: str = None
opinions: list[str] = field(default_factory=list)
def __str__(self) -> str:
opinions = "\n".join(opinion for opinion in self.opinions)
return dedent(
f"""\
We are here to discuss the following idea:
{self.refined_idea if self.refined_idea else self.idea}
{opinions if opinions else ""}"""
)
def add_opinion(self, opinion: str) -> None:
self.opinions.append(opinion)
def __add__(self, other: str) -> "Transcript":
if not isinstance(other, str):
raise ValueError("Only can add string opinion to Transcript")
self.add_opinion(other)
return self
@dataclass
class Meeting:
idea: str
config: Path = None
def __post_init__(self) -> None:
"""Create agents"""
client_factory = ai_client_factory(
AIClientConfig(
client_type=AIClientType.ChatGPT,
model=Models.GPT4,
api_key=os.environ["openai.api_key"],
)
)
if self.config:
sme_dict = parse_yaml_config(self.config)
else:
sme_dict = DEFAULT_SME_DICT
|
@dataclass
class Transcript(str):
idea: str
refined_idea: str = None
opinions: list[str] = field(default_factory=list)
def __str__(self) -> str:
opinions = "\n".join(opinion for opinion in self.opinions)
return dedent(
f"""\
We are here to discuss the following idea:
{self.refined_idea if self.refined_idea else self.idea}
{opinions if opinions else ""}"""
)
def add_opinion(self, opinion: str) -> None:
self.opinions.append(opinion)
def __add__(self, other: str) -> "Transcript":
if not isinstance(other, str):
raise ValueError("Only can add string opinion to Transcript")
self.add_opinion(other)
return self
@dataclass
class Meeting:
idea: str
config: Path = None
def __post_init__(self) -> None:
"""Create agents"""
client_factory = ai_client_factory(
AIClientConfig(
client_type=AIClientType.ChatGPT,
model=Models.GPT4,
api_key=os.environ["openai.api_key"],
)
)
if self.config:
sme_dict = parse_yaml_config(self.config)
else:
sme_dict = DEFAULT_SME_DICT | self.smes = [SME(client_factory=client_factory, **d) for d in sme_dict] | 1 | 2023-10-18 22:45:50+00:00 | 4k |
MeetingAgent/MeetingAgent-Core | meeting_buddy.py | [
{
"identifier": "MyTTS",
"path": "voice_cloning/clone.py",
"snippet": "class MyTTS:\n def __init__(self):\n # Get device\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n self.tts = TTS(\"tts_models/en/ljspeech/tacotron2-DDC\")\n self.use_default_speak... | import pyaudio
import wave
import whisper
import threading
import time
import pygame
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.switch import Switch
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.textinput import TextInput
from kivy.core.window import Window
from kivy.support import install_twisted_reactor
from gtts import gTTS
from pydub import AudioSegment
from ftlangdetect import detect
from voice_cloning.clone import MyTTS
from meeting_buddy_system.gpt_utils import gpt_4_answer, gpt_3_5_turbo_16k_answer
from meeting_buddy_system.prompts import MEETING_BUDDY_MAIN_PROMPT, EXTRACT_QUERY_PROMPT | 2,694 | play_audio('meeting_buddy_audio/output.mp3')
else:
# Update the answer text without text-to-speech
Clock.schedule_once(lambda dt: app.update_answer_text(aggregated_text))
return query, answer
def meeting_buddy(meeting_context: str) -> None:
global audio_thread
audio_thread = threading.Thread(target=get_audio)
audio_thread.start()
audio_thread.join()
input_text = whisper_process_audio("meeting_buddy_audio/audio.wav")
question, answer = gpt_pipeline(meeting_context=meeting_context, input_text=input_text)
print(f"Question: {question}")
print(f"Answer: {answer}")
Window.size = (800, 600)
class MeetingBuddyApp(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio_thread = None
self.context_input = TextInput(
hint_text='Paste your meeting notes here',
multiline=True,
size_hint=(1, 0.2),
font_size='20sp',
background_color=[0, 0, 0, 1],
foreground_color=[1, 1, 1, 1]
)
self.tts = None
def on_start(self):
self.load_tts_model()
def build(self):
self.answer_output = TextInput(
text='',
multiline=True,
size_hint=(1, 0.6),
font_size='20sp',
readonly=True,
background_color=[0, 0, 0, 1],
foreground_color=[1, 1, 1, 1]
)
start_button = Button(
text='Start Recording',
on_release=self.start_meeting_buddy,
size_hint=(1, 0.1),
font_size='20sp'
)
stop_button_layout = BoxLayout(orientation='vertical', spacing=10, size_hint=(1, 0.3))
stop_button = Button(
text='Stop Recording',
on_release=self.stop_recording,
size_hint=(1, 0.1),
font_size='20sp'
)
switch_layout = BoxLayout(
orientation='horizontal',
spacing=10,
size_hint=(None, None),
size=(200, 175),
pos_hint={'center_x': 0.5}
)
tts_label = Label(
text='Text to Speech:',
size_hint=(None, None),
size=(0, 200)
)
self.tts_switch = Switch(size_hint=(None, None), size=(400, 200))
switch_layout.add_widget(tts_label)
switch_layout.add_widget(self.tts_switch)
stop_button_layout.add_widget(stop_button)
stop_button_layout.add_widget(switch_layout)
layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
layout.add_widget(self.context_input)
layout.add_widget(start_button)
layout.add_widget(stop_button_layout)
layout.add_widget(self.answer_output)
return layout
def update_answer_text(self, text):
self.answer_output.text = f'{text}'
def start_meeting_buddy(self, instance):
global app
app = self
meeting_context = self.context_input.text
global audio_thread
audio_thread = threading.Thread(target=meeting_buddy, args=(meeting_context,))
audio_thread.start()
stop_audio_playback()
def stop_recording(self, instance):
stop_audio()
if self.audio_thread is not None:
self.audio_thread.join()
Clock.schedule_once(self.delayed_update, 1)
def delayed_update(self, dt):
self.update_answer_text("Getting answer...")
def load_tts_model(self):
| # Audio Processing
# GUI
install_twisted_reactor()
# gtts text to speech
# personalized voice text to speech
# Local
recording = False
audio_thread = None
def get_audio() -> None:
global recording
recording = True
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
frames = []
try:
print("Recording...")
while recording:
data = stream.read(1024)
frames.append(data)
print("Finished recording.")
finally:
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open('meeting_buddy_audio/input_audio.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(44100)
wf.writeframes(b''.join(frames))
wf.close()
def stop_audio() -> None:
global recording
recording = False
def whisper_process_audio(audio_file: str) -> str:
model = whisper.load_model("base") # for multilingual
result = model.transcribe(audio_file)
return result["text"]
def detect_language(text: str) -> str:
cleaned_text = text.replace('\n', ' ')
return detect(text=cleaned_text, low_memory=True)
def gtts_text_to_speech(text: str, output_file='meeting_buddy_audio/output.mp3') -> None:
language = detect_language(text=text)["lang"]
tts = gTTS(text=text, lang=language, slow=False)
tts.save(output_file)
print(f'Audio saved as {output_file}')
def voice_clone_text_to_speech(text: str, output_file='meeting_buddy_audio/output.wav') -> None:
app.tts.text_to_speech(text, output_file)
print(f'Audio saved as {output_file}')
# initialize mixer
pygame.mixer.init()
def play_audio(file_path):
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
def stop_audio_playback():
pygame.mixer.music.stop()
def gpt_pipeline(meeting_context: str, input_text: str) -> str:
"""
Extract query from text and produce the final answer to query.
"""
print("\n\n\n###### EXTRACTING QUERY FROM TEXT ######\n\n\n")
messages = [{"role": "system", "content": EXTRACT_QUERY_PROMPT}, {"role": "user", "content": input_text}]
query = gpt_3_5_turbo_16k_answer(messages=messages)
full_query_text = f"Extracted Query: {query}"
print("\n\n\n###### FINISHED EXTRACTING QUERY FROM TEXT ######\n\n\n")
print("\n\n\n###### RESPONDING TO QUERY ######\n\n\n")
messages = [{"role": "system", "content": MEETING_BUDDY_MAIN_PROMPT.format(meeting_context=meeting_context)}, {"role": "user", "content": query}]
answer = gpt_4_answer(messages=messages)
full_answer_text = f"Answer: {answer}"
print("\n\n\n###### RESPONDED TO QUERY ######\n\n\n")
aggregated_text = full_query_text + "\n\n" + full_answer_text
if app.tts_switch.active:
try:
print("\n\n###### GETTING TTS TEXT TO SPEECH RESPONSE ######\n\n")
# getting custom voice text to speech response
voice_clone_text_to_speech(answer)
Clock.schedule_once(lambda dt: app.update_answer_text(aggregated_text))
play_audio('meeting_buddy_audio/output.wav')
except:
print("\n\n###### GETTING GTTS TEXT TO SPEECH RESPONSE ######\n\n")
# getting gtts text to speech response
gtts_text_to_speech(answer)
Clock.schedule_once(lambda dt: app.update_answer_text(aggregated_text))
play_audio('meeting_buddy_audio/output.mp3')
else:
# Update the answer text without text-to-speech
Clock.schedule_once(lambda dt: app.update_answer_text(aggregated_text))
return query, answer
def meeting_buddy(meeting_context: str) -> None:
global audio_thread
audio_thread = threading.Thread(target=get_audio)
audio_thread.start()
audio_thread.join()
input_text = whisper_process_audio("meeting_buddy_audio/audio.wav")
question, answer = gpt_pipeline(meeting_context=meeting_context, input_text=input_text)
print(f"Question: {question}")
print(f"Answer: {answer}")
Window.size = (800, 600)
class MeetingBuddyApp(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio_thread = None
self.context_input = TextInput(
hint_text='Paste your meeting notes here',
multiline=True,
size_hint=(1, 0.2),
font_size='20sp',
background_color=[0, 0, 0, 1],
foreground_color=[1, 1, 1, 1]
)
self.tts = None
def on_start(self):
self.load_tts_model()
def build(self):
self.answer_output = TextInput(
text='',
multiline=True,
size_hint=(1, 0.6),
font_size='20sp',
readonly=True,
background_color=[0, 0, 0, 1],
foreground_color=[1, 1, 1, 1]
)
start_button = Button(
text='Start Recording',
on_release=self.start_meeting_buddy,
size_hint=(1, 0.1),
font_size='20sp'
)
stop_button_layout = BoxLayout(orientation='vertical', spacing=10, size_hint=(1, 0.3))
stop_button = Button(
text='Stop Recording',
on_release=self.stop_recording,
size_hint=(1, 0.1),
font_size='20sp'
)
switch_layout = BoxLayout(
orientation='horizontal',
spacing=10,
size_hint=(None, None),
size=(200, 175),
pos_hint={'center_x': 0.5}
)
tts_label = Label(
text='Text to Speech:',
size_hint=(None, None),
size=(0, 200)
)
self.tts_switch = Switch(size_hint=(None, None), size=(400, 200))
switch_layout.add_widget(tts_label)
switch_layout.add_widget(self.tts_switch)
stop_button_layout.add_widget(stop_button)
stop_button_layout.add_widget(switch_layout)
layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
layout.add_widget(self.context_input)
layout.add_widget(start_button)
layout.add_widget(stop_button_layout)
layout.add_widget(self.answer_output)
return layout
def update_answer_text(self, text):
self.answer_output.text = f'{text}'
def start_meeting_buddy(self, instance):
global app
app = self
meeting_context = self.context_input.text
global audio_thread
audio_thread = threading.Thread(target=meeting_buddy, args=(meeting_context,))
audio_thread.start()
stop_audio_playback()
def stop_recording(self, instance):
stop_audio()
if self.audio_thread is not None:
self.audio_thread.join()
Clock.schedule_once(self.delayed_update, 1)
def delayed_update(self, dt):
self.update_answer_text("Getting answer...")
def load_tts_model(self): | self.tts = MyTTS() | 0 | 2023-10-18 06:50:56+00:00 | 4k |
tonnetonne814/MB-iSTFT-BERT-VITS2-44100-Ja | modules.py | [
{
"identifier": "init_weights",
"path": "commons.py",
"snippet": "def init_weights(m, mean=0.0, std=0.01):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n m.weight.data.normal_(mean, std)"
},
{
"identifier": "get_padding",
"path": "commons.py",
"sni... | import math
import torch
import commons
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
from attentions import Encoder | 2,950 | dilation_rate,
n_layers,
gin_channels=0,
p_dropout=0,
):
super(WN, self).__init__()
assert kernel_size % 2 == 1
self.hidden_channels = hidden_channels
self.kernel_size = (kernel_size,)
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.drop = nn.Dropout(p_dropout)
if gin_channels != 0:
cond_layer = torch.nn.Conv1d(
gin_channels, 2 * hidden_channels * n_layers, 1
)
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
for i in range(n_layers):
dilation = dilation_rate**i
padding = int((kernel_size * dilation - dilation) / 2)
in_layer = torch.nn.Conv1d(
hidden_channels,
2 * hidden_channels,
kernel_size,
dilation=dilation,
padding=padding,
)
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
self.in_layers.append(in_layer)
# last one is not necessary
if i < n_layers - 1:
res_skip_channels = 2 * hidden_channels
else:
res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
else:
g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts)
if i < self.n_layers - 1:
res_acts = res_skip_acts[:, : self.hidden_channels, :]
x = (x + res_acts) * x_mask
output = output + res_skip_acts[:, self.hidden_channels :, :]
else:
output = output + res_skip_acts
return output * x_mask
def remove_weight_norm(self):
if self.gin_channels != 0:
torch.nn.utils.remove_weight_norm(self.cond_layer)
for l in self.in_layers:
torch.nn.utils.remove_weight_norm(l)
for l in self.res_skip_layers:
torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2]),
)
),
]
)
|
LRELU_SLOPE = 0.1
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels))
self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x):
x = x.transpose(1, -1)
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
return x.transpose(1, -1)
class ConvReluNorm(nn.Module):
def __init__(
self,
in_channels,
hidden_channels,
out_channels,
kernel_size,
n_layers,
p_dropout,
):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
assert n_layers > 1, "Number of layers should be larger than 0."
self.conv_layers = nn.ModuleList()
self.norm_layers = nn.ModuleList()
self.conv_layers.append(
nn.Conv1d(
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
for _ in range(n_layers - 1):
self.conv_layers.append(
nn.Conv1d(
hidden_channels,
hidden_channels,
kernel_size,
padding=kernel_size // 2,
)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask):
x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
class DDSConv(nn.Module):
"""
Dialted and Depth-Separable Convolution
"""
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
super().__init__()
self.channels = channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout)
self.convs_sep = nn.ModuleList()
self.convs_1x1 = nn.ModuleList()
self.norms_1 = nn.ModuleList()
self.norms_2 = nn.ModuleList()
for i in range(n_layers):
dilation = kernel_size**i
padding = (kernel_size * dilation - dilation) // 2
self.convs_sep.append(
nn.Conv1d(
channels,
channels,
kernel_size,
groups=channels,
dilation=dilation,
padding=padding,
)
)
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
self.norms_1.append(LayerNorm(channels))
self.norms_2.append(LayerNorm(channels))
def forward(self, x, x_mask, g=None):
if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
class WN(torch.nn.Module):
def __init__(
self,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0,
p_dropout=0,
):
super(WN, self).__init__()
assert kernel_size % 2 == 1
self.hidden_channels = hidden_channels
self.kernel_size = (kernel_size,)
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.drop = nn.Dropout(p_dropout)
if gin_channels != 0:
cond_layer = torch.nn.Conv1d(
gin_channels, 2 * hidden_channels * n_layers, 1
)
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
for i in range(n_layers):
dilation = dilation_rate**i
padding = int((kernel_size * dilation - dilation) / 2)
in_layer = torch.nn.Conv1d(
hidden_channels,
2 * hidden_channels,
kernel_size,
dilation=dilation,
padding=padding,
)
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
self.in_layers.append(in_layer)
# last one is not necessary
if i < n_layers - 1:
res_skip_channels = 2 * hidden_channels
else:
res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
else:
g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts)
if i < self.n_layers - 1:
res_acts = res_skip_acts[:, : self.hidden_channels, :]
x = (x + res_acts) * x_mask
output = output + res_skip_acts[:, self.hidden_channels :, :]
else:
output = output + res_skip_acts
return output * x_mask
def remove_weight_norm(self):
if self.gin_channels != 0:
torch.nn.utils.remove_weight_norm(self.cond_layer)
for l in self.in_layers:
torch.nn.utils.remove_weight_norm(l)
for l in self.res_skip_layers:
torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2]),
)
),
]
) | self.convs1.apply(init_weights) | 0 | 2023-10-16 10:04:32+00:00 | 4k |
KaichengGroup/FUSE-Flow | test.py | [
{
"identifier": "NPZDataset",
"path": "data_modules/npz_dataset.py",
"snippet": "class NPZDataset(VisionDataset):\n \"\"\"Load datasets from NPZ files.\n NPZ files are assumed to have 2 files named \"x\" and \"y\"\n that represent the input and target, respectively.\n\n Parameters\n -----... | import os
import pytorch_lightning as pl
import torch
from pytorch_lightning import Trainer
from torch.utils.data import DataLoader
from torchvision.transforms import ToTensor, Compose
from data_modules.npz_dataset import NPZDataset
from utils.utils import load_config, create_subset, save_train_results, CONFIG_PATH, determine_version_name, \
get_latest_checkpoint_path, CONFIG_FILENAME, save_outputs, initialize_model | 1,937 |
if __name__ == '__main__':
pl.seed_everything(42)
# "highest" (default), float32 matrix multiplications use the float32 datatype for internal computations.
# "high", float32 matrix multiplications use the TensorFloat32 or bfloat16_3x
# "medium", float32 matrix multiplications use the bfloat16 datatype
torch.set_float32_matmul_precision('highest')
|
if __name__ == '__main__':
pl.seed_everything(42)
# "highest" (default), float32 matrix multiplications use the float32 datatype for internal computations.
# "high", float32 matrix multiplications use the TensorFloat32 or bfloat16_3x
# "medium", float32 matrix multiplications use the bfloat16 datatype
torch.set_float32_matmul_precision('highest')
| config = load_config(CONFIG_PATH) | 1 | 2023-10-19 06:49:31+00:00 | 4k |
TheAcharya/Airlift | airlift/airtable_upload.py | [
{
"identifier": "new_client",
"path": "airlift/airtable_client.py",
"snippet": "class new_client:\n\n def __init__(self,token:str,base:str,table:str):\n\n self.api = token\n self.base = base\n self.table = table\n self.headers = {\n \"Authorization\": \"Bear... | import logging
import concurrent.futures
import os
from airlift.airtable_client import new_client
from typing import Any, Dict, Iterable, Iterator, List, Optional
from queue import Queue, Empty
from airlift.dropbox_client import dropbox_client
from tqdm import tqdm
from icecream import ic
from airlift.dropbox_client import dropbox_client | 2,823 |
logger = logging.getLogger(__name__)
ATDATA = List[Dict[str, Dict[str, str]]]
class Upload:
|
logger = logging.getLogger(__name__)
ATDATA = List[Dict[str, Dict[str, str]]]
class Upload: | def __init__(self,client: new_client, new_data:ATDATA,dbx:dropbox_client,args:dict): | 0 | 2023-10-21 01:57:41+00:00 | 4k |
zytedata/zyte-spider-templates | zyte_spider_templates/spiders/base.py | [
{
"identifier": "GEOLOCATION_OPTIONS_WITH_CODE",
"path": "zyte_spider_templates/_geolocations.py",
"snippet": "GEOLOCATION_OPTIONS_WITH_CODE = {\n code: f\"{name} ({code})\" for code, name in GEOLOCATION_OPTIONS.items()\n}"
},
{
"identifier": "Geolocation",
"path": "zyte_spider_templates/... | from importlib.metadata import version
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field
from scrapy.crawler import Crawler
from scrapy.utils.url import parse_url
from zyte_spider_templates._geolocations import (
GEOLOCATION_OPTIONS_WITH_CODE,
Geolocation,
)
import scrapy | 2,504 |
# Higher priority than command-line-defined settings (40).
ARG_SETTING_PRIORITY: int = 50
class BaseSpiderParams(BaseModel):
url: str = Field(
title="URL",
description="Initial URL for the crawl.",
pattern=r"^https?:\/\/[^:\/\s]+(:\d{1,5})?(\/[^\s]*)*(#[^\s]*)?$",
)
|
# Higher priority than command-line-defined settings (40).
ARG_SETTING_PRIORITY: int = 50
class BaseSpiderParams(BaseModel):
url: str = Field(
title="URL",
description="Initial URL for the crawl.",
pattern=r"^https?:\/\/[^:\/\s]+(:\d{1,5})?(\/[^\s]*)*(#[^\s]*)?$",
) | geolocation: Optional[Geolocation] = Field( | 1 | 2023-10-18 10:58:44+00:00 | 4k |
DegangWang97/IEEE_TGRS_PDBSNet | main.py | [
{
"identifier": "PDBSNet",
"path": "model.py",
"snippet": "class PDBSNet(nn.Module):\n def __init__(self, nch_in=189, nch_out=189, nch_ker=64, nblk=9):\n super().__init__()\n\n ly = []\n ly += [ nn.Conv2d(nch_in, nch_ker, kernel_size=1) ]\n ly += [ nn.ReLU(inplace=True) ]\... | import argparse
import torch
import torch.nn as nn
import scipy.io as sio
import os
import numpy as np
import time
from model import PDBSNet
from dataset import PDBSNetData, pixel_shuffle_up_sampling, pixel_shuffle_down_sampling
from utils import get_auc, setup_seed, TensorToHSI
from torch import optim
from torch.utils.tensorboard import SummaryWriter
| 3,107 | Trains a PyTorch `nn.Module` object provided in `model`
on training sets provided in `dataloader`
using `criterion` and `optimizer`.
Saves model weight snapshots every `save_freq` epochs and saves the
weights at the end of training.
Parameters
----------
model : torch model object, with callable `forward` method.
criterion : callable taking inputs and targets, returning loss.
optimizer : torch.optim optimizer.
dataloader : train dataloaders.
model_path : string. output path for model.
logs_path : string. output path for log.
save_freq : integer. Number of epochs between model checkpoints. Default = 50.
scheduler : learning rate scheduler.
'''
self.model = model
self.optimizer = optimizer
self.criterion = criterion
self.dataloader = dataloader
self.device = device
self.model_path = model_path
self.logs_path = logs_path
self.save_freq = save_freq
self.scheduler = scheduler
self.opt = opt
if not os.path.exists(self.model_path):
os.makedirs(self.model_path)
if not os.path.exists(self.logs_path):
os.makedirs(self.logs_path)
self.log_output = open(f"{self.logs_path}/log.txt", 'w')
self.writer = SummaryWriter(logs_path)
print(self.opt)
print(self.opt, file=self.log_output)
def train_epoch(self) -> None:
# Run a train phase for each epoch
self.model.train(True)
loss_train = []
train_data = pixel_shuffle_down_sampling(self.dataloader, self.opt.factor_train, pad=0)
loader_train = self.dataloader.to(self.device)
train_data = train_data.to(self.device)
# forward net
output = self.model(train_data)
# backward net
self.optimizer.zero_grad()
outputs = pixel_shuffle_up_sampling(output, self.opt.factor_train, pad=0)
loss = self.criterion(outputs, loader_train)
loss.backward()
self.optimizer.step()
# get losses
loss_train = loss.item()
print("Train Loss:" + str(round(loss_train, 4)))
print("Train Loss:" + str(round(loss_train, 4)), file = self.log_output)
# ============ TensorBoard logging ============#
# Log the scalar values
info = {
'Loss_train': np.mean(loss_train)
}
for tag, value in info.items():
self.writer.add_scalar(tag, value, self.epoch + 1)
# Saving model
if ((self.epoch + 1) % self.save_freq == 0):
torch.save(self.model.state_dict(), os.path.join(self.model_path, 'PDBSNet' + '_' + self.opt.dataset + '_' + str(self.epoch + 1) + '.pkl'))
def train(self) -> nn.Module:
for epoch in range(self.opt.epochs):
self.epoch = epoch
print('-' * 50)
print('Epoch {}/{}'.format(epoch + 1, self.opt.epochs))
print('Epoch {}/{}'.format(epoch + 1, self.opt.epochs), file = self.log_output)
print('-' * 50)
# run training epoch
self.train_epoch()
if self.scheduler is not None:
self.scheduler.step()
return self.model
def train_model(opt):
DB = opt.dataset
expr_dir = os.path.join('./checkpoints/', DB)
if not os.path.exists(expr_dir):
os.makedirs(expr_dir)
prefix = 'PDBSNet' + '_epoch_' + str(opt.epochs)+ '_learning_rate_' + str(opt.learning_rate) + '_factor_train_' + str(opt.factor_train) + '_gpu_ids_' + str(opt.gpu_ids)
trainfile = os.path.join(expr_dir, prefix)
if not os.path.exists(trainfile):
os.makedirs(trainfile)
# Device
device = torch.device('cuda:{}'.format(opt.gpu_ids)) if torch.cuda.is_available() else torch.device('cpu')
# Directories for storing model and output samples
model_path = os.path.join(trainfile, 'model')
logs_path = os.path.join(trainfile, './logs')
setup_seed(opt.seed)
loader_train, band = PDBSNetData(opt)
| """
See more details in papers:
[1] D. Wang, L. Zhuang, L. Gao, X. Sun, M. Huang, and A. Plaza,
“PDBSNet: Pixel-Shuffle Downsampling Blind-Spot Reconstruction Network
for Hyperspectral Anomaly Detection,” IEEE Trans. Geosci. Remote Sens.,
vol. 61, 2023, Art. no. 5511914. DOI: 10.1109/TGRS.2023.3276175
URL: https://ieeexplore.ieee.org/abstract/document/10124448
------------------------------------------------------------------------------
Copyright (May, 2023):
Degang Wang (wangdegang20@mails.ucas.ac.cn)
Lina Zhuang (zhuangln@aircas.ac.cn)
Lianru Gao (gaolr@aircas.ac.cn)
Xu Sun (sunxu@aircas.ac.cn)
Min Huang (huangmin@aircas.ac.cn)
Antonio Plaza (aplaza@unex.es)
PDBSNet is distributed under the terms of the GNU General Public License 2.0.
Permission to use, copy, modify, and distribute this software for
any purpose without fee is hereby granted, provided that this entire
notice is included in all copies of any software which is or includes
a copy or modification of this software and in all copies of the
supporting documentation for such software.
This software is being provided "as is", without any express or
implied warranty. In particular, the authors do not make any
representation or warranty of any kind concerning the merchantability
of this software or its fitness for any particular purpose.
------------------------------------------------------------------------------
"""
class Trainer(object):
'''
Trains a model
'''
def __init__(self,
opt,
model,
criterion,
optimizer,
dataloader,
device,
model_path: str,
logs_path: str,
save_freq: int=50,
scheduler = None):
'''
Trains a PyTorch `nn.Module` object provided in `model`
on training sets provided in `dataloader`
using `criterion` and `optimizer`.
Saves model weight snapshots every `save_freq` epochs and saves the
weights at the end of training.
Parameters
----------
model : torch model object, with callable `forward` method.
criterion : callable taking inputs and targets, returning loss.
optimizer : torch.optim optimizer.
dataloader : train dataloaders.
model_path : string. output path for model.
logs_path : string. output path for log.
save_freq : integer. Number of epochs between model checkpoints. Default = 50.
scheduler : learning rate scheduler.
'''
self.model = model
self.optimizer = optimizer
self.criterion = criterion
self.dataloader = dataloader
self.device = device
self.model_path = model_path
self.logs_path = logs_path
self.save_freq = save_freq
self.scheduler = scheduler
self.opt = opt
if not os.path.exists(self.model_path):
os.makedirs(self.model_path)
if not os.path.exists(self.logs_path):
os.makedirs(self.logs_path)
self.log_output = open(f"{self.logs_path}/log.txt", 'w')
self.writer = SummaryWriter(logs_path)
print(self.opt)
print(self.opt, file=self.log_output)
def train_epoch(self) -> None:
# Run a train phase for each epoch
self.model.train(True)
loss_train = []
train_data = pixel_shuffle_down_sampling(self.dataloader, self.opt.factor_train, pad=0)
loader_train = self.dataloader.to(self.device)
train_data = train_data.to(self.device)
# forward net
output = self.model(train_data)
# backward net
self.optimizer.zero_grad()
outputs = pixel_shuffle_up_sampling(output, self.opt.factor_train, pad=0)
loss = self.criterion(outputs, loader_train)
loss.backward()
self.optimizer.step()
# get losses
loss_train = loss.item()
print("Train Loss:" + str(round(loss_train, 4)))
print("Train Loss:" + str(round(loss_train, 4)), file = self.log_output)
# ============ TensorBoard logging ============#
# Log the scalar values
info = {
'Loss_train': np.mean(loss_train)
}
for tag, value in info.items():
self.writer.add_scalar(tag, value, self.epoch + 1)
# Saving model
if ((self.epoch + 1) % self.save_freq == 0):
torch.save(self.model.state_dict(), os.path.join(self.model_path, 'PDBSNet' + '_' + self.opt.dataset + '_' + str(self.epoch + 1) + '.pkl'))
def train(self) -> nn.Module:
for epoch in range(self.opt.epochs):
self.epoch = epoch
print('-' * 50)
print('Epoch {}/{}'.format(epoch + 1, self.opt.epochs))
print('Epoch {}/{}'.format(epoch + 1, self.opt.epochs), file = self.log_output)
print('-' * 50)
# run training epoch
self.train_epoch()
if self.scheduler is not None:
self.scheduler.step()
return self.model
def train_model(opt):
DB = opt.dataset
expr_dir = os.path.join('./checkpoints/', DB)
if not os.path.exists(expr_dir):
os.makedirs(expr_dir)
prefix = 'PDBSNet' + '_epoch_' + str(opt.epochs)+ '_learning_rate_' + str(opt.learning_rate) + '_factor_train_' + str(opt.factor_train) + '_gpu_ids_' + str(opt.gpu_ids)
trainfile = os.path.join(expr_dir, prefix)
if not os.path.exists(trainfile):
os.makedirs(trainfile)
# Device
device = torch.device('cuda:{}'.format(opt.gpu_ids)) if torch.cuda.is_available() else torch.device('cpu')
# Directories for storing model and output samples
model_path = os.path.join(trainfile, 'model')
logs_path = os.path.join(trainfile, './logs')
setup_seed(opt.seed)
loader_train, band = PDBSNetData(opt)
| net = PDBSNet(band, band, nch_ker=opt.nch_ker, nblk=opt.nblk).to(device)
| 0 | 2023-10-16 08:28:56+00:00 | 4k |
AVAniketh0905/fluidspy | fluidspylib/fluidspy/tests/test_fdm.py | [
{
"identifier": "Bottom",
"path": "fluidspylib/fluidspy/numerical/boundary/direction.py",
"snippet": "class Bottom(Direction):\n \"\"\"Bottom direction.\"\"\"\n\n def __init__(\n self,\n initial_value: float,\n state: SimulationState,\n boundary_condition: BoundaryCondi... | import pytest
from ..numerical.boundary import Bottom
from ..numerical.boundary import CompositeBoundary
from ..numerical.boundary import Constant
from ..numerical.boundary import Insulated
from ..numerical.boundary import Left
from ..numerical.boundary import Right
from ..numerical.boundary import Top
from ..numerical.dim.dimension import OneDimSpatial
from ..numerical.dim.dimension import TwoDimSpatial
from ..numerical.material_properties import ThermalProperties
from ..numerical.methods.finite_differential import FTCS
from ..numerical.state import SimulationState
from ..numerical.step import Step
from ..numerical.step import Vector | 3,076 |
def create_state_dim(state, dim, shape):
dim = dim(state)
dim.create_grid(shape)
return dim
def test_ftcs():
state = SimulationState()
dim = create_state_dim(state, OneDimSpatial, 10)
boundary = CompositeBoundary(
Left(5, state, Constant()), Right(10, state, Insulated())
)
boundary.init_apply()
material = ThermalProperties("Copper", 8940, 385, 0.71, 401, 0.0016)
|
def create_state_dim(state, dim, shape):
dim = dim(state)
dim.create_grid(shape)
return dim
def test_ftcs():
state = SimulationState()
dim = create_state_dim(state, OneDimSpatial, 10)
boundary = CompositeBoundary(
Left(5, state, Constant()), Right(10, state, Insulated())
)
boundary.init_apply()
material = ThermalProperties("Copper", 8940, 385, 0.71, 401, 0.0016) | step = Step(0.1, Vector(0.1)) | 13 | 2023-10-21 06:55:58+00:00 | 4k |
jobless-devs/Jobhub | lambdas/packages/python/psycopg2/extras.py | [
{
"identifier": "PY2",
"path": "lambdas/packages/python/psycopg2/compat.py",
"snippet": "PY2 = True\nPY3 = False\nPY2 = False\nPY3 = True"
},
{
"identifier": "adapt",
"path": "lambdas/packages/python/psycopg2/extensions.py",
"snippet": "ISOLATION_LEVEL_AUTOCOMMIT = 0\nISOLATION_LEVEL_REA... | import logging as _logging
import os as _os
import re as _re
import time as _time
import psycopg2
import uuid
import warnings
import select
from collections import namedtuple, OrderedDict
from psycopg2 import extensions as _ext
from psycopg2._ipaddress import register_ipaddress # noqa
from psycopg2._json import ( # noqa
json, Json, register_json, register_default_json, register_default_jsonb)
from psycopg2._psycopg import ( # noqa
REPLICATION_PHYSICAL, REPLICATION_LOGICAL,
ReplicationConnection as _replicationConnection,
ReplicationCursor as _replicationCursor,
ReplicationMessage)
from psycopg2._range import ( # noqa
Range, NumericRange, DateRange, DateTimeRange, DateTimeTZRange,
register_range, RangeAdapter, RangeCaster)
from .compat import PY2, PY3, lru_cache
from .extensions import adapt as _A, quote_ident
from .extensions import connection as _connection
from .extensions import cursor as _cursor
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
from psycopg2.sql import Composable | 2,715 | if self._prefetch:
res = super(DictCursorBase, self).fetchmany(size)
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).fetchmany(size)
return res
def fetchall(self):
if self._prefetch:
res = super(DictCursorBase, self).fetchall()
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).fetchall()
return res
def __iter__(self):
try:
if self._prefetch:
res = super(DictCursorBase, self).__iter__()
first = next(res)
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).__iter__()
first = next(res)
yield first
while True:
yield next(res)
except StopIteration:
return
class DictConnection(_connection):
"""A connection that uses `DictCursor` automatically."""
def cursor(self, *args, **kwargs):
kwargs.setdefault('cursor_factory', self.cursor_factory or DictCursor)
return super(DictConnection, self).cursor(*args, **kwargs)
class DictCursor(DictCursorBase):
"""A cursor that keeps a list of column name -> index mappings."""
def __init__(self, *args, **kwargs):
kwargs['row_factory'] = DictRow
super(DictCursor, self).__init__(*args, **kwargs)
self._prefetch = True
def execute(self, query, vars=None):
self.index = OrderedDict()
self._query_executed = True
return super(DictCursor, self).execute(query, vars)
def callproc(self, procname, vars=None):
self.index = OrderedDict()
self._query_executed = True
return super(DictCursor, self).callproc(procname, vars)
def _build_index(self):
if self._query_executed and self.description:
for i in range(len(self.description)):
self.index[self.description[i][0]] = i
self._query_executed = False
class DictRow(list):
"""A row object that allow by-column-name access to data."""
__slots__ = ('_index',)
def __init__(self, cursor):
self._index = cursor.index
self[:] = [None] * len(cursor.description)
def __getitem__(self, x):
if not isinstance(x, (int, slice)):
x = self._index[x]
return super(DictRow, self).__getitem__(x)
def __setitem__(self, x, v):
if not isinstance(x, (int, slice)):
x = self._index[x]
super(DictRow, self).__setitem__(x, v)
def items(self):
g = super(DictRow, self).__getitem__
return ((n, g(self._index[n])) for n in self._index)
def keys(self):
return iter(self._index)
def values(self):
g = super(DictRow, self).__getitem__
return (g(self._index[n]) for n in self._index)
def get(self, x, default=None):
try:
return self[x]
except Exception:
return default
def copy(self):
return OrderedDict(self.items())
def __contains__(self, x):
return x in self._index
def __reduce__(self):
# this is apparently useless, but it fixes #1073
return super(DictRow, self).__reduce__()
def __getstate__(self):
return self[:], self._index.copy()
def __setstate__(self, data):
self[:] = data[0]
self._index = data[1]
| """Miscellaneous goodies for psycopg2
This module is a generic place used to hold little helper functions
and classes until a better place in the distribution is found.
"""
# psycopg/extras.py - miscellaneous extra goodies for psycopg
#
# Copyright (C) 2003-2019 Federico Di Gregorio <fog@debian.org>
# Copyright (C) 2020 The Psycopg Team
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# In addition, as a special exception, the copyright holders give
# permission to link this program with the OpenSSL library (or with
# modified versions of OpenSSL that use the same license as OpenSSL),
# and distribute linked combinations including the two.
#
# You must obey the GNU Lesser General Public License in all respects for
# all of the code used other than OpenSSL.
#
# psycopg2 is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
# Expose ipaddress-related objects
# expose the json adaptation stuff into the module
# Expose range-related objects
class DictCursorBase(_cursor):
"""Base class for all dict-like cursors."""
def __init__(self, *args, **kwargs):
if 'row_factory' in kwargs:
row_factory = kwargs['row_factory']
del kwargs['row_factory']
else:
raise NotImplementedError(
"DictCursorBase can't be instantiated without a row factory.")
super(DictCursorBase, self).__init__(*args, **kwargs)
self._query_executed = False
self._prefetch = False
self.row_factory = row_factory
def fetchone(self):
if self._prefetch:
res = super(DictCursorBase, self).fetchone()
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).fetchone()
return res
def fetchmany(self, size=None):
if self._prefetch:
res = super(DictCursorBase, self).fetchmany(size)
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).fetchmany(size)
return res
def fetchall(self):
if self._prefetch:
res = super(DictCursorBase, self).fetchall()
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).fetchall()
return res
def __iter__(self):
try:
if self._prefetch:
res = super(DictCursorBase, self).__iter__()
first = next(res)
if self._query_executed:
self._build_index()
if not self._prefetch:
res = super(DictCursorBase, self).__iter__()
first = next(res)
yield first
while True:
yield next(res)
except StopIteration:
return
class DictConnection(_connection):
"""A connection that uses `DictCursor` automatically."""
def cursor(self, *args, **kwargs):
kwargs.setdefault('cursor_factory', self.cursor_factory or DictCursor)
return super(DictConnection, self).cursor(*args, **kwargs)
class DictCursor(DictCursorBase):
"""A cursor that keeps a list of column name -> index mappings."""
def __init__(self, *args, **kwargs):
kwargs['row_factory'] = DictRow
super(DictCursor, self).__init__(*args, **kwargs)
self._prefetch = True
def execute(self, query, vars=None):
self.index = OrderedDict()
self._query_executed = True
return super(DictCursor, self).execute(query, vars)
def callproc(self, procname, vars=None):
self.index = OrderedDict()
self._query_executed = True
return super(DictCursor, self).callproc(procname, vars)
def _build_index(self):
if self._query_executed and self.description:
for i in range(len(self.description)):
self.index[self.description[i][0]] = i
self._query_executed = False
class DictRow(list):
"""A row object that allow by-column-name access to data."""
__slots__ = ('_index',)
def __init__(self, cursor):
self._index = cursor.index
self[:] = [None] * len(cursor.description)
def __getitem__(self, x):
if not isinstance(x, (int, slice)):
x = self._index[x]
return super(DictRow, self).__getitem__(x)
def __setitem__(self, x, v):
if not isinstance(x, (int, slice)):
x = self._index[x]
super(DictRow, self).__setitem__(x, v)
def items(self):
g = super(DictRow, self).__getitem__
return ((n, g(self._index[n])) for n in self._index)
def keys(self):
return iter(self._index)
def values(self):
g = super(DictRow, self).__getitem__
return (g(self._index[n]) for n in self._index)
def get(self, x, default=None):
try:
return self[x]
except Exception:
return default
def copy(self):
return OrderedDict(self.items())
def __contains__(self, x):
return x in self._index
def __reduce__(self):
# this is apparently useless, but it fixes #1073
return super(DictRow, self).__reduce__()
def __getstate__(self):
return self[:], self._index.copy()
def __setstate__(self, data):
self[:] = data[0]
self._index = data[1]
| if PY2: | 0 | 2023-10-22 20:09:51+00:00 | 4k |
kyegomez/gradient-ascent | visualization.py | [
{
"identifier": "GradientAscent",
"path": "gradient_ascent/main.py",
"snippet": "class GradientAscent:\n \"\"\"\n Gradient Ascent Optimizer\n\n Optimizer that performs gradient ascent on the parameters of the model.\n\n Args:\n parameters (iterable): iterable of parameters to optimize... | import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib.animation import FuncAnimation
from gradient_ascent import GradientAscent
from gradient_ascent.main import GradientAscent | 2,636 |
class SimpleModel(torch.nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = torch.nn.Linear(1, 1)
def forward(self, x):
return self.fc(x)
# Set up real-time plotting
plt.ion() # Turn on interactive mode
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlim(0, 1000) # Assuming 1000 epochs
ax.set_ylim(0, 10) # Arbitrary y-axis limits for visualization purposes
ax.set_title("Model Output vs. Target during Training")
ax.set_xlabel("Epoch")
ax.set_ylabel("Value")
(line_output,) = ax.plot([], [], "r-", label="Model Output")
(line_target,) = ax.plot([], [], "g-", label="Target Value")
ax.legend()
# Initialization function for the animation
def init():
line_output.set_data([], [])
line_target.set_data([], [])
return line_output, line_target
def update(epoch, model_output_value):
x_data_output, y_data_output = line_output.get_data()
x_data_target, y_data_target = line_target.get_data()
# Convert numpy arrays to lists only if they aren't already lists
if not isinstance(x_data_output, list):
x_data_output = x_data_output.tolist()
if not isinstance(y_data_output, list):
y_data_output = y_data_output.tolist()
if not isinstance(x_data_target, list):
x_data_target = x_data_target.tolist()
if not isinstance(y_data_target, list):
y_data_target = y_data_target.tolist()
# Append new data
x_data_output.append(epoch)
y_data_output.append(model_output_value)
x_data_target.append(epoch)
y_data_target.append(target.item())
line_output.set_data(x_data_output, y_data_output)
line_target.set_data(x_data_target, y_data_target)
fig.canvas.flush_events()
return line_output, line_target
# Test the optimizer
model = SimpleModel()
# Define the optimizer
|
class SimpleModel(torch.nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = torch.nn.Linear(1, 1)
def forward(self, x):
return self.fc(x)
# Set up real-time plotting
plt.ion() # Turn on interactive mode
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlim(0, 1000) # Assuming 1000 epochs
ax.set_ylim(0, 10) # Arbitrary y-axis limits for visualization purposes
ax.set_title("Model Output vs. Target during Training")
ax.set_xlabel("Epoch")
ax.set_ylabel("Value")
(line_output,) = ax.plot([], [], "r-", label="Model Output")
(line_target,) = ax.plot([], [], "g-", label="Target Value")
ax.legend()
# Initialization function for the animation
def init():
line_output.set_data([], [])
line_target.set_data([], [])
return line_output, line_target
def update(epoch, model_output_value):
x_data_output, y_data_output = line_output.get_data()
x_data_target, y_data_target = line_target.get_data()
# Convert numpy arrays to lists only if they aren't already lists
if not isinstance(x_data_output, list):
x_data_output = x_data_output.tolist()
if not isinstance(y_data_output, list):
y_data_output = y_data_output.tolist()
if not isinstance(x_data_target, list):
x_data_target = x_data_target.tolist()
if not isinstance(y_data_target, list):
y_data_target = y_data_target.tolist()
# Append new data
x_data_output.append(epoch)
y_data_output.append(model_output_value)
x_data_target.append(epoch)
y_data_target.append(target.item())
line_output.set_data(x_data_output, y_data_output)
line_target.set_data(x_data_target, y_data_target)
fig.canvas.flush_events()
return line_output, line_target
# Test the optimizer
model = SimpleModel()
# Define the optimizer | optimizer = GradientAscent( | 1 | 2023-10-21 01:14:22+00:00 | 4k |
cfs-energy/cfspopcon | cfspopcon/formulas/scrape_off_layer_model/lambda_q.py | [
{
"identifier": "LambdaQScaling",
"path": "cfspopcon/named_options.py",
"snippet": "class LambdaQScaling(Enum):\n \"\"\"Options for heat flux decay length scaling.\"\"\"\n\n Brunner = auto()\n EichRegression14 = auto()\n EichRegression15 = auto()"
},
{
"identifier": "wraps_ufunc",
... | from ...named_options import LambdaQScaling
from ...unit_handling import ureg, wraps_ufunc | 2,160 | """Routines to calculate the heat flux decay length (lambda_q), for several different scalings."""
@wraps_ufunc(
return_units=dict(lambda_q=ureg.millimeter),
input_units=dict(
lambda_q_scaling=None,
average_total_pressure=ureg.atm,
power_crossing_separatrix=ureg.megawatt,
major_radius=ureg.meter,
B_pol_omp=ureg.tesla,
inverse_aspect_ratio=ureg.dimensionless,
),
)
def calc_lambda_q(
| """Routines to calculate the heat flux decay length (lambda_q), for several different scalings."""
@wraps_ufunc(
return_units=dict(lambda_q=ureg.millimeter),
input_units=dict(
lambda_q_scaling=None,
average_total_pressure=ureg.atm,
power_crossing_separatrix=ureg.megawatt,
major_radius=ureg.meter,
B_pol_omp=ureg.tesla,
inverse_aspect_ratio=ureg.dimensionless,
),
)
def calc_lambda_q( | lambda_q_scaling: LambdaQScaling, | 0 | 2023-10-19 16:58:23+00:00 | 4k |
GXimingLu/IPA | policy_gp3.py | [
{
"identifier": "ConstrainedHypothesis",
"path": "lexical_constraints.py",
"snippet": "class ConstrainedHypothesis:\n\n def __init__(self,\n constraint_list: List[List[List[int]]],\n eos_tokens: List[int]) -> None:\n self.clauses = []\n for idx, clause in... | import torch
import torch.nn.functional as F
import json
import numpy as np
import openai
from typing import Union, List, Dict
from transformers import GPT2LMHeadModel, GPT2Tokenizer
from lexical_constraints import ConstrainedHypothesis, init_batch
from utils.constants import NEGATIVE_INF, OPENAI_API_KEY
from utils.utils import process_generation
from utils.generation_utils import add_control_code, get_model_output | 2,234 |
openai.api_key = OPENAI_API_KEY
class Policy:
def __init__(self, value_model_name, value_model_checkpoint, device, tree_tokens, alpha, force_eos):
self.device = device
self.value_model = GPT2LMHeadModel.from_pretrained(value_model_name)
self.tokenizer = GPT2Tokenizer.from_pretrained(value_model_name, pad_token="<|endoftext|>")
self.value_model.config.pad_token_id = self.tokenizer.pad_token_id
self.tokenizer.add_tokens(tree_tokens, special_tokens=True)
self.value_model.resize_token_embeddings(len(self.tokenizer))
self.value_model.load_state_dict(value_model_checkpoint)
self.value_model = self.value_model.to(self.device)
self.value_model.parallelize()
self.best_cat = tree_tokens[0]
self.best_cat_id = self.tokenizer.convert_tokens_to_ids(self.best_cat)
self.alpha = alpha
self.eos_tokens = None
if force_eos:
self.eos_tokens = self.tokenizer.convert_tokens_to_ids(['.', 'Ġ.', '!', 'Ġ!'])
def request(self, queries: List[str], model='text-davinci-003'):
# Retry request (handles connection errors, timeouts, and overloaded API)
while True:
try:
return openai.Completion.create(
engine=model,
prompt=queries,
max_tokens=1, # get logits for next token
logprobs=100, # max tokens allowable
n=1,
echo=True,
)
except Exception as e:
print(str(e))
print("Retrying...")
def get_gpt3_logits(self, input_ids):
queries = self.tokenizer.batch_decode(input_ids, skip_special_tokens=True)
response = self.request(queries)
response_logits = [choice['logprobs']['top_logprobs'] for choice in response['choices']]
gpt3_logits = -50000.0 * torch.ones([len(queries), len(self.tokenizer)], dtype=torch.float32).to(self.device)
for i in range(len(queries)):
response_dict = response_logits[i][-1] # get 0 index predictions
for token, logit in response_dict.items():
token_idx = self.tokenizer.convert_tokens_to_ids(token.replace(' ', 'Ġ').replace('\n', 'Ċ'))
if token != '<|endoftext|>' and token_idx == 50256:
continue
gpt3_logits[i, token_idx] = logit
return gpt3_logits
def sample(self,
prompts: Union[str, List[str]] = None,
input_ids: torch.Tensor = None,
attention_mask: torch.Tensor = None,
constraints: List[ConstrainedHypothesis] = None,
max_len: int = 64,
min_len: int = 16,
sample: bool = True,
top_k: int = None,
top_p: float = None,
temperature: float = None,
use_control_code: bool = False) -> Dict[str, Union[torch.Tensor, List[str]]]:
use_constraints = constraints is not None
if use_constraints:
constraints = init_batch([json.loads(x) for x in constraints], self.eos_tokens)
if prompts is not None:
assert input_ids is None and attention_mask is None, 'repeated input'
if isinstance(prompts, str):
prompts = [prompts]
encodings_dict = self.tokenizer(prompts, return_tensors="pt", padding=True)
input_ids = encodings_dict['input_ids'].to(self.device)
attention_mask = encodings_dict['attention_mask'].to(self.device)
else:
input_ids = input_ids.to(self.device)
attention_mask = attention_mask.to(self.device)
batch_size, input_seq_len = input_ids.shape
value_input_ids, value_attention_mask = add_control_code(input_ids, attention_mask, self.best_cat_id)
value_model_kwargs = {'attention_mask': value_attention_mask}
logits_warper = self.value_model._get_logits_warper(
top_k=top_k, top_p=top_p, temperature=temperature, num_beams=1
)
unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=self.device)
output_logprob = torch.zeros([batch_size, 0], dtype=torch.float, device=self.device)
output_mask = torch.ones([batch_size, 0], dtype=torch.long, device=self.device)
self.value_model.eval()
with torch.no_grad():
for step in range(max_len):
next_token_logits = self.get_gpt3_logits(input_ids)
# get logit from value model
if use_control_code:
|
openai.api_key = OPENAI_API_KEY
class Policy:
def __init__(self, value_model_name, value_model_checkpoint, device, tree_tokens, alpha, force_eos):
self.device = device
self.value_model = GPT2LMHeadModel.from_pretrained(value_model_name)
self.tokenizer = GPT2Tokenizer.from_pretrained(value_model_name, pad_token="<|endoftext|>")
self.value_model.config.pad_token_id = self.tokenizer.pad_token_id
self.tokenizer.add_tokens(tree_tokens, special_tokens=True)
self.value_model.resize_token_embeddings(len(self.tokenizer))
self.value_model.load_state_dict(value_model_checkpoint)
self.value_model = self.value_model.to(self.device)
self.value_model.parallelize()
self.best_cat = tree_tokens[0]
self.best_cat_id = self.tokenizer.convert_tokens_to_ids(self.best_cat)
self.alpha = alpha
self.eos_tokens = None
if force_eos:
self.eos_tokens = self.tokenizer.convert_tokens_to_ids(['.', 'Ġ.', '!', 'Ġ!'])
def request(self, queries: List[str], model='text-davinci-003'):
# Retry request (handles connection errors, timeouts, and overloaded API)
while True:
try:
return openai.Completion.create(
engine=model,
prompt=queries,
max_tokens=1, # get logits for next token
logprobs=100, # max tokens allowable
n=1,
echo=True,
)
except Exception as e:
print(str(e))
print("Retrying...")
def get_gpt3_logits(self, input_ids):
queries = self.tokenizer.batch_decode(input_ids, skip_special_tokens=True)
response = self.request(queries)
response_logits = [choice['logprobs']['top_logprobs'] for choice in response['choices']]
gpt3_logits = -50000.0 * torch.ones([len(queries), len(self.tokenizer)], dtype=torch.float32).to(self.device)
for i in range(len(queries)):
response_dict = response_logits[i][-1] # get 0 index predictions
for token, logit in response_dict.items():
token_idx = self.tokenizer.convert_tokens_to_ids(token.replace(' ', 'Ġ').replace('\n', 'Ċ'))
if token != '<|endoftext|>' and token_idx == 50256:
continue
gpt3_logits[i, token_idx] = logit
return gpt3_logits
def sample(self,
prompts: Union[str, List[str]] = None,
input_ids: torch.Tensor = None,
attention_mask: torch.Tensor = None,
constraints: List[ConstrainedHypothesis] = None,
max_len: int = 64,
min_len: int = 16,
sample: bool = True,
top_k: int = None,
top_p: float = None,
temperature: float = None,
use_control_code: bool = False) -> Dict[str, Union[torch.Tensor, List[str]]]:
use_constraints = constraints is not None
if use_constraints:
constraints = init_batch([json.loads(x) for x in constraints], self.eos_tokens)
if prompts is not None:
assert input_ids is None and attention_mask is None, 'repeated input'
if isinstance(prompts, str):
prompts = [prompts]
encodings_dict = self.tokenizer(prompts, return_tensors="pt", padding=True)
input_ids = encodings_dict['input_ids'].to(self.device)
attention_mask = encodings_dict['attention_mask'].to(self.device)
else:
input_ids = input_ids.to(self.device)
attention_mask = attention_mask.to(self.device)
batch_size, input_seq_len = input_ids.shape
value_input_ids, value_attention_mask = add_control_code(input_ids, attention_mask, self.best_cat_id)
value_model_kwargs = {'attention_mask': value_attention_mask}
logits_warper = self.value_model._get_logits_warper(
top_k=top_k, top_p=top_p, temperature=temperature, num_beams=1
)
unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=self.device)
output_logprob = torch.zeros([batch_size, 0], dtype=torch.float, device=self.device)
output_mask = torch.ones([batch_size, 0], dtype=torch.long, device=self.device)
self.value_model.eval()
with torch.no_grad():
for step in range(max_len):
next_token_logits = self.get_gpt3_logits(input_ids)
# get logit from value model
if use_control_code: | value_outputs, value_next_token_logits = get_model_output(self.value_model, step, value_input_ids, | 6 | 2023-10-20 08:30:18+00:00 | 4k |
yifei-he/GOAT | experiments.py | [
{
"identifier": "ot_ablation",
"path": "ot_util.py",
"snippet": "def ot_ablation(size, mode):\n ns, nt = size, size\n plan = np.zeros((ns, nt))\n ran = np.arange(ns*nt)\n np.random.shuffle(ran)\n idx = ran[:size]\n\n for i in idx:\n row = i // nt\n col = i-i//nt * nt\n ... | import torch
import torch.optim as optim
import copy
import argparse
import random
import torch.backends.cudnn as cudnn
import time
from model import *
from train_model import *
from util import *
from ot_util import ot_ablation
from da_algo import *
from ot_util import generate_domains
from dataset import * | 1,769 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_source_model(args, trainset, testset, n_class, mode, encoder=None, epochs=50, verbose=True):
print("Start training source model")
model = Classifier(encoder, MLP(mode=mode, n_class=n_class, hidden=1024)).to(device)
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-4)
trainloader = DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers)
testloader = DataLoader(testset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)
for epoch in range(1, epochs+1):
train(epoch, trainloader, model, optimizer, verbose=verbose)
if epoch % 5 == 0:
test(testloader, model, verbose=verbose)
return model
def run_goat(model_copy, source_model, src_trainset, tgt_trainset, all_sets, generated_domains, epochs=10):
# get the performance of direct adaptation from the source to target, st involves self-training on target
direct_acc, st_acc = self_train(args, model_copy, [tgt_trainset], epochs=epochs)
# get the performance of GST from the source to target, st involves self-training on target
direct_acc_all, st_acc_all = self_train(args, source_model, all_sets, epochs=epochs)
# encode the source and target domains
e_src_trainset, e_tgt_trainset = get_encoded_dataset(source_model.encoder, src_trainset), get_encoded_dataset(source_model.encoder, tgt_trainset)
# encode the intermediate ground-truth domains
intersets = all_sets[:-1]
encoded_intersets = [e_src_trainset]
for i in intersets:
encoded_intersets.append(get_encoded_dataset(source_model.encoder, i))
encoded_intersets.append(e_tgt_trainset)
# generate intermediate domains
generated_acc = 0
if generated_domains > 0:
all_domains = []
for i in range(len(encoded_intersets)-1):
all_domains += generate_domains(generated_domains, encoded_intersets[i], encoded_intersets[i+1])
_, generated_acc = self_train(args, source_model.mlp, all_domains, epochs=epochs)
return direct_acc, st_acc, direct_acc_all, st_acc_all, generated_acc
def run_mnist_experiment(target, gt_domains, generated_domains):
t = time.time()
src_trainset, tgt_trainset = get_single_rotate(False, 0), get_single_rotate(False, target)
encoder = ENCODER().to(device)
source_model = get_source_model(args, src_trainset, src_trainset, 10, "mnist", encoder=encoder, epochs=5)
model_copy = copy.deepcopy(source_model)
all_sets = []
for i in range(1, gt_domains+1):
all_sets.append(get_single_rotate(False, i*target//(gt_domains+1)))
print(i*target//(gt_domains+1))
all_sets.append(tgt_trainset)
direct_acc, st_acc, direct_acc_all, st_acc_all, generated_acc = run_goat(model_copy, source_model, src_trainset, tgt_trainset, all_sets, generated_domains, epochs=5)
elapsed = round(time.time() - t, 2)
print(elapsed)
with open(f"logs/mnist_{target}_{gt_domains}_layer.txt", "a") as f:
f.write(f"seed{args.seed}with{gt_domains}gt{generated_domains}generated,{round(direct_acc, 2)},{round(st_acc, 2)},{round(direct_acc_all, 2)},{round(st_acc_all, 2)},{round(generated_acc, 2)}\n")
def run_mnist_ablation(target, gt_domains, generated_domains):
encoder = ENCODER().to(device)
src_trainset, tgt_trainset = get_single_rotate(False, 0), get_single_rotate(False, target)
source_model = get_source_model(args, src_trainset, src_trainset, 10, "mnist", encoder=encoder, epochs=20)
model_copy = copy.deepcopy(source_model)
all_sets = []
for i in range(1, gt_domains+1):
all_sets.append(get_single_rotate(False, i*target//(gt_domains+1)))
print(i*target//(gt_domains+1))
all_sets.append(tgt_trainset)
direct_acc, st_acc = self_train(args, model_copy, [tgt_trainset], epochs=10)
direct_acc_all, st_acc_all = self_train(args, source_model, all_sets, epochs=10)
model_copy1 = copy.deepcopy(source_model)
model_copy2 = copy.deepcopy(source_model)
model_copy3 = copy.deepcopy(source_model)
model_copy4 = copy.deepcopy(source_model)
e_src_trainset, e_tgt_trainset = get_encoded_dataset(source_model.encoder, src_trainset), get_encoded_dataset(source_model.encoder, tgt_trainset)
intersets = all_sets[:-1]
encoded_intersets = [e_src_trainset]
for i in intersets:
encoded_intersets.append(get_encoded_dataset(source_model.encoder, i))
encoded_intersets.append(e_tgt_trainset)
# random plan
all_domains1 = []
for i in range(len(encoded_intersets)-1):
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_source_model(args, trainset, testset, n_class, mode, encoder=None, epochs=50, verbose=True):
print("Start training source model")
model = Classifier(encoder, MLP(mode=mode, n_class=n_class, hidden=1024)).to(device)
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-4)
trainloader = DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers)
testloader = DataLoader(testset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)
for epoch in range(1, epochs+1):
train(epoch, trainloader, model, optimizer, verbose=verbose)
if epoch % 5 == 0:
test(testloader, model, verbose=verbose)
return model
def run_goat(model_copy, source_model, src_trainset, tgt_trainset, all_sets, generated_domains, epochs=10):
# get the performance of direct adaptation from the source to target, st involves self-training on target
direct_acc, st_acc = self_train(args, model_copy, [tgt_trainset], epochs=epochs)
# get the performance of GST from the source to target, st involves self-training on target
direct_acc_all, st_acc_all = self_train(args, source_model, all_sets, epochs=epochs)
# encode the source and target domains
e_src_trainset, e_tgt_trainset = get_encoded_dataset(source_model.encoder, src_trainset), get_encoded_dataset(source_model.encoder, tgt_trainset)
# encode the intermediate ground-truth domains
intersets = all_sets[:-1]
encoded_intersets = [e_src_trainset]
for i in intersets:
encoded_intersets.append(get_encoded_dataset(source_model.encoder, i))
encoded_intersets.append(e_tgt_trainset)
# generate intermediate domains
generated_acc = 0
if generated_domains > 0:
all_domains = []
for i in range(len(encoded_intersets)-1):
all_domains += generate_domains(generated_domains, encoded_intersets[i], encoded_intersets[i+1])
_, generated_acc = self_train(args, source_model.mlp, all_domains, epochs=epochs)
return direct_acc, st_acc, direct_acc_all, st_acc_all, generated_acc
def run_mnist_experiment(target, gt_domains, generated_domains):
t = time.time()
src_trainset, tgt_trainset = get_single_rotate(False, 0), get_single_rotate(False, target)
encoder = ENCODER().to(device)
source_model = get_source_model(args, src_trainset, src_trainset, 10, "mnist", encoder=encoder, epochs=5)
model_copy = copy.deepcopy(source_model)
all_sets = []
for i in range(1, gt_domains+1):
all_sets.append(get_single_rotate(False, i*target//(gt_domains+1)))
print(i*target//(gt_domains+1))
all_sets.append(tgt_trainset)
direct_acc, st_acc, direct_acc_all, st_acc_all, generated_acc = run_goat(model_copy, source_model, src_trainset, tgt_trainset, all_sets, generated_domains, epochs=5)
elapsed = round(time.time() - t, 2)
print(elapsed)
with open(f"logs/mnist_{target}_{gt_domains}_layer.txt", "a") as f:
f.write(f"seed{args.seed}with{gt_domains}gt{generated_domains}generated,{round(direct_acc, 2)},{round(st_acc, 2)},{round(direct_acc_all, 2)},{round(st_acc_all, 2)},{round(generated_acc, 2)}\n")
def run_mnist_ablation(target, gt_domains, generated_domains):
encoder = ENCODER().to(device)
src_trainset, tgt_trainset = get_single_rotate(False, 0), get_single_rotate(False, target)
source_model = get_source_model(args, src_trainset, src_trainset, 10, "mnist", encoder=encoder, epochs=20)
model_copy = copy.deepcopy(source_model)
all_sets = []
for i in range(1, gt_domains+1):
all_sets.append(get_single_rotate(False, i*target//(gt_domains+1)))
print(i*target//(gt_domains+1))
all_sets.append(tgt_trainset)
direct_acc, st_acc = self_train(args, model_copy, [tgt_trainset], epochs=10)
direct_acc_all, st_acc_all = self_train(args, source_model, all_sets, epochs=10)
model_copy1 = copy.deepcopy(source_model)
model_copy2 = copy.deepcopy(source_model)
model_copy3 = copy.deepcopy(source_model)
model_copy4 = copy.deepcopy(source_model)
e_src_trainset, e_tgt_trainset = get_encoded_dataset(source_model.encoder, src_trainset), get_encoded_dataset(source_model.encoder, tgt_trainset)
intersets = all_sets[:-1]
encoded_intersets = [e_src_trainset]
for i in intersets:
encoded_intersets.append(get_encoded_dataset(source_model.encoder, i))
encoded_intersets.append(e_tgt_trainset)
# random plan
all_domains1 = []
for i in range(len(encoded_intersets)-1): | plan = ot_ablation(len(src_trainset), "random") | 0 | 2023-10-20 16:41:00+00:00 | 4k |
ansible/django-ansible-base | ansible_base/tests/unit/utils/test_validation.py | [
{
"identifier": "to_python_boolean",
"path": "ansible_base/utils/validation.py",
"snippet": "def to_python_boolean(value, allow_none=False):\n value = str(value)\n if value.lower() in ('true', '1', 't'):\n return True\n elif value.lower() in ('false', '0', 'f'):\n return False\n ... | import pytest
from rest_framework.exceptions import ValidationError
from ansible_base.utils.validation import to_python_boolean, validate_cert_with_key, validate_image_data, validate_url | 1,721 |
@pytest.mark.parametrize(
"valid,url,schemes,allow_plain_hostname",
[
(False, 4, [], True),
(False, "https://example", ['https'], False),
(True, "https://example", ['https'], True),
(True, "https://somedomain.example.com/sso/complete/saml/", ['https'], True),
(False, "https://somedomain.example.com/sso/complete/saml/", ['ldaps'], True),
(True, "ldaps://somedomain.example.com/sso/complete/saml/", ['ldaps'], True),
(False, "https://somedomain.[obfuscated.domain]/sso/complete/saml/", ['https'], True),
],
)
def test_validate_bad_urls(valid, url, schemes, allow_plain_hostname):
exception = None
try:
validate_url(url, schemes=schemes, allow_plain_hostname=allow_plain_hostname)
except ValidationError as e:
exception = e
if valid and exception:
assert False, f"Configuration should have been valid but got exception: {exception}"
elif not valid and not exception:
assert False, "Expected an exception but test passed"
@pytest.mark.parametrize(
"cert, key",
[
(False, False),
(None, None),
(None, False),
(False, None),
("", ""),
("", None),
(None, ""),
("", "asdf"),
("asdf", ""),
("asdf", None),
(None, "asdf"),
],
)
def test_validate_cert_with_key_falsy_param(cert, key):
"""
Ensure that validate_cert_with_key returns None when passed falsy values.
"""
assert validate_cert_with_key(cert, key) is None
@pytest.mark.parametrize(
"cert, key",
[
("asdf", "asdf"),
# In the below, None, means use the value from the fixture
(None, "asdf"),
("asdf", None),
],
)
def test_validate_cert_with_key_invalid_params(rsa_keypair_with_cert, cert, key):
"""
Ensure that validate_cert_with_key is False when it fails to load a cert or key.
"""
if cert is None:
cert = rsa_keypair_with_cert.certificate
if key is None:
key = rsa_keypair_with_cert.private
assert validate_cert_with_key(cert, key) is False
def test_validate_cert_with_key_mismatch(rsa_keypair_with_cert_1, rsa_keypair_with_cert_2):
"""
Ensure that validate_cert_with_key raises a ValidationError when the cert and key don't match.
"""
with pytest.raises(ValidationError) as e:
validate_cert_with_key(rsa_keypair_with_cert_1.certificate, rsa_keypair_with_cert_2.private)
assert "The certificate and private key do not match" in str(e.value)
def test_validate_image_data_with_valid_data():
"""
Ensure that validate_image_data accepts valid data.
"""
image_data = "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs="
|
@pytest.mark.parametrize(
"valid,url,schemes,allow_plain_hostname",
[
(False, 4, [], True),
(False, "https://example", ['https'], False),
(True, "https://example", ['https'], True),
(True, "https://somedomain.example.com/sso/complete/saml/", ['https'], True),
(False, "https://somedomain.example.com/sso/complete/saml/", ['ldaps'], True),
(True, "ldaps://somedomain.example.com/sso/complete/saml/", ['ldaps'], True),
(False, "https://somedomain.[obfuscated.domain]/sso/complete/saml/", ['https'], True),
],
)
def test_validate_bad_urls(valid, url, schemes, allow_plain_hostname):
exception = None
try:
validate_url(url, schemes=schemes, allow_plain_hostname=allow_plain_hostname)
except ValidationError as e:
exception = e
if valid and exception:
assert False, f"Configuration should have been valid but got exception: {exception}"
elif not valid and not exception:
assert False, "Expected an exception but test passed"
@pytest.mark.parametrize(
"cert, key",
[
(False, False),
(None, None),
(None, False),
(False, None),
("", ""),
("", None),
(None, ""),
("", "asdf"),
("asdf", ""),
("asdf", None),
(None, "asdf"),
],
)
def test_validate_cert_with_key_falsy_param(cert, key):
"""
Ensure that validate_cert_with_key returns None when passed falsy values.
"""
assert validate_cert_with_key(cert, key) is None
@pytest.mark.parametrize(
"cert, key",
[
("asdf", "asdf"),
# In the below, None, means use the value from the fixture
(None, "asdf"),
("asdf", None),
],
)
def test_validate_cert_with_key_invalid_params(rsa_keypair_with_cert, cert, key):
"""
Ensure that validate_cert_with_key is False when it fails to load a cert or key.
"""
if cert is None:
cert = rsa_keypair_with_cert.certificate
if key is None:
key = rsa_keypair_with_cert.private
assert validate_cert_with_key(cert, key) is False
def test_validate_cert_with_key_mismatch(rsa_keypair_with_cert_1, rsa_keypair_with_cert_2):
"""
Ensure that validate_cert_with_key raises a ValidationError when the cert and key don't match.
"""
with pytest.raises(ValidationError) as e:
validate_cert_with_key(rsa_keypair_with_cert_1.certificate, rsa_keypair_with_cert_2.private)
assert "The certificate and private key do not match" in str(e.value)
def test_validate_image_data_with_valid_data():
"""
Ensure that validate_image_data accepts valid data.
"""
image_data = "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=" | res = validate_image_data(image_data) | 2 | 2023-10-20 13:20:12+00:00 | 4k |
violet-sto/HN-GFN | dataset.py | [
{
"identifier": "MolMDPExtended",
"path": "mol_mdp_ext.py",
"snippet": "class MolMDPExtended(MolMDP):\n\n def build_translation_table(self):\n \"\"\"build a symmetry mapping for blocks. Necessary to compute parent transitions\"\"\"\n self.translation_table = {}\n for blockidx in ... | import pandas as pd
import numpy as np
import torch
import time
import threading
import json
from sklearn.utils import shuffle
from mol_mdp_ext import MolMDPExtended, BlockMoleculeDataExtended
from tqdm import tqdm
from botorch.utils.multi_objective.hypervolume import Hypervolume | 3,098 |
class Dataset:
def __init__(self, args, bpath, oracle, device):
self.test_split_rng = np.random.RandomState(142857)
self.train_rng = np.random.RandomState(int(time.time()))
self.train_mols = []
self.test_mols = []
self.all_mols = []
self.train_mols_map = {}
|
class Dataset:
def __init__(self, args, bpath, oracle, device):
self.test_split_rng = np.random.RandomState(142857)
self.train_rng = np.random.RandomState(int(time.time()))
self.train_mols = []
self.test_mols = []
self.all_mols = []
self.train_mols_map = {}
| self.mdp = MolMDPExtended(bpath) | 0 | 2023-10-24 14:10:35+00:00 | 4k |
line/Skeleton-Temporal-Action-Localization | evaluation/eval.py | [
{
"identifier": "getClassificationMAP",
"path": "evaluation/classificationMAP.py",
"snippet": "def getClassificationMAP(confidence, labels):\n \"\"\" confidence and labels are of dimension n_samples x n_label \"\"\"\n\n AP = []\n for i in range(np.shape(labels)[1]):\n AP.append(getAP(con... | import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from .classificationMAP import getClassificationMAP as cmAP
from .detectionMAP import getSingleStreamDetectionMAP as dsmAP
from .detectionMAP import getTwoStreamDetectionMAP as dtmAP
from .utils import write_results_to_eval_file, write_results_to_file | 1,845 |
def ss_eval(epoch, dataloader, args, logger, model, device):
vid_preds = []
frm_preds = []
vid_lens = []
labels = []
for num, sample in enumerate(dataloader):
if (num + 1) % 100 == 0:
print("Testing test data point %d of %d" % (num + 1, len(dataloader)))
features = sample["data"].numpy()
label = sample["labels"].numpy()
vid_len = sample["vid_len"].numpy()
features = torch.from_numpy(features).float().to(device)
with torch.no_grad():
_, vid_pred, _, frm_scr = model(Variable(features))
frm_pred = F.softmax(frm_scr, -1)
vid_pred = np.squeeze(vid_pred.cpu().data.numpy(), axis=0)
frm_pred = np.squeeze(frm_pred.cpu().data.numpy(), axis=0)
label = np.squeeze(label, axis=0)
vid_preds.append(vid_pred)
frm_preds.append(frm_pred)
vid_lens.append(vid_len)
labels.append(label)
vid_preds = np.array(vid_preds)
frm_preds = np.array(frm_preds)
vid_lens = np.array(vid_lens)
labels = np.array(labels)
cmap = cmAP(vid_preds, labels)
dmap, iou = dsmAP(
vid_preds, frm_preds, vid_lens, dataloader.dataset.path_to_annotations, args
)
print("Classification map %f" % cmap)
for item in list(zip(iou, dmap)):
print("Detection map @ %f = %f" % (item[0], item[1]))
logger.log_value("Test Classification mAP", cmap, epoch)
for item in list(zip(dmap, iou)):
logger.log_value("Test Detection1 mAP @ IoU = " + str(item[1]), item[0], epoch)
write_results_to_file(args, dmap, cmap, epoch)
def ts_eval(dataloader, args, logger, rgb_model, flow_model, device):
rgb_vid_preds = []
rgb_frame_preds = []
flow_vid_preds = []
flow_frame_preds = []
vid_lens = []
labels = []
for num, sample in enumerate(dataloader):
if (num + 1) % 100 == 0:
print("Testing test data point %d of %d" % (num + 1, len(dataloader)))
rgb_features = sample["rgb_data"].numpy()
flow_features = sample["flow_data"].numpy()
label = sample["labels"].numpy()
vid_len = sample["vid_len"].numpy()
rgb_features_inp = torch.from_numpy(rgb_features).float().to(device)
flow_features_inp = torch.from_numpy(flow_features).float().to(device)
with torch.no_grad():
_, rgb_video_pred, _, rgb_frame_scr = rgb_model(Variable(rgb_features_inp))
_, flow_video_pred, _, flow_frame_scr = flow_model(
Variable(flow_features_inp)
)
rgb_frame_pred = F.softmax(rgb_frame_scr, -1)
flow_frame_pred = F.softmax(flow_frame_scr, -1)
rgb_frame_pred = np.squeeze(rgb_frame_pred.cpu().data.numpy(), axis=0)
flow_frame_pred = np.squeeze(flow_frame_pred.cpu().data.numpy(), axis=0)
rgb_video_pred = np.squeeze(rgb_video_pred.cpu().data.numpy(), axis=0)
flow_video_pred = np.squeeze(flow_video_pred.cpu().data.numpy(), axis=0)
label = np.squeeze(label, axis=0)
rgb_vid_preds.append(rgb_video_pred)
rgb_frame_preds.append(rgb_frame_pred)
flow_vid_preds.append(flow_video_pred)
flow_frame_preds.append(flow_frame_pred)
vid_lens.append(vid_len)
labels.append(label)
rgb_vid_preds = np.array(rgb_vid_preds)
rgb_frame_preds = np.array(rgb_frame_preds)
flow_vid_preds = np.array(flow_vid_preds)
flow_frame_preds = np.array(flow_frame_preds)
vid_lens = np.array(vid_lens)
labels = np.array(labels)
|
def ss_eval(epoch, dataloader, args, logger, model, device):
vid_preds = []
frm_preds = []
vid_lens = []
labels = []
for num, sample in enumerate(dataloader):
if (num + 1) % 100 == 0:
print("Testing test data point %d of %d" % (num + 1, len(dataloader)))
features = sample["data"].numpy()
label = sample["labels"].numpy()
vid_len = sample["vid_len"].numpy()
features = torch.from_numpy(features).float().to(device)
with torch.no_grad():
_, vid_pred, _, frm_scr = model(Variable(features))
frm_pred = F.softmax(frm_scr, -1)
vid_pred = np.squeeze(vid_pred.cpu().data.numpy(), axis=0)
frm_pred = np.squeeze(frm_pred.cpu().data.numpy(), axis=0)
label = np.squeeze(label, axis=0)
vid_preds.append(vid_pred)
frm_preds.append(frm_pred)
vid_lens.append(vid_len)
labels.append(label)
vid_preds = np.array(vid_preds)
frm_preds = np.array(frm_preds)
vid_lens = np.array(vid_lens)
labels = np.array(labels)
cmap = cmAP(vid_preds, labels)
dmap, iou = dsmAP(
vid_preds, frm_preds, vid_lens, dataloader.dataset.path_to_annotations, args
)
print("Classification map %f" % cmap)
for item in list(zip(iou, dmap)):
print("Detection map @ %f = %f" % (item[0], item[1]))
logger.log_value("Test Classification mAP", cmap, epoch)
for item in list(zip(dmap, iou)):
logger.log_value("Test Detection1 mAP @ IoU = " + str(item[1]), item[0], epoch)
write_results_to_file(args, dmap, cmap, epoch)
def ts_eval(dataloader, args, logger, rgb_model, flow_model, device):
rgb_vid_preds = []
rgb_frame_preds = []
flow_vid_preds = []
flow_frame_preds = []
vid_lens = []
labels = []
for num, sample in enumerate(dataloader):
if (num + 1) % 100 == 0:
print("Testing test data point %d of %d" % (num + 1, len(dataloader)))
rgb_features = sample["rgb_data"].numpy()
flow_features = sample["flow_data"].numpy()
label = sample["labels"].numpy()
vid_len = sample["vid_len"].numpy()
rgb_features_inp = torch.from_numpy(rgb_features).float().to(device)
flow_features_inp = torch.from_numpy(flow_features).float().to(device)
with torch.no_grad():
_, rgb_video_pred, _, rgb_frame_scr = rgb_model(Variable(rgb_features_inp))
_, flow_video_pred, _, flow_frame_scr = flow_model(
Variable(flow_features_inp)
)
rgb_frame_pred = F.softmax(rgb_frame_scr, -1)
flow_frame_pred = F.softmax(flow_frame_scr, -1)
rgb_frame_pred = np.squeeze(rgb_frame_pred.cpu().data.numpy(), axis=0)
flow_frame_pred = np.squeeze(flow_frame_pred.cpu().data.numpy(), axis=0)
rgb_video_pred = np.squeeze(rgb_video_pred.cpu().data.numpy(), axis=0)
flow_video_pred = np.squeeze(flow_video_pred.cpu().data.numpy(), axis=0)
label = np.squeeze(label, axis=0)
rgb_vid_preds.append(rgb_video_pred)
rgb_frame_preds.append(rgb_frame_pred)
flow_vid_preds.append(flow_video_pred)
flow_frame_preds.append(flow_frame_pred)
vid_lens.append(vid_len)
labels.append(label)
rgb_vid_preds = np.array(rgb_vid_preds)
rgb_frame_preds = np.array(rgb_frame_preds)
flow_vid_preds = np.array(flow_vid_preds)
flow_frame_preds = np.array(flow_frame_preds)
vid_lens = np.array(vid_lens)
labels = np.array(labels)
| dmap, iou = dtmAP( | 0 | 2023-10-20 05:38:16+00:00 | 4k |
SALT-NLP/Efficient_Unlearning | src/models/transformers/parameter-efficient-finetuning/modeling.py | [
{
"identifier": "AdapterConfig",
"path": "src/models/transformers/parameter-efficient-finetuning/configuration.py",
"snippet": "class AdapterConfig(AdapterConfigBase):\n \"\"\"\n Base class that models the architecture of an adapter.\n\n Args:\n mh_adapter (:obj:`bool`): If True, add ada... | import math
import torch
from torch import nn
from transformers.activations import get_activation
from .configuration import AdapterConfig, AdapterFusionConfig
from .context import ForwardContext | 2,948 |
class Activation_Function_Class(nn.Module):
"""
Implementation of various activation function.
"""
def __init__(self, hidden_act):
super().__init__()
if hidden_act.lower() == "leakyrelu":
self.f = nn.functional.leaky_relu
else:
self.f = get_activation(hidden_act.lower())
def forward(self, x):
return self.f(x)
# Single Adapter
class Adapter(nn.Module):
"""
Implementation of a sequential bottleneck adapter block.
"""
def __init__(
self,
adapter_name,
input_size,
down_sample,
|
class Activation_Function_Class(nn.Module):
"""
Implementation of various activation function.
"""
def __init__(self, hidden_act):
super().__init__()
if hidden_act.lower() == "leakyrelu":
self.f = nn.functional.leaky_relu
else:
self.f = get_activation(hidden_act.lower())
def forward(self, x):
return self.f(x)
# Single Adapter
class Adapter(nn.Module):
"""
Implementation of a sequential bottleneck adapter block.
"""
def __init__(
self,
adapter_name,
input_size,
down_sample, | config: AdapterConfig, | 0 | 2023-10-18 18:05:54+00:00 | 4k |
yntha/cstruct | cstruct/_classwrap.py | [
{
"identifier": "collect_metadata",
"path": "cstruct/_metadata.py",
"snippet": "def collect_metadata(class_obj: dataclass) -> StructMetadata:\n metadata = StructMetadata()\n\n for field in dataclasses.fields(class_obj):\n # the parameters passed to the dataclass constructor individually\n ... | import dataclasses
import typing
from dataclasses import dataclass
from ._metadata import collect_metadata
from ._lexer import CStructLexer | 3,155 | # --------------------------------------------------------------------------------------
# Copyright(C) 2023 yntha -
# -
# This program is free software: you can redistribute it and/or modify it under -
# the terms of the GNU General Public License as published by the Free Software -
# Foundation, either version 3 of the License, or (at your option) any later -
# version. -
# -
# This program is distributed in the hope that it will be useful, but WITHOUT ANY -
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -
# PARTICULAR PURPOSE. See the GNU General Public License for more details. -
# -
# You should have received a copy of the GNU General Public License along with -
# this program. If not, see <http://www.gnu.org/licenses/>. -
# --------------------------------------------------------------------------------------
class ClassWrapper:
@classmethod
def wrap(cls, struct_class: type, struct_format: str, byte_order: str) -> type:
return _make_newclass(struct_class, struct_format, byte_order)
# noinspection PyProtectedMember
def _gen_superclass(cls: type) -> type:
superclass_bases = []
annotations = {}
for base in cls.__bases__:
if hasattr(base, "_source_class"):
superclass_bases.append(base._source_class)
annotations.update(base._source_class.__annotations__)
else:
superclass_bases.append(base)
if hasattr(base, "__annotations__"):
annotations.update(base.__annotations__)
annotations.update(cls.__annotations__)
# remove all initvars and classvars from the annotations, if this
# class is a subclass.
if cls.__base__ is not object:
for annotation in annotations.copy():
if isinstance(annotations[annotation], dataclasses.InitVar):
annotations.pop(annotation)
continue
if annotations[annotation] is typing.ClassVar:
annotations.pop(annotation)
# we must remove the old dict because it is improperly copied to
# the new class with `type`. See
# https://jira.mongodb.org/browse/MOTOR-460 for more information.
cls_dict = dict(cls.__dict__)
cls_dict.pop("__dict__", None)
superclass = type(cls.__name__, tuple(superclass_bases), cls_dict)
# copy over the old class annotations
setattr(superclass, "__annotations__", annotations)
# noinspection PyTypeChecker
superclass = dataclass(superclass)
return superclass
class ClassWrapperMeta(type):
# noinspection PyUnresolvedReferences
def __repr__(cls):
return f"<class 'cstruct.classwrapper.{cls._source_class.__name__}'>"
def _make_newclass(src_cls: type, struct_format: str, byte_order: str) -> type:
@dataclass
class newclass(_gen_superclass(src_cls), metaclass=ClassWrapperMeta):
_source_class = src_cls
_lexer = None
primitive_format = struct_format
data_byte_order = byte_order
# noinspection PyArgumentList
def __new__(cls, stream, offset: int = -1):
self = super().__new__(cls)
self.__class__._lexer = CStructLexer(
cls, self.primitive_format, self.data_byte_order, stream, offset
)
cls.__init__(self, None, **self._lexer.parsed_data)
return self
def __getitem__(self, item):
dataclass_values = [i for i in dataclasses.asdict(self).values()]
return dataclass_values[item]
def __repr__(self):
return repr(self.meta)
def __str__(self):
return str(self.meta)
def __post_init__(self, *args, **kwargs):
| # --------------------------------------------------------------------------------------
# Copyright(C) 2023 yntha -
# -
# This program is free software: you can redistribute it and/or modify it under -
# the terms of the GNU General Public License as published by the Free Software -
# Foundation, either version 3 of the License, or (at your option) any later -
# version. -
# -
# This program is distributed in the hope that it will be useful, but WITHOUT ANY -
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -
# PARTICULAR PURPOSE. See the GNU General Public License for more details. -
# -
# You should have received a copy of the GNU General Public License along with -
# this program. If not, see <http://www.gnu.org/licenses/>. -
# --------------------------------------------------------------------------------------
class ClassWrapper:
@classmethod
def wrap(cls, struct_class: type, struct_format: str, byte_order: str) -> type:
return _make_newclass(struct_class, struct_format, byte_order)
# noinspection PyProtectedMember
def _gen_superclass(cls: type) -> type:
superclass_bases = []
annotations = {}
for base in cls.__bases__:
if hasattr(base, "_source_class"):
superclass_bases.append(base._source_class)
annotations.update(base._source_class.__annotations__)
else:
superclass_bases.append(base)
if hasattr(base, "__annotations__"):
annotations.update(base.__annotations__)
annotations.update(cls.__annotations__)
# remove all initvars and classvars from the annotations, if this
# class is a subclass.
if cls.__base__ is not object:
for annotation in annotations.copy():
if isinstance(annotations[annotation], dataclasses.InitVar):
annotations.pop(annotation)
continue
if annotations[annotation] is typing.ClassVar:
annotations.pop(annotation)
# we must remove the old dict because it is improperly copied to
# the new class with `type`. See
# https://jira.mongodb.org/browse/MOTOR-460 for more information.
cls_dict = dict(cls.__dict__)
cls_dict.pop("__dict__", None)
superclass = type(cls.__name__, tuple(superclass_bases), cls_dict)
# copy over the old class annotations
setattr(superclass, "__annotations__", annotations)
# noinspection PyTypeChecker
superclass = dataclass(superclass)
return superclass
class ClassWrapperMeta(type):
# noinspection PyUnresolvedReferences
def __repr__(cls):
return f"<class 'cstruct.classwrapper.{cls._source_class.__name__}'>"
def _make_newclass(src_cls: type, struct_format: str, byte_order: str) -> type:
@dataclass
class newclass(_gen_superclass(src_cls), metaclass=ClassWrapperMeta):
_source_class = src_cls
_lexer = None
primitive_format = struct_format
data_byte_order = byte_order
# noinspection PyArgumentList
def __new__(cls, stream, offset: int = -1):
self = super().__new__(cls)
self.__class__._lexer = CStructLexer(
cls, self.primitive_format, self.data_byte_order, stream, offset
)
cls.__init__(self, None, **self._lexer.parsed_data)
return self
def __getitem__(self, item):
dataclass_values = [i for i in dataclasses.asdict(self).values()]
return dataclass_values[item]
def __repr__(self):
return repr(self.meta)
def __str__(self):
return str(self.meta)
def __post_init__(self, *args, **kwargs): | self.meta = collect_metadata(self) | 0 | 2023-10-22 18:33:32+00:00 | 4k |
sehyun03/MulActSeg | trainer/active_joint_multi_lossdecomp.py | [
{
"identifier": "active_joint_multi",
"path": "trainer/active_joint_multi.py",
"snippet": "class ActiveTrainer(active.ActiveTrainer):\n def __init__(self, args, logger, selection_iter):\n def get_criterion(self):\n def zero_if_nan(self, loss):\n def check_loss_sanity(self, loss):\n def up... | import torch
import numpy as np
import torch.nn.functional as F
from torch import nn
from tqdm import tqdm
from torch_scatter import scatter
from trainer import active_joint_multi
from trainer.active_joint_multi_predignore_mclossablation2 import GroupMultiLabelCE_onlymulti
from utils.loss import MultiChoiceCE | 2,380 |
r"""
Decomposition of previous multi-positive loss & group-multi loss
- One-hot spxs: CE loss
- Multi-hot spxs: Multi-positive, Group Multi
- without predignore
"""
class OnehotCEMultihotChoice(MultiChoiceCE):
def __init__(self, num_class, temperature=1.0, reduction='mean'):
super().__init__(num_class, temperature, reduction)
assert(self.reduction == 'mean')
def forward(self, inputs, targets, superpixels, spmasks):
''' inputs: N x C x H x W
targets: N x self.num_superpiexl x C+1
superpixels: N x H x W
spmasks: N x H x W
'''
N, C, H, W = inputs.shape
inputs = inputs.permute(0,2,3,1).reshape(N, -1, C) ### N x HW x C
outputs = F.softmax(inputs / self.temp, dim=2) ### N x HW x C
superpixels = superpixels.reshape(N, -1, 1) ### N x HW x 1
spmasks = spmasks.reshape(N, -1) ### N x HW: binary mask indicating current selected spxs
oh_loss = 0
oh_num_valid = 1
mh_loss = 0
mh_num_valid = 1
for i in range(N):
'''
outputs[i] ### HW x C
superpixels[i] ### HW x 1
spmasks[i] ### HW x 1
'''
r''' skip this image if valid superpixel is not included '''
valid_mask = spmasks[i] ### HW
if not torch.any(valid_mask): continue ### empty image
r''' calculate pixel-wise (CE, MC) loss jointly'''
valid_output = outputs[i][valid_mask] ### HW' x C : class-wise prediction 중 valid 한 영역
valid_superpixel = superpixels[i][valid_mask] ### HW' x 1 : superpixel id 중 valid 한 ID
trg_sup = targets[i] ### self.num_superpixel x C: multi-hot annotation
trg_pixel = trg_sup[valid_superpixel.squeeze(dim=1)] ### HW' x C : pixel-wise multi-hot annotation
pos_pred = (valid_output * trg_pixel).sum(dim=1)
r''' ce loss on one-hot spx '''
onehot_trg = (1 == trg_pixel.sum(dim=1))
if torch.any(onehot_trg):
oh_pos_pred = pos_pred[onehot_trg]
oh_loss += -torch.log(oh_pos_pred + self.eps).sum()
oh_num_valid += oh_pos_pred.shape[0]
r''' mc loss on multi-hot spx '''
# multihot_trg = torch.logical_not(onehot_trg)
multihot_trg = (1 < trg_pixel.sum(dim=1))
if torch.any(multihot_trg):
# assert(torch.all(multihot_trg == (1 < trg_pixel.sum(dim=1))))
mh_pos_pred = pos_pred[multihot_trg]
mh_loss += -torch.log(mh_pos_pred + self.eps).sum()
mh_num_valid += mh_pos_pred.shape[0]
return oh_loss / oh_num_valid, mh_loss / mh_num_valid
|
r"""
Decomposition of previous multi-positive loss & group-multi loss
- One-hot spxs: CE loss
- Multi-hot spxs: Multi-positive, Group Multi
- without predignore
"""
class OnehotCEMultihotChoice(MultiChoiceCE):
def __init__(self, num_class, temperature=1.0, reduction='mean'):
super().__init__(num_class, temperature, reduction)
assert(self.reduction == 'mean')
def forward(self, inputs, targets, superpixels, spmasks):
''' inputs: N x C x H x W
targets: N x self.num_superpiexl x C+1
superpixels: N x H x W
spmasks: N x H x W
'''
N, C, H, W = inputs.shape
inputs = inputs.permute(0,2,3,1).reshape(N, -1, C) ### N x HW x C
outputs = F.softmax(inputs / self.temp, dim=2) ### N x HW x C
superpixels = superpixels.reshape(N, -1, 1) ### N x HW x 1
spmasks = spmasks.reshape(N, -1) ### N x HW: binary mask indicating current selected spxs
oh_loss = 0
oh_num_valid = 1
mh_loss = 0
mh_num_valid = 1
for i in range(N):
'''
outputs[i] ### HW x C
superpixels[i] ### HW x 1
spmasks[i] ### HW x 1
'''
r''' skip this image if valid superpixel is not included '''
valid_mask = spmasks[i] ### HW
if not torch.any(valid_mask): continue ### empty image
r''' calculate pixel-wise (CE, MC) loss jointly'''
valid_output = outputs[i][valid_mask] ### HW' x C : class-wise prediction 중 valid 한 영역
valid_superpixel = superpixels[i][valid_mask] ### HW' x 1 : superpixel id 중 valid 한 ID
trg_sup = targets[i] ### self.num_superpixel x C: multi-hot annotation
trg_pixel = trg_sup[valid_superpixel.squeeze(dim=1)] ### HW' x C : pixel-wise multi-hot annotation
pos_pred = (valid_output * trg_pixel).sum(dim=1)
r''' ce loss on one-hot spx '''
onehot_trg = (1 == trg_pixel.sum(dim=1))
if torch.any(onehot_trg):
oh_pos_pred = pos_pred[onehot_trg]
oh_loss += -torch.log(oh_pos_pred + self.eps).sum()
oh_num_valid += oh_pos_pred.shape[0]
r''' mc loss on multi-hot spx '''
# multihot_trg = torch.logical_not(onehot_trg)
multihot_trg = (1 < trg_pixel.sum(dim=1))
if torch.any(multihot_trg):
# assert(torch.all(multihot_trg == (1 < trg_pixel.sum(dim=1))))
mh_pos_pred = pos_pred[multihot_trg]
mh_loss += -torch.log(mh_pos_pred + self.eps).sum()
mh_num_valid += mh_pos_pred.shape[0]
return oh_loss / oh_num_valid, mh_loss / mh_num_valid
| class ActiveTrainer(active_joint_multi.ActiveTrainer): | 0 | 2023-10-24 09:19:58+00:00 | 4k |
hms-dbmi/CHIEF | train.py | [
{
"identifier": "read_yaml",
"path": "utils/utils.py",
"snippet": "def read_yaml(fpath=\"./configs/sample.yaml\"):\n with open(fpath, mode=\"r\") as file:\n yml = yaml.load(file, Loader=yaml.Loader)\n return Dict(yml)"
},
{
"identifier": "seed_torch",
"path": "utils/utils.py... | import argparse
import os
import shutil
import torch
from utils.utils import read_yaml, seed_torch
from utils.trainer import Trainer | 2,304 |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--config_path', type=str)
parser.add_argument('--begin', type=int, default=0)
parser.add_argument('--end', type=int, default=10)
return parser.parse_args()
if __name__ == '__main__':
args = get_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--config_path', type=str)
parser.add_argument('--begin', type=int, default=0)
parser.add_argument('--end', type=int, default=10)
return parser.parse_args()
if __name__ == '__main__':
args = get_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | cfg = read_yaml(args.config_path) | 0 | 2023-10-17 21:19:25+00:00 | 4k |
justincui03/tesla | buffer.py | [
{
"identifier": "get_dataset",
"path": "utils.py",
"snippet": "def get_dataset(dataset, data_path, batch_size=1, args=None):\n\n class_map = None\n loader_train_dict = None\n class_map_inv = None\n\n if dataset == 'CIFAR10':\n channel = 3\n im_size = (32, 32)\n num_class... | import os
import argparse
import torch
import torch.nn as nn
import copy
import warnings
from tqdm import tqdm
from utils import get_dataset, get_network, get_daparam,\
TensorDataset, epoch, ParamDiffAug
from PIL import PngImagePlugin | 3,186 |
LARGE_ENOUGH_NUMBER = 100
PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2)
warnings.filterwarnings("ignore", category=DeprecationWarning)
def main(args):
args.dsa = True if args.dsa == 'True' else False
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
args.dsa_param = ParamDiffAug()
|
LARGE_ENOUGH_NUMBER = 100
PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2)
warnings.filterwarnings("ignore", category=DeprecationWarning)
def main(args):
args.dsa = True if args.dsa == 'True' else False
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
args.dsa_param = ParamDiffAug()
| channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader, loader_train_dict, class_map, class_map_inv = get_dataset(args.dataset, args.data_path, args.batch_real, args=args) | 0 | 2023-10-17 23:11:36+00:00 | 4k |
upiterbarg/hihack | models/hierarchical_transformer_lstm.py | [
{
"identifier": "generate_square_subsequent_mask",
"path": "models/transformer_lstm.py",
"snippet": "def generate_square_subsequent_mask(sz: int, device: str = \"cpu\") -> torch.Tensor:\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = (\n mask.float()\n .masked... | import json
import numpy as np
import os
import pathlib
import pdb
import torch
import sys
from nle import nethack
from nle.nethack.actions import ACTIONS as A
from torch import nn
from torch.nn import functional as F
from .transformer_lstm import (
generate_square_subsequent_mask,
PositionalEncoding
)
from chaotic_dwarf import (
TopLineEncoder,
BottomLinesEncoder,
ScreenEncoder,
conv_outdim
) | 2,541 | self.inference_unroll_length = flags.unroll_length if not 'inference_unroll_length' in flags else flags.inference_unroll_length
self.wrapped = False
def initial_state(self, batch_size=1):
return (
torch.zeros(1, batch_size, self.inference_unroll_length, self.inference_unroll_length), # transformer portion 0
torch.rand(self.inference_unroll_length, batch_size, self.hidden_dim), # transformer portion 1
torch.zeros(self.core.num_layers, batch_size, self.core.hidden_size), # lstm portion 0
torch.zeros(self.core.num_layers, batch_size, self.core.hidden_size) # lstm portion 1
)
def get_encodings(self, inputs, for_lstm=False):
T, B, C, H, W = inputs["screen_image"].shape
topline = inputs["tty_chars"][..., 0, :]
bottom_line = inputs["tty_chars"][..., -2:, :]
if for_lstm or not hasattr(self, 'topline_encoder2'):
st = [
self.topline_encoder(
topline.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.bottomline_encoder(
bottom_line.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.screen_encoder(
inputs["screen_image"]
.float(memory_format=torch.contiguous_format)
.view(T * B, C, H, W)
),
]
else:
st = [
self.topline_encoder2(
topline.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.bottomline_encoder2(
bottom_line.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.screen_encoder2(
inputs["screen_image"]
.float(memory_format=torch.contiguous_format)
.view(T * B, C, H, W)
),
]
if self.use_prev_action:
st.append(torch.nn.functional.one_hot(inputs["prev_action"], self.prev_actions_dim).view(T * B, -1))
st = torch.cat(st, dim=1)
return st
def forward(self, inputs, core_state=None, last_ttyrec_data=None, return_strategywise_logits=False):
T, B, C, H, W = inputs["screen_image"].shape
st_lstm = self.get_encodings(inputs, for_lstm=True)
st_trnsfrmr = self.get_encodings(inputs, for_lstm=False)
T_eff = T
if not last_ttyrec_data is None and self.training:
last_st_lstm = self.get_encodings(last_ttyrec_data, for_lstm=True)
last_st_trnsfrmr = self.get_encodings(last_ttyrec_data, for_lstm=False)
T_eff = T * 2
st_lstm = torch.cat([last_st_lstm.reshape(T, B, -1), st_lstm.reshape(T, B, -1)], axis=0).reshape(T_eff * B, -1)
st_trnsfrmr = torch.cat([last_st_trnsfrmr.reshape(T, B, -1), st_trnsfrmr.reshape(T, B, -1)], axis=0).reshape(T_eff * B, -1)
self.wrapped = True
c0, c1, c2, c3 = core_state
trnsfrmr_core_state = c0, c1
lstm_core_state = c2, c3
lstm_core_input = st_lstm.view(T_eff, B, -1)
lstm_core_output_list = []
if self.wrapped:
notdone = torch.cat([(~last_ttyrec_data["done"]).float(), (~inputs["done"]).float()], axis=0)
else:
notdone = (~inputs["done"]).float()
for input, nd in zip(lstm_core_input.unbind(), notdone.unbind()):
# Reset core state to zero whenever an episode ended.
# Make `done` broadcastable with (num_layers, B, hidden_size)
nd = nd.view(1, -1, 1)
lstm_core_state = tuple(nd * t for t in lstm_core_state)
output, lstm_core_state = self.core(input.unsqueeze(0), lstm_core_state)
lstm_core_output_list.append(output)
lstm_core_output = torch.flatten(torch.cat(lstm_core_output_list), 0, 1)
st = torch.cat([st_trnsfrmr, lstm_core_output], dim=1)
trnsfrmr_core_input = st.reshape(T_eff, B, -1)
if not self.training:
prev_mask, prev_encodings = trnsfrmr_core_state
prev_mask = prev_mask.squeeze(0)
trnsfrmr_core_input = torch.cat([prev_encodings[1:], trnsfrmr_core_input], axis=0)
trnsfrmr_core_mask = torch.stack(
[torch.cat([torch.cat([prev_mask[i, 1:, 1:], prev_mask[i, -1, 1:].unsqueeze(0)], axis=0) * notdone[-1, i], torch.zeros((self.inference_unroll_length, 1)).to(trnsfrmr_core_input.device)], axis=1) for i in range(B)]
)
trnsfrmr_core_mask[:, -1, -1] = 1
trnsfrmr_core_state = (trnsfrmr_core_mask.detach().clone().unsqueeze(0),
trnsfrmr_core_input.detach().clone()
)
for i in range(B):
trnsfrmr_core_mask[i].fill_diagonal_(1)
trnsfrmr_core_mask = (trnsfrmr_core_mask.float().masked_fill(trnsfrmr_core_mask == 0, float("-inf")).masked_fill(trnsfrmr_core_mask == 1, float(0.0))).to(device=trnsfrmr_core_input.device)
trnsfrmr_core_mask = torch.repeat_interleave(trnsfrmr_core_mask, self.num_attention_heads, dim=1).reshape(B * self.num_attention_heads, self.inference_unroll_length, self.inference_unroll_length)
T = trnsfrmr_core_input.shape[0]
elif self.wrapped:
mask1 = (torch.triu(torch.ones(T_eff, T_eff)) == 1).transpose(0, 1)
mask2 = F.pad((torch.triu(torch.ones(T, T)) == 1).transpose(0, 1), (0, T, T, 0))
trnsfrmr_core_mask = mask1.long() + mask2.long()
trnsfrmr_core_mask[trnsfrmr_core_mask != 1] = 0
trnsfrmr_core_mask = (trnsfrmr_core_mask.float().masked_fill(trnsfrmr_core_mask == 0, float("-inf")).masked_fill(trnsfrmr_core_mask == 1, float(0.0))).to(device=trnsfrmr_core_input.device)
else:
|
base_path = pathlib.Path().resolve()
sys.path.insert(0, os.path.join(base_path, '..', 'dungeonsdata-neurips2022/experiment_code/hackrl/models'))
class HierarchicalTransformerLSTM(nn.Module):
def __init__(self, shape, action_space, flags, device, num_strategies=20):
super(HierarchicalTransformerLSTM, self).__init__()
self.flags = flags
self.num_actions = len(action_space)
self.use_prev_action = flags.use_prev_action
self.topline_encoder = TopLineEncoder()
self.bottomline_encoder = torch.jit.script(BottomLinesEncoder())
pixel_size = flags.pixel_size
if flags.crop_dim == 0:
screen_shape = (24 * pixel_size, 80 * pixel_size)
else:
screen_shape = (flags.crop_dim * pixel_size, flags.crop_dim * pixel_size)
self.screen_encoder = torch.jit.script(ScreenEncoder(screen_shape))
## second copy of encoders
self.topline_encoder2 = TopLineEncoder()
self.bottomline_encoder2 = torch.jit.script(BottomLinesEncoder())
self.screen_encoder2 = torch.jit.script(ScreenEncoder(screen_shape))
###
self.prev_actions_dim = 128 if self.use_prev_action else 0
self.h_dim = sum(
[
self.topline_encoder.hidden_dim,
self.bottomline_encoder.hidden_dim,
self.screen_encoder.hidden_dim,
self.prev_actions_dim
]
)
self.hidden_dim = 512
self.policy_hidden_dim = 256
self.strategy_dim = num_strategies
self.core = nn.LSTM(self.h_dim, self.hidden_dim, num_layers=1)
self.num_attention_heads = flags.num_attention_heads
self.num_transformer_encoder_layers = flags.num_transformer_layers
self.hidden_dim = self.h_dim + self.hidden_dim
core_trnsfrmr_layer = nn.TransformerEncoderLayer(d_model=self.hidden_dim, nhead=self.num_attention_heads, norm_first=True, activation='gelu')
self.core_trnsfrmr = nn.TransformerEncoder(core_trnsfrmr_layer, num_layers=self.num_transformer_encoder_layers)
self.positional_encoder = PositionalEncoding(self.hidden_dim)
self.strategy_encoder = nn.Linear(self.hidden_dim, self.strategy_dim)
self.policies = nn.ModuleDict(
[[f'{i}', nn.Sequential(nn.Linear(self.hidden_dim, self.policy_hidden_dim),
nn.ELU(),
nn.Linear(self.policy_hidden_dim, self.num_actions))] for i in range(self.strategy_dim)]
)
self.baseline = nn.Linear(self.hidden_dim, 1)
self.version = 0
self.inference_unroll_length = flags.unroll_length if not 'inference_unroll_length' in flags else flags.inference_unroll_length
self.wrapped = False
def initial_state(self, batch_size=1):
return (
torch.zeros(1, batch_size, self.inference_unroll_length, self.inference_unroll_length), # transformer portion 0
torch.rand(self.inference_unroll_length, batch_size, self.hidden_dim), # transformer portion 1
torch.zeros(self.core.num_layers, batch_size, self.core.hidden_size), # lstm portion 0
torch.zeros(self.core.num_layers, batch_size, self.core.hidden_size) # lstm portion 1
)
def get_encodings(self, inputs, for_lstm=False):
T, B, C, H, W = inputs["screen_image"].shape
topline = inputs["tty_chars"][..., 0, :]
bottom_line = inputs["tty_chars"][..., -2:, :]
if for_lstm or not hasattr(self, 'topline_encoder2'):
st = [
self.topline_encoder(
topline.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.bottomline_encoder(
bottom_line.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.screen_encoder(
inputs["screen_image"]
.float(memory_format=torch.contiguous_format)
.view(T * B, C, H, W)
),
]
else:
st = [
self.topline_encoder2(
topline.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.bottomline_encoder2(
bottom_line.float(memory_format=torch.contiguous_format).view(T * B, -1)
),
self.screen_encoder2(
inputs["screen_image"]
.float(memory_format=torch.contiguous_format)
.view(T * B, C, H, W)
),
]
if self.use_prev_action:
st.append(torch.nn.functional.one_hot(inputs["prev_action"], self.prev_actions_dim).view(T * B, -1))
st = torch.cat(st, dim=1)
return st
def forward(self, inputs, core_state=None, last_ttyrec_data=None, return_strategywise_logits=False):
T, B, C, H, W = inputs["screen_image"].shape
st_lstm = self.get_encodings(inputs, for_lstm=True)
st_trnsfrmr = self.get_encodings(inputs, for_lstm=False)
T_eff = T
if not last_ttyrec_data is None and self.training:
last_st_lstm = self.get_encodings(last_ttyrec_data, for_lstm=True)
last_st_trnsfrmr = self.get_encodings(last_ttyrec_data, for_lstm=False)
T_eff = T * 2
st_lstm = torch.cat([last_st_lstm.reshape(T, B, -1), st_lstm.reshape(T, B, -1)], axis=0).reshape(T_eff * B, -1)
st_trnsfrmr = torch.cat([last_st_trnsfrmr.reshape(T, B, -1), st_trnsfrmr.reshape(T, B, -1)], axis=0).reshape(T_eff * B, -1)
self.wrapped = True
c0, c1, c2, c3 = core_state
trnsfrmr_core_state = c0, c1
lstm_core_state = c2, c3
lstm_core_input = st_lstm.view(T_eff, B, -1)
lstm_core_output_list = []
if self.wrapped:
notdone = torch.cat([(~last_ttyrec_data["done"]).float(), (~inputs["done"]).float()], axis=0)
else:
notdone = (~inputs["done"]).float()
for input, nd in zip(lstm_core_input.unbind(), notdone.unbind()):
# Reset core state to zero whenever an episode ended.
# Make `done` broadcastable with (num_layers, B, hidden_size)
nd = nd.view(1, -1, 1)
lstm_core_state = tuple(nd * t for t in lstm_core_state)
output, lstm_core_state = self.core(input.unsqueeze(0), lstm_core_state)
lstm_core_output_list.append(output)
lstm_core_output = torch.flatten(torch.cat(lstm_core_output_list), 0, 1)
st = torch.cat([st_trnsfrmr, lstm_core_output], dim=1)
trnsfrmr_core_input = st.reshape(T_eff, B, -1)
if not self.training:
prev_mask, prev_encodings = trnsfrmr_core_state
prev_mask = prev_mask.squeeze(0)
trnsfrmr_core_input = torch.cat([prev_encodings[1:], trnsfrmr_core_input], axis=0)
trnsfrmr_core_mask = torch.stack(
[torch.cat([torch.cat([prev_mask[i, 1:, 1:], prev_mask[i, -1, 1:].unsqueeze(0)], axis=0) * notdone[-1, i], torch.zeros((self.inference_unroll_length, 1)).to(trnsfrmr_core_input.device)], axis=1) for i in range(B)]
)
trnsfrmr_core_mask[:, -1, -1] = 1
trnsfrmr_core_state = (trnsfrmr_core_mask.detach().clone().unsqueeze(0),
trnsfrmr_core_input.detach().clone()
)
for i in range(B):
trnsfrmr_core_mask[i].fill_diagonal_(1)
trnsfrmr_core_mask = (trnsfrmr_core_mask.float().masked_fill(trnsfrmr_core_mask == 0, float("-inf")).masked_fill(trnsfrmr_core_mask == 1, float(0.0))).to(device=trnsfrmr_core_input.device)
trnsfrmr_core_mask = torch.repeat_interleave(trnsfrmr_core_mask, self.num_attention_heads, dim=1).reshape(B * self.num_attention_heads, self.inference_unroll_length, self.inference_unroll_length)
T = trnsfrmr_core_input.shape[0]
elif self.wrapped:
mask1 = (torch.triu(torch.ones(T_eff, T_eff)) == 1).transpose(0, 1)
mask2 = F.pad((torch.triu(torch.ones(T, T)) == 1).transpose(0, 1), (0, T, T, 0))
trnsfrmr_core_mask = mask1.long() + mask2.long()
trnsfrmr_core_mask[trnsfrmr_core_mask != 1] = 0
trnsfrmr_core_mask = (trnsfrmr_core_mask.float().masked_fill(trnsfrmr_core_mask == 0, float("-inf")).masked_fill(trnsfrmr_core_mask == 1, float(0.0))).to(device=trnsfrmr_core_input.device)
else: | trnsfrmr_core_mask = generate_square_subsequent_mask(T, trnsfrmr_core_input.device) | 0 | 2023-10-23 15:44:32+00:00 | 4k |
nmathey/finasync | finasync/realt.py | [
{
"identifier": "GNOSIS_API_TOKENLIST_URI",
"path": "finasync/constants.py",
"snippet": "GNOSIS_API_TOKENLIST_URI = (\n \"https://blockscout.com/xdai/mainnet/api?module=account&action=tokenlist&address=\"\n)"
},
{
"identifier": "REALT_API_TOKENLIST_URI",
"path": "finasync/constants.py",
... | import requests
import re
import json
import time
import os
import logging
from pathlib import Path
from datetime import datetime, timedelta
from json.decoder import JSONDecodeError
from finary_uapi.user_real_estates import (
get_user_real_estates,
delete_user_real_estates,
update_user_real_estates,
add_user_real_estates,
add_user_real_estates_with_currency,
)
from finary_uapi.user_me import get_display_currency_code
from .constants import (
GNOSIS_API_TOKENLIST_URI,
REALT_API_TOKENLIST_URI,
REALT_OFFLINE_TOKENS_LIST,
)
from .utils import convert_currency | 2,393 | logging.debug("My RealT Finary portfolio")
logging.debug(myFinary_real_estates)
myFinary_realT = {}
for item in myFinary_real_estates:
contractAddress = re.findall(r"0x.+", str(item.get("description")))
name = re.findall(r"- (.*) -", str(item.get("description")))
myFinary_realT.update(
{
contractAddress[0].lower(): {
"name": name[0],
"contractAddress": contractAddress[0].lower(),
"finary_id": item.get("id"),
"category": item.get("category"),
"description": item.get("description"),
"buying_price": item.get("buying_price"),
"ownership_percentage": item.get("ownership_percentage"),
}
}
)
return json.dumps(myFinary_realT)
def get_realt_rentals_blockchain(wallet_address):
myWallet = json.loads(requests.get(GNOSIS_API_TOKENLIST_URI + wallet_address).text)
myRealT_rentals = {}
logging.debug("My wallet details")
logging.debug(myWallet)
for item in myWallet["result"]:
if re.match(r"^REALTOKEN", str(item.get("symbol")), re.IGNORECASE):
logging.debug("Updating RealT Token to Finary: " + item["symbol"])
myRealT_rentals.update(
{
item["contractAddress"].lower(): {
"name": item["symbol"],
"balance": float(item["balance"])
/ pow(10, int(item["decimals"])),
"contractAddress": item["contractAddress"].lower(),
}
}
)
elif re.match(r"^armmREALT", str(item.get("symbol"))):
time.sleep(0.2)
original_contract_address = requests.get(
GNOSIS_API_TOKENLIST_URI + item["contractAddress"]
).json()
original_contract_address = list(
filter(
lambda x: re.match("^REALTOKEN", x["symbol"]),
original_contract_address["result"],
)
)
original_contract_address = str(
original_contract_address[0]["contractAddress"]
)
logging.debug("Updating armm RealT Token to Finary: " + item["symbol"])
myRealT_rentals.update(
{
original_contract_address.lower(): {
"name": item["symbol"],
"balance": float(item["balance"])
/ pow(10, int(item["decimals"])),
"contractAddress": original_contract_address.lower(),
}
}
)
logging.debug("My RealT portfolio from the blockchain")
logging.debug(myRealT_rentals)
return json.dumps(myRealT_rentals)
def get_building_type(realT_propertyType):
# building type: house, building, apartment, land, commercial, parking_box, or other
# propertyType from RealT -> 1 = Single Family | 2 = Multi Family | 3 = Duplex | 4 = Condominium | 6 = Mixed-Used | 8 = Quadplex | 9 = Commercial |10 = SFR Portfolio
building_type = "other"
if realT_propertyType == 1:
building_type = "house"
elif realT_propertyType == 2 or realT_propertyType == 3 or realT_propertyType == 8:
building_type = "building"
elif realT_propertyType == 4 or realT_propertyType == 9:
building_type = "commercial"
return building_type
def sync_realt_rent(session: requests.Session, wallet_address):
# Get current Finary RealT rent portfolio
myFinary_realT = json.loads(get_realt_rentals_finary(session))
# Get current RealT rent from wallet
myRealT_rentals = json.loads(get_realt_rentals_blockchain(wallet_address))
# If finary RealT rentals not in RealT wallet then delete otherwise update
for key in myFinary_realT:
if key not in myRealT_rentals:
delete_user_real_estates(session, myFinary_realT[key]["finary_id"])
logging.info("Deleting " + myFinary_realT[key]["description"])
else:
token_details = get_realt_token_details(key)
# Handling currency
if token_details["currency"] == get_display_currency_code(session):
user_estimated_value = (
token_details["totalTokens"] * token_details["tokenPrice"]
)
monthly_rent = token_details["netRentMonth"]
elif (
token_details["currency"] == "EUR"
or "USD"
or "SGD"
or "CHF"
or "GBP"
or "CAD"
):
user_estimated_value = (
token_details["totalTokens"] * token_details["tokenPrice"]
)
monthly_rent = token_details["netRentMonth"]
else:
|
def get_realt_token_details(realt_token_contractAdress):
Now_Time = datetime.today()
RealT_OfflineTokensList_Path = Path(REALT_OFFLINE_TOKENS_LIST)
RealT_OfflineTokensList_Path.touch(exist_ok=True)
with open(RealT_OfflineTokensList_Path) as json_file:
try:
RealT_OfflineTokensList = json.load(json_file)
except JSONDecodeError:
RealT_OfflineTokensList = {
"info": {
"last_sync": str(datetime.timestamp(Now_Time - timedelta(weeks=2)))
},
"data": {},
}
# Update offlineTokensList from RealT API only if more than 1 week old
if float(RealT_OfflineTokensList["info"]["last_sync"]) < datetime.timestamp(
Now_Time - timedelta(weeks=1)
):
MyRealT_API_Header = {
"Accept": "*/*",
"X-AUTH-REALT-TOKEN": os.environ["MYREALT_API_KEY"],
}
TokensListReq = requests.get(
REALT_API_TOKENLIST_URI, headers=MyRealT_API_Header
)
TokensList = TokensListReq.json()
logging.debug("Tokens list details from API RealT")
logging.debug(TokensList)
for item in TokensList:
RealT_OfflineTokensList["data"].update(
{
item.get("uuid").lower(): {
"fullName": item.get("fullName"),
"shortName": item.get("shortName"),
"tokenPrice": item.get("tokenPrice"),
"currency": item.get("currency"),
"rentStartDate": item.get("rentStartDate"),
"squareFeet": item.get("squareFeet"),
"totalTokens": item.get("totalTokens"),
"totalInvestment": item.get("totalInvestment"),
"grossRentMonth": item.get("grossRentMont"),
"propertyManagement": item.get("propertyManagement"),
"realtPlatform": item.get("realtPlaform"),
"insurance": item.get("insurance"),
"propertyTaxes": item.get("propertyTaxes"),
"propertyMaintenanceMonthly": item.get(
"propertyMaintenanceMonthly"
),
"utilities": item.get("utilities"),
"netRentMonth": item.get("netRentMonth"),
"netRentMonthPerToken": item.get("netRentMonthPerToken"),
"coordinate": item.get("coordinate"),
"propertyType": item.get("propertyType"),
"rentalType": item.get("rentalType"),
"productType": item.get("productType"),
}
}
)
RealT_OfflineTokensList["info"]["last_sync"] = str(datetime.timestamp(Now_Time))
with open(RealT_OfflineTokensList_Path, "w") as outfile:
json.dump(RealT_OfflineTokensList, outfile, indent=4)
return RealT_OfflineTokensList["data"][realt_token_contractAdress]
def get_realt_rentals_finary(session: requests.Session):
myFinary_real_estates = get_user_real_estates(session)
myFinary_real_estates = list(
filter(
lambda x: re.match("^RealT -", x["description"]),
myFinary_real_estates["result"],
)
)
logging.debug("My RealT Finary portfolio")
logging.debug(myFinary_real_estates)
myFinary_realT = {}
for item in myFinary_real_estates:
contractAddress = re.findall(r"0x.+", str(item.get("description")))
name = re.findall(r"- (.*) -", str(item.get("description")))
myFinary_realT.update(
{
contractAddress[0].lower(): {
"name": name[0],
"contractAddress": contractAddress[0].lower(),
"finary_id": item.get("id"),
"category": item.get("category"),
"description": item.get("description"),
"buying_price": item.get("buying_price"),
"ownership_percentage": item.get("ownership_percentage"),
}
}
)
return json.dumps(myFinary_realT)
def get_realt_rentals_blockchain(wallet_address):
myWallet = json.loads(requests.get(GNOSIS_API_TOKENLIST_URI + wallet_address).text)
myRealT_rentals = {}
logging.debug("My wallet details")
logging.debug(myWallet)
for item in myWallet["result"]:
if re.match(r"^REALTOKEN", str(item.get("symbol")), re.IGNORECASE):
logging.debug("Updating RealT Token to Finary: " + item["symbol"])
myRealT_rentals.update(
{
item["contractAddress"].lower(): {
"name": item["symbol"],
"balance": float(item["balance"])
/ pow(10, int(item["decimals"])),
"contractAddress": item["contractAddress"].lower(),
}
}
)
elif re.match(r"^armmREALT", str(item.get("symbol"))):
time.sleep(0.2)
original_contract_address = requests.get(
GNOSIS_API_TOKENLIST_URI + item["contractAddress"]
).json()
original_contract_address = list(
filter(
lambda x: re.match("^REALTOKEN", x["symbol"]),
original_contract_address["result"],
)
)
original_contract_address = str(
original_contract_address[0]["contractAddress"]
)
logging.debug("Updating armm RealT Token to Finary: " + item["symbol"])
myRealT_rentals.update(
{
original_contract_address.lower(): {
"name": item["symbol"],
"balance": float(item["balance"])
/ pow(10, int(item["decimals"])),
"contractAddress": original_contract_address.lower(),
}
}
)
logging.debug("My RealT portfolio from the blockchain")
logging.debug(myRealT_rentals)
return json.dumps(myRealT_rentals)
def get_building_type(realT_propertyType):
# building type: house, building, apartment, land, commercial, parking_box, or other
# propertyType from RealT -> 1 = Single Family | 2 = Multi Family | 3 = Duplex | 4 = Condominium | 6 = Mixed-Used | 8 = Quadplex | 9 = Commercial |10 = SFR Portfolio
building_type = "other"
if realT_propertyType == 1:
building_type = "house"
elif realT_propertyType == 2 or realT_propertyType == 3 or realT_propertyType == 8:
building_type = "building"
elif realT_propertyType == 4 or realT_propertyType == 9:
building_type = "commercial"
return building_type
def sync_realt_rent(session: requests.Session, wallet_address):
# Get current Finary RealT rent portfolio
myFinary_realT = json.loads(get_realt_rentals_finary(session))
# Get current RealT rent from wallet
myRealT_rentals = json.loads(get_realt_rentals_blockchain(wallet_address))
# If finary RealT rentals not in RealT wallet then delete otherwise update
for key in myFinary_realT:
if key not in myRealT_rentals:
delete_user_real_estates(session, myFinary_realT[key]["finary_id"])
logging.info("Deleting " + myFinary_realT[key]["description"])
else:
token_details = get_realt_token_details(key)
# Handling currency
if token_details["currency"] == get_display_currency_code(session):
user_estimated_value = (
token_details["totalTokens"] * token_details["tokenPrice"]
)
monthly_rent = token_details["netRentMonth"]
elif (
token_details["currency"] == "EUR"
or "USD"
or "SGD"
or "CHF"
or "GBP"
or "CAD"
):
user_estimated_value = (
token_details["totalTokens"] * token_details["tokenPrice"]
)
monthly_rent = token_details["netRentMonth"]
else: | user_estimated_value = token_details["totalTokens"] * convert_currency( | 3 | 2023-10-24 00:32:05+00:00 | 4k |
vitaliisili/petoshield-rest | petoshield_api/apps/policy/filters.py | [
{
"identifier": "ServiceProvider",
"path": "petoshield_api/apps/policy/models.py",
"snippet": "class ServiceProvider(ExportModelOperationsMixin('service_provider'), BaseModel):\n \"\"\"Model representing a service provider.\n Attributes:\n company_name (CharField): The name of the company. ... | from django_filters import rest_framework as filters
from .models import ServiceProvider, Policy, InsuranceCase, IncomingInvoice | 1,723 |
class ServiceProviderFilter(filters.FilterSet):
"""A filter class for the ServiceProvider model.
Attributes:
user (CharFilter): Filter for the 'user__name' field using the 'icontains' lookup.
created_at__year__exact (NumberFilter): Filter for the 'created_at__year' field with exact matching.
created_at__year__gt (NumberFilter): Filter for the 'created_at__year' field with greater than matching.
created_at__year__lt (NumberFilter): Filter for the 'created_at__year' field with less than matching.
Meta:
model (ServiceProvider): The model to be filtered.
fields (dict): The fields and lookup types to be used for filtering.
"""
user = filters.CharFilter(field_name='user__name', lookup_expr='icontains')
created_at__year__exact = filters.NumberFilter(field_name='created_at__year', lookup_expr='exact')
created_at__year__gt = filters.NumberFilter(field_name='created_at__year', lookup_expr='gt')
created_at__year__lt = filters.NumberFilter(field_name='created_at__year', lookup_expr='lt')
class Meta:
|
class ServiceProviderFilter(filters.FilterSet):
"""A filter class for the ServiceProvider model.
Attributes:
user (CharFilter): Filter for the 'user__name' field using the 'icontains' lookup.
created_at__year__exact (NumberFilter): Filter for the 'created_at__year' field with exact matching.
created_at__year__gt (NumberFilter): Filter for the 'created_at__year' field with greater than matching.
created_at__year__lt (NumberFilter): Filter for the 'created_at__year' field with less than matching.
Meta:
model (ServiceProvider): The model to be filtered.
fields (dict): The fields and lookup types to be used for filtering.
"""
user = filters.CharFilter(field_name='user__name', lookup_expr='icontains')
created_at__year__exact = filters.NumberFilter(field_name='created_at__year', lookup_expr='exact')
created_at__year__gt = filters.NumberFilter(field_name='created_at__year', lookup_expr='gt')
created_at__year__lt = filters.NumberFilter(field_name='created_at__year', lookup_expr='lt')
class Meta: | model = ServiceProvider | 0 | 2023-10-19 08:09:10+00:00 | 4k |
biggzlar/plausible-uncertainties | train.py | [
{
"identifier": "get_device",
"path": "utils.py",
"snippet": "def get_device():\n return torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
},
{
"identifier": "UnivariateDummyData",
"path": "utils.py",
"snippet": "class UnivariateDummyData:\n\tdef __init__(self, N, X_ra... | import tqdm
import torch
import numpy as np
import matplotlib.pyplot as plt
from utils import get_device, UnivariateDummyData, get_predicted_cdf
from evidential_regression.networks import UnivariateDerNet
from evidential_regression.losses import UnivariateEvidentialRegressionLoss
from mle_mc_dropout.networks import UnivariateKenNet
from mle_mc_dropout.losses import UnivariateL1Loss, UnivariateL2Loss, BetaNLLLoss | 2,487 |
# plot settings
plt.rcParams.update(
{
"font.size": 12,
"text.usetex": False,
"font.family": "stixgeneral",
"mathtext.fontset": "stix",
}
)
if __name__ == "__main__":
device = get_device()
print(f"Working on {device}!")
EPOCHS = 120
in_lower = -2.0
in_upper = 10.0
train_data = UnivariateDummyData(N=2000, X_range=(in_lower, in_upper))
test_data = UnivariateDummyData(N=100, X_range=(-10.0, 20.0))
train_loader = torch.utils.data.DataLoader(train_data, batch_size=128, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=32)
optimizer_params = {
"lr": 1e-03,
"betas": (0.9, 0.999),
"eps": 1e-8,
"weight_decay": 1e-2,
"amsgrad": False}
net = UnivariateDerNet()
net.to(device)
|
# plot settings
plt.rcParams.update(
{
"font.size": 12,
"text.usetex": False,
"font.family": "stixgeneral",
"mathtext.fontset": "stix",
}
)
if __name__ == "__main__":
device = get_device()
print(f"Working on {device}!")
EPOCHS = 120
in_lower = -2.0
in_upper = 10.0
train_data = UnivariateDummyData(N=2000, X_range=(in_lower, in_upper))
test_data = UnivariateDummyData(N=100, X_range=(-10.0, 20.0))
train_loader = torch.utils.data.DataLoader(train_data, batch_size=128, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=32)
optimizer_params = {
"lr": 1e-03,
"betas": (0.9, 0.999),
"eps": 1e-8,
"weight_decay": 1e-2,
"amsgrad": False}
net = UnivariateDerNet()
net.to(device) | criterion = UnivariateEvidentialRegressionLoss() | 4 | 2023-10-19 08:44:08+00:00 | 4k |
avilliai/Bert_Vits2_Sever | modules.py | [
{
"identifier": "init_weights",
"path": "commons.py",
"snippet": "def init_weights(m, mean=0.0, std=0.01):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n m.weight.data.normal_(mean, std)"
},
{
"identifier": "get_padding",
"path": "commons.py",
"snippet": "... | import copy
import math
import numpy as np
import scipy
import torch
import commons
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm
from commons import init_weights, get_padding
from transforms import piecewise_rational_quadratic_transform
from attentions import Encoder | 2,812 | self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout)
self.convs_sep = nn.ModuleList()
self.convs_1x1 = nn.ModuleList()
self.norms_1 = nn.ModuleList()
self.norms_2 = nn.ModuleList()
for i in range(n_layers):
dilation = kernel_size ** i
padding = (kernel_size * dilation - dilation) // 2
self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
groups=channels, dilation=dilation, padding=padding
))
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
self.norms_1.append(LayerNorm(channels))
self.norms_2.append(LayerNorm(channels))
def forward(self, x, x_mask, g=None):
if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
class WN(torch.nn.Module):
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
super(WN, self).__init__()
assert(kernel_size % 2 == 1)
self.hidden_channels =hidden_channels
self.kernel_size = kernel_size,
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.drop = nn.Dropout(p_dropout)
if gin_channels != 0:
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
for i in range(n_layers):
dilation = dilation_rate ** i
padding = int((kernel_size * dilation - dilation) / 2)
in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
dilation=dilation, padding=padding)
in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
self.in_layers.append(in_layer)
# last one is not necessary
if i < n_layers - 1:
res_skip_channels = 2 * hidden_channels
else:
res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
else:
g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(
x_in,
g_l,
n_channels_tensor)
acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts)
if i < self.n_layers - 1:
res_acts = res_skip_acts[:,:self.hidden_channels,:]
x = (x + res_acts) * x_mask
output = output + res_skip_acts[:,self.hidden_channels:,:]
else:
output = output + res_skip_acts
return output * x_mask
def remove_weight_norm(self):
if self.gin_channels != 0:
torch.nn.utils.remove_weight_norm(self.cond_layer)
for l in self.in_layers:
torch.nn.utils.remove_weight_norm(l)
for l in self.res_skip_layers:
torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2])))
])
|
LRELU_SLOPE = 0.1
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels))
self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x):
x = x.transpose(1, -1)
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
return x.transpose(1, -1)
class ConvReluNorm(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
assert n_layers > 1, "Number of layers should be larger than 0."
self.conv_layers = nn.ModuleList()
self.norm_layers = nn.ModuleList()
self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
self.norm_layers.append(LayerNorm(hidden_channels))
self.relu_drop = nn.Sequential(
nn.ReLU(),
nn.Dropout(p_dropout))
for _ in range(n_layers-1):
self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
self.norm_layers.append(LayerNorm(hidden_channels))
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask):
x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
class DDSConv(nn.Module):
"""
Dialted and Depth-Separable Convolution
"""
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
super().__init__()
self.channels = channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout)
self.convs_sep = nn.ModuleList()
self.convs_1x1 = nn.ModuleList()
self.norms_1 = nn.ModuleList()
self.norms_2 = nn.ModuleList()
for i in range(n_layers):
dilation = kernel_size ** i
padding = (kernel_size * dilation - dilation) // 2
self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
groups=channels, dilation=dilation, padding=padding
))
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
self.norms_1.append(LayerNorm(channels))
self.norms_2.append(LayerNorm(channels))
def forward(self, x, x_mask, g=None):
if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
class WN(torch.nn.Module):
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
super(WN, self).__init__()
assert(kernel_size % 2 == 1)
self.hidden_channels =hidden_channels
self.kernel_size = kernel_size,
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.drop = nn.Dropout(p_dropout)
if gin_channels != 0:
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
for i in range(n_layers):
dilation = dilation_rate ** i
padding = int((kernel_size * dilation - dilation) / 2)
in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
dilation=dilation, padding=padding)
in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
self.in_layers.append(in_layer)
# last one is not necessary
if i < n_layers - 1:
res_skip_channels = 2 * hidden_channels
else:
res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
else:
g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(
x_in,
g_l,
n_channels_tensor)
acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts)
if i < self.n_layers - 1:
res_acts = res_skip_acts[:,:self.hidden_channels,:]
x = (x + res_acts) * x_mask
output = output + res_skip_acts[:,self.hidden_channels:,:]
else:
output = output + res_skip_acts
return output * x_mask
def remove_weight_norm(self):
if self.gin_channels != 0:
torch.nn.utils.remove_weight_norm(self.cond_layer)
for l in self.in_layers:
torch.nn.utils.remove_weight_norm(l)
for l in self.res_skip_layers:
torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList([
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]))),
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2])))
]) | self.convs1.apply(init_weights) | 0 | 2023-10-23 08:24:12+00:00 | 4k |
t-ega/whatsapp-cloud-sdk | whatsapp_cloud_sdk/_files/contact.py | [
{
"identifier": "File",
"path": "whatsapp_cloud_sdk/_files/file_object.py",
"snippet": "class File:\n \"\"\"Base Class for all file objects.\"\"\"\n\n __slots__ = ()\n _id_attrs = ()\n\n def __str__(self):\n \"\"\"Return a string representation of the object.\"\"\"\n attributes... | from typing import List, Optional, Union
from whatsapp_cloud_sdk._files.file_object import File
from whatsapp_cloud_sdk._utils.types import JSONDict
from whatsapp_cloud_sdk._validators.messages import (
AddressValidator,
NameValidator,
PhoneValidator,
OrgValidator,
URLValidator,
EmailValidator,
) | 1,630 | """This module contains an object that represents a Whatsapp Contact and it related details."""
# pylint: disable=redefined-builtin
# pylint: disable=too-few-public-methods
class Address(File):
"""
Represents a contact address.
Args:
street (str): The street address.
city (str): The city.
state (str): The state.
zip (str): The ZIP code.
country (str): The country.
country_code (str): The country code.
type (str): The type of address.
Attributes:
street (str): The street address.
city (str): The city.
state (str): The state.
zip (str): The ZIP code.
country (str): The country.
country_code (str): The country code.
type (str): The type of address.
"""
__slots__ = (
"street",
"city",
"state",
"zip",
"country",
"country_code",
"type",
)
# pylint: disable=too-many-arguments
# pylint: disable=redefined-builtin
def __init__(
self,
street: str,
city: str,
state: str,
zip: str,
country: str,
country_code: str,
type: str,
):
| """This module contains an object that represents a Whatsapp Contact and it related details."""
# pylint: disable=redefined-builtin
# pylint: disable=too-few-public-methods
class Address(File):
"""
Represents a contact address.
Args:
street (str): The street address.
city (str): The city.
state (str): The state.
zip (str): The ZIP code.
country (str): The country.
country_code (str): The country code.
type (str): The type of address.
Attributes:
street (str): The street address.
city (str): The city.
state (str): The state.
zip (str): The ZIP code.
country (str): The country.
country_code (str): The country code.
type (str): The type of address.
"""
__slots__ = (
"street",
"city",
"state",
"zip",
"country",
"country_code",
"type",
)
# pylint: disable=too-many-arguments
# pylint: disable=redefined-builtin
def __init__(
self,
street: str,
city: str,
state: str,
zip: str,
country: str,
country_code: str,
type: str,
): | validator = AddressValidator( | 2 | 2023-10-15 21:12:45+00:00 | 4k |
caglarkucuk/earthformer-satellite-to-radar | ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py | [
{
"identifier": "CuboidSelfAttentionPatterns",
"path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer_patterns.py",
"snippet": "def full_attention(input_shape):\ndef self_axial(input_shape):\ndef self_video_swin(input_shape, P=2, M=4):\ndef self_divided_space_time(input_shape):\ndef self_... | from typing import Sequence, Union
from functools import lru_cache
from collections import OrderedDict
from torch import nn
from einops import rearrange
from .cuboid_transformer_patterns import CuboidSelfAttentionPatterns, CuboidCrossAttentionPatterns
from .utils import (
get_activation, get_norm_layer,
_generalize_padding, _generalize_unpadding,
apply_initialization, round_to)
import warnings
import torch
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint | 3,433 | # spatiotemporal learned positional embedding
if self.typ == 't+h+w':
self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim)
self.H_embed = nn.Embedding(num_embeddings=maxH, embedding_dim=embed_dim)
self.W_embed = nn.Embedding(num_embeddings=maxW, embedding_dim=embed_dim)
# nn.init.trunc_normal_(self.T_embed.weight, std=0.02)
# nn.init.trunc_normal_(self.H_embed.weight, std=0.02)
# nn.init.trunc_normal_(self.W_embed.weight, std=0.02)
elif self.typ == 't+hw':
self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim)
self.HW_embed = nn.Embedding(num_embeddings=maxH * maxW, embedding_dim=embed_dim)
# nn.init.trunc_normal_(self.T_embed.weight, std=0.02)
# nn.init.trunc_normal_(self.HW_embed.weight, std=0.02)
else:
raise NotImplementedError
self.reset_parameters()
def reset_parameters(self):
for m in self.children():
apply_initialization(m, embed_mode="0")
def forward(self, x):
"""
Parameters
----------
x
Shape (B, T, H, W, C)
Returns
-------
out
Return the x + positional embeddings
"""
_, T, H, W, _ = x.shape
t_idx = torch.arange(T, device=x.device) # (T, C)
h_idx = torch.arange(H, device=x.device) # (H, C)
w_idx = torch.arange(W, device=x.device) # (W, C)
if self.typ == 't+h+w':
return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim)\
+ self.H_embed(h_idx).reshape(1, H, 1, self.embed_dim)\
+ self.W_embed(w_idx).reshape(1, 1, W, self.embed_dim)
elif self.typ == 't+hw':
spatial_idx = h_idx.unsqueeze(-1) * self.maxW + w_idx
return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim) + self.HW_embed(spatial_idx)
else:
raise NotImplementedError
class PositionwiseFFN(nn.Module):
"""The Position-wise FFN layer used in Transformer-like architectures
If pre_norm is True:
norm(data) -> fc1 -> act -> act_dropout -> fc2 -> dropout -> res(+data)
Else:
data -> fc1 -> act -> act_dropout -> fc2 -> dropout -> norm(res(+data))
Also, if we use gated projection. We will use
fc1_1 * act(fc1_2(data)) to map the data
"""
def __init__(self,
units: int = 512,
hidden_size: int = 2048,
activation_dropout: float = 0.0,
dropout: float = 0.1,
gated_proj: bool = False,
activation='relu',
normalization: str = 'layer_norm',
layer_norm_eps: float = 1E-5,
pre_norm: bool = False,
linear_init_mode="0",
norm_init_mode="0",
):
"""
Parameters
----------
units
hidden_size
activation_dropout
dropout
activation
normalization
layer_norm or no_norm
layer_norm_eps
pre_norm
Pre-layer normalization as proposed in the paper:
"[ACL2018] The Best of Both Worlds: Combining Recent Advances in
Neural Machine Translation"
This will stabilize the training of Transformers.
You may also refer to
"[Arxiv2020] Understanding the Difficulty of Training Transformers"
"""
super().__init__()
# initialization
self.linear_init_mode = linear_init_mode
self.norm_init_mode = norm_init_mode
self._pre_norm = pre_norm
self._gated_proj = gated_proj
self._kwargs = OrderedDict([
('units', units),
('hidden_size', hidden_size),
('activation_dropout', activation_dropout),
('activation', activation),
('dropout', dropout),
('normalization', normalization),
('layer_norm_eps', layer_norm_eps),
('gated_proj', gated_proj),
('pre_norm', pre_norm)
])
self.dropout_layer = nn.Dropout(dropout)
self.activation_dropout_layer = nn.Dropout(activation_dropout)
self.ffn_1 = nn.Linear(in_features=units, out_features=hidden_size,
bias=True)
if self._gated_proj:
self.ffn_1_gate = nn.Linear(in_features=units,
out_features=hidden_size,
bias=True)
self.activation = get_activation(activation)
self.ffn_2 = nn.Linear(in_features=hidden_size, out_features=units,
bias=True)
| """Only change done in this file is the added upsampling layer to the CuboidTransformerModel,
which increaes `h` and `w` dimensions of the input tensor by 2x to match the dimensions of the output tensor!
The rest is same with the original file from EarthFormer repo!
"""
"""A space-time Transformer with Cuboid Attention"""
class PosEmbed(nn.Module):
def __init__(self, embed_dim, maxT, maxH, maxW, typ='t+h+w'):
r"""
Parameters
----------
embed_dim
maxT
maxH
maxW
typ
The type of the positional embedding.
- t+h+w:
Embed the spatial position to embeddings
- t+hw:
Embed the spatial position to embeddings
"""
super(PosEmbed, self).__init__()
self.typ = typ
assert self.typ in ['t+h+w', 't+hw']
self.maxT = maxT
self.maxH = maxH
self.maxW = maxW
self.embed_dim = embed_dim
# spatiotemporal learned positional embedding
if self.typ == 't+h+w':
self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim)
self.H_embed = nn.Embedding(num_embeddings=maxH, embedding_dim=embed_dim)
self.W_embed = nn.Embedding(num_embeddings=maxW, embedding_dim=embed_dim)
# nn.init.trunc_normal_(self.T_embed.weight, std=0.02)
# nn.init.trunc_normal_(self.H_embed.weight, std=0.02)
# nn.init.trunc_normal_(self.W_embed.weight, std=0.02)
elif self.typ == 't+hw':
self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim)
self.HW_embed = nn.Embedding(num_embeddings=maxH * maxW, embedding_dim=embed_dim)
# nn.init.trunc_normal_(self.T_embed.weight, std=0.02)
# nn.init.trunc_normal_(self.HW_embed.weight, std=0.02)
else:
raise NotImplementedError
self.reset_parameters()
def reset_parameters(self):
for m in self.children():
apply_initialization(m, embed_mode="0")
def forward(self, x):
"""
Parameters
----------
x
Shape (B, T, H, W, C)
Returns
-------
out
Return the x + positional embeddings
"""
_, T, H, W, _ = x.shape
t_idx = torch.arange(T, device=x.device) # (T, C)
h_idx = torch.arange(H, device=x.device) # (H, C)
w_idx = torch.arange(W, device=x.device) # (W, C)
if self.typ == 't+h+w':
return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim)\
+ self.H_embed(h_idx).reshape(1, H, 1, self.embed_dim)\
+ self.W_embed(w_idx).reshape(1, 1, W, self.embed_dim)
elif self.typ == 't+hw':
spatial_idx = h_idx.unsqueeze(-1) * self.maxW + w_idx
return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim) + self.HW_embed(spatial_idx)
else:
raise NotImplementedError
class PositionwiseFFN(nn.Module):
"""The Position-wise FFN layer used in Transformer-like architectures
If pre_norm is True:
norm(data) -> fc1 -> act -> act_dropout -> fc2 -> dropout -> res(+data)
Else:
data -> fc1 -> act -> act_dropout -> fc2 -> dropout -> norm(res(+data))
Also, if we use gated projection. We will use
fc1_1 * act(fc1_2(data)) to map the data
"""
def __init__(self,
units: int = 512,
hidden_size: int = 2048,
activation_dropout: float = 0.0,
dropout: float = 0.1,
gated_proj: bool = False,
activation='relu',
normalization: str = 'layer_norm',
layer_norm_eps: float = 1E-5,
pre_norm: bool = False,
linear_init_mode="0",
norm_init_mode="0",
):
"""
Parameters
----------
units
hidden_size
activation_dropout
dropout
activation
normalization
layer_norm or no_norm
layer_norm_eps
pre_norm
Pre-layer normalization as proposed in the paper:
"[ACL2018] The Best of Both Worlds: Combining Recent Advances in
Neural Machine Translation"
This will stabilize the training of Transformers.
You may also refer to
"[Arxiv2020] Understanding the Difficulty of Training Transformers"
"""
super().__init__()
# initialization
self.linear_init_mode = linear_init_mode
self.norm_init_mode = norm_init_mode
self._pre_norm = pre_norm
self._gated_proj = gated_proj
self._kwargs = OrderedDict([
('units', units),
('hidden_size', hidden_size),
('activation_dropout', activation_dropout),
('activation', activation),
('dropout', dropout),
('normalization', normalization),
('layer_norm_eps', layer_norm_eps),
('gated_proj', gated_proj),
('pre_norm', pre_norm)
])
self.dropout_layer = nn.Dropout(dropout)
self.activation_dropout_layer = nn.Dropout(activation_dropout)
self.ffn_1 = nn.Linear(in_features=units, out_features=hidden_size,
bias=True)
if self._gated_proj:
self.ffn_1_gate = nn.Linear(in_features=units,
out_features=hidden_size,
bias=True)
self.activation = get_activation(activation)
self.ffn_2 = nn.Linear(in_features=hidden_size, out_features=units,
bias=True) | self.layer_norm = get_norm_layer(normalization=normalization, | 2 | 2023-10-23 11:45:50+00:00 | 4k |
DTennant/GPC | data/fgvc_aircraft.py | [
{
"identifier": "subsample_instances",
"path": "data/data_utils.py",
"snippet": "def subsample_instances(dataset, prop_indices_to_subsample=0.8):\n\n np.random.seed(0)\n subsample_indices = np.random.choice(range(len(dataset)), replace=False,\n size=(int(pro... | import os
import pandas as pd
import numpy as np
import tarfile
from copy import deepcopy
from torchvision.datasets.folder import default_loader
from torch.utils.data import Dataset
from data.data_utils import subsample_instances
from config import aircraft_root
from six.moves import urllib | 2,580 | index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target, self.uq_idxs[index]
def __len__(self):
return len(self.samples)
def __repr__(self):
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
tmp = ' Target Transforms (if any): '
fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
def _check_exists(self):
return os.path.exists(os.path.join(self.root, 'data', 'images')) and \
os.path.exists(self.classes_file)
def download(self):
"""Download the FGVC-Aircraft data if it doesn't exist already."""
if self._check_exists():
return
# prepare to download data to PARENT_DIR/fgvc-aircraft-2013.tar.gz
print('Downloading %s ... (may take a few minutes)' % self.url)
parent_dir = os.path.abspath(os.path.join(self.root, os.pardir))
tar_name = self.url.rpartition('/')[-1]
tar_path = os.path.join(parent_dir, tar_name)
data = urllib.request.urlopen(self.url)
# download .tar.gz file
with open(tar_path, 'wb') as f:
f.write(data.read())
# extract .tar.gz to PARENT_DIR/fgvc-aircraft-2013b
data_folder = tar_path.strip('.tar.gz')
print('Extracting %s to %s ... (may take a few minutes)' % (tar_path, data_folder))
tar = tarfile.open(tar_path)
tar.extractall(parent_dir)
# if necessary, rename data folder to self.root
if not os.path.samefile(data_folder, self.root):
print('Renaming %s to %s ...' % (data_folder, self.root))
os.rename(data_folder, self.root)
# delete .tar.gz file
print('Deleting %s ...' % tar_path)
os.remove(tar_path)
print('Done!')
def subsample_dataset(dataset, idxs):
mask = np.zeros(len(dataset)).astype('bool')
mask[idxs] = True
dataset.samples = [(p, t) for i, (p, t) in enumerate(dataset.samples) if i in idxs]
dataset.uq_idxs = dataset.uq_idxs[mask]
return dataset
def subsample_classes(dataset, include_classes=range(60)):
cls_idxs = [i for i, (p, t) in enumerate(dataset.samples) if t in include_classes]
# TODO: Don't transform targets for now
target_xform_dict = {}
for i, k in enumerate(include_classes):
target_xform_dict[k] = i
dataset = subsample_dataset(dataset, cls_idxs)
dataset.target_transform = lambda x: target_xform_dict[x]
return dataset
def get_train_val_indices(train_dataset, val_split=0.2):
all_targets = [t for i, (p, t) in enumerate(train_dataset.samples)]
train_classes = np.unique(all_targets)
# Get train/test indices
train_idxs = []
val_idxs = []
for cls in train_classes:
cls_idxs = np.where(all_targets == cls)[0]
v_ = np.random.choice(cls_idxs, replace=False, size=((int(val_split * len(cls_idxs))),))
t_ = [x for x in cls_idxs if x not in v_]
train_idxs.extend(t_)
val_idxs.extend(v_)
return train_idxs, val_idxs
def get_aircraft_datasets(train_transform, test_transform, train_classes=range(50), prop_train_labels=0.8,
split_train_val=False, seed=0):
np.random.seed(seed)
# Init entire training set
|
def make_dataset(dir, image_ids, targets):
assert(len(image_ids) == len(targets))
images = []
dir = os.path.expanduser(dir)
for i in range(len(image_ids)):
item = (os.path.join(dir, 'data', 'images',
'%s.jpg' % image_ids[i]), targets[i])
images.append(item)
return images
def find_classes(classes_file):
# read classes file, separating out image IDs and class names
image_ids = []
targets = []
f = open(classes_file, 'r')
for line in f:
split_line = line.split(' ')
image_ids.append(split_line[0])
targets.append(' '.join(split_line[1:]))
f.close()
# index class names
classes = np.unique(targets)
class_to_idx = {classes[i]: i for i in range(len(classes))}
targets = [class_to_idx[c] for c in targets]
return (image_ids, targets, classes, class_to_idx)
class FGVCAircraft(Dataset):
"""`FGVC-Aircraft <http://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft>`_ Dataset.
Args:
root (string): Root directory path to dataset.
class_type (string, optional): The level of FGVC-Aircraft fine-grain classification
to label data with (i.e., ``variant``, ``family``, or ``manufacturer``).
transform (callable, optional): A function/transform that takes in a PIL image
and returns a transformed version. E.g. ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that takes in the
target and transforms it.
loader (callable, optional): A function to load an image given its path.
download (bool, optional): If true, downloads the dataset from the internet and
puts it in the root directory. If dataset is already downloaded, it is not
downloaded again.
"""
url = 'http://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/archives/fgvc-aircraft-2013b.tar.gz'
class_types = ('variant', 'family', 'manufacturer')
splits = ('train', 'val', 'trainval', 'test')
def __init__(self, root, class_type='variant', split='train', transform=None,
target_transform=None, loader=default_loader, download=False):
if split not in self.splits:
raise ValueError('Split "{}" not found. Valid splits are: {}'.format(
split, ', '.join(self.splits),
))
if class_type not in self.class_types:
raise ValueError('Class type "{}" not found. Valid class types are: {}'.format(
class_type, ', '.join(self.class_types),
))
self.root = os.path.expanduser(root)
self.class_type = class_type
self.split = split
self.classes_file = os.path.join(self.root, 'data',
'images_%s_%s.txt' % (self.class_type, self.split))
if download:
self.download()
(image_ids, targets, classes, class_to_idx) = find_classes(self.classes_file)
samples = make_dataset(self.root, image_ids, targets)
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.samples = samples
self.classes = classes
self.class_to_idx = class_to_idx
self.train = True if split == 'train' else False
self.uq_idxs = np.array(range(len(self)))
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target, self.uq_idxs[index]
def __len__(self):
return len(self.samples)
def __repr__(self):
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
tmp = ' Target Transforms (if any): '
fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
def _check_exists(self):
return os.path.exists(os.path.join(self.root, 'data', 'images')) and \
os.path.exists(self.classes_file)
def download(self):
"""Download the FGVC-Aircraft data if it doesn't exist already."""
if self._check_exists():
return
# prepare to download data to PARENT_DIR/fgvc-aircraft-2013.tar.gz
print('Downloading %s ... (may take a few minutes)' % self.url)
parent_dir = os.path.abspath(os.path.join(self.root, os.pardir))
tar_name = self.url.rpartition('/')[-1]
tar_path = os.path.join(parent_dir, tar_name)
data = urllib.request.urlopen(self.url)
# download .tar.gz file
with open(tar_path, 'wb') as f:
f.write(data.read())
# extract .tar.gz to PARENT_DIR/fgvc-aircraft-2013b
data_folder = tar_path.strip('.tar.gz')
print('Extracting %s to %s ... (may take a few minutes)' % (tar_path, data_folder))
tar = tarfile.open(tar_path)
tar.extractall(parent_dir)
# if necessary, rename data folder to self.root
if not os.path.samefile(data_folder, self.root):
print('Renaming %s to %s ...' % (data_folder, self.root))
os.rename(data_folder, self.root)
# delete .tar.gz file
print('Deleting %s ...' % tar_path)
os.remove(tar_path)
print('Done!')
def subsample_dataset(dataset, idxs):
mask = np.zeros(len(dataset)).astype('bool')
mask[idxs] = True
dataset.samples = [(p, t) for i, (p, t) in enumerate(dataset.samples) if i in idxs]
dataset.uq_idxs = dataset.uq_idxs[mask]
return dataset
def subsample_classes(dataset, include_classes=range(60)):
cls_idxs = [i for i, (p, t) in enumerate(dataset.samples) if t in include_classes]
# TODO: Don't transform targets for now
target_xform_dict = {}
for i, k in enumerate(include_classes):
target_xform_dict[k] = i
dataset = subsample_dataset(dataset, cls_idxs)
dataset.target_transform = lambda x: target_xform_dict[x]
return dataset
def get_train_val_indices(train_dataset, val_split=0.2):
all_targets = [t for i, (p, t) in enumerate(train_dataset.samples)]
train_classes = np.unique(all_targets)
# Get train/test indices
train_idxs = []
val_idxs = []
for cls in train_classes:
cls_idxs = np.where(all_targets == cls)[0]
v_ = np.random.choice(cls_idxs, replace=False, size=((int(val_split * len(cls_idxs))),))
t_ = [x for x in cls_idxs if x not in v_]
train_idxs.extend(t_)
val_idxs.extend(v_)
return train_idxs, val_idxs
def get_aircraft_datasets(train_transform, test_transform, train_classes=range(50), prop_train_labels=0.8,
split_train_val=False, seed=0):
np.random.seed(seed)
# Init entire training set | whole_training_set = FGVCAircraft(root=aircraft_root, transform=train_transform, split='trainval') | 1 | 2023-10-23 18:23:22+00:00 | 4k |
camenduru/MiniGPT-v2-hf | minigpt4/models/base_model.py | [
{
"identifier": "download_cached_file",
"path": "minigpt4/common/dist_utils.py",
"snippet": "def download_cached_file(url, check_hash=True, progress=False):\n \"\"\"\n Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again.\n If distributed, only... | import os
import logging
import contextlib
import numpy as np
import torch
import torch.nn as nn
from omegaconf import OmegaConf
from transformers import BertTokenizer, LlamaTokenizer
from transformers.models.llama.modeling_llama import LlamaForCausalLM
from peft import (
LoraConfig,
get_peft_model,
prepare_model_for_int8_training,
)
from minigpt4.common.dist_utils import download_cached_file, is_dist_avail_and_initialized
from minigpt4.common.utils import get_abs_path, is_url
from minigpt4.models.eva_vit import create_eva_vit_g | 1,732 | """Base class for models."""
def __init__(self):
super().__init__()
@property
def device(self):
return list(self.parameters())[-1].device
def load_checkpoint(self, url_or_filename):
"""
Load from a finetuned checkpoint.
This should expect no mismatch in the model keys and the checkpoint keys.
"""
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if "model" in checkpoint.keys():
state_dict = checkpoint["model"]
else:
state_dict = checkpoint
msg = self.load_state_dict(state_dict, strict=False)
logging.info("Missing keys {}".format(msg.missing_keys))
logging.info("load checkpoint from %s" % url_or_filename)
return msg
@classmethod
def from_pretrained(cls, model_type):
"""
Build a pretrained model from default configuration file, specified by model_type.
Args:
- model_type (str): model type, specifying architecture and checkpoints.
Returns:
- model (nn.Module): pretrained or finetuned model, depending on the configuration.
"""
model_cfg = OmegaConf.load(cls.default_config_path(model_type)).model
model = cls.from_config(model_cfg)
return model
@classmethod
def default_config_path(cls, model_type):
assert (
model_type in cls.PRETRAINED_MODEL_CONFIG_DICT
), "Unknown model type {}".format(model_type)
return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type])
def load_checkpoint_from_config(self, cfg, **kwargs):
"""
Load checkpoint as specified in the config file.
If load_finetuned is True, load the finetuned model; otherwise, load the pretrained model.
When loading the pretrained model, each task-specific architecture may define their
own load_from_pretrained() method.
"""
load_finetuned = cfg.get("load_finetuned", True)
if load_finetuned:
finetune_path = cfg.get("finetuned", None)
assert (
finetune_path is not None
), "Found load_finetuned is True, but finetune_path is None."
self.load_checkpoint(url_or_filename=finetune_path)
else:
# load pre-trained weights
pretrain_path = cfg.get("pretrained", None)
assert "Found load_finetuned is False, but pretrain_path is None."
self.load_from_pretrained(url_or_filename=pretrain_path, **kwargs)
def before_evaluation(self, **kwargs):
pass
def show_n_params(self, return_str=True):
tot = 0
for p in self.parameters():
w = 1
for x in p.shape:
w *= x
tot += w
if return_str:
if tot >= 1e6:
return "{:.1f}M".format(tot / 1e6)
else:
return "{:.1f}K".format(tot / 1e3)
else:
return tot
def maybe_autocast(self, dtype=torch.float16):
# if on cpu, don't use autocast
# if on gpu, use autocast with dtype if provided, otherwise use torch.float16
enable_autocast = self.device != torch.device("cpu")
if enable_autocast:
return torch.cuda.amp.autocast(dtype=dtype)
else:
return contextlib.nullcontext()
@classmethod
def init_vision_encoder(
cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision, freeze
):
logging.info('Loading VIT')
assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4"
if not freeze:
precision = "fp32" # fp16 is not for training
| """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class BaseModel(nn.Module):
"""Base class for models."""
def __init__(self):
super().__init__()
@property
def device(self):
return list(self.parameters())[-1].device
def load_checkpoint(self, url_or_filename):
"""
Load from a finetuned checkpoint.
This should expect no mismatch in the model keys and the checkpoint keys.
"""
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if "model" in checkpoint.keys():
state_dict = checkpoint["model"]
else:
state_dict = checkpoint
msg = self.load_state_dict(state_dict, strict=False)
logging.info("Missing keys {}".format(msg.missing_keys))
logging.info("load checkpoint from %s" % url_or_filename)
return msg
@classmethod
def from_pretrained(cls, model_type):
"""
Build a pretrained model from default configuration file, specified by model_type.
Args:
- model_type (str): model type, specifying architecture and checkpoints.
Returns:
- model (nn.Module): pretrained or finetuned model, depending on the configuration.
"""
model_cfg = OmegaConf.load(cls.default_config_path(model_type)).model
model = cls.from_config(model_cfg)
return model
@classmethod
def default_config_path(cls, model_type):
assert (
model_type in cls.PRETRAINED_MODEL_CONFIG_DICT
), "Unknown model type {}".format(model_type)
return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type])
def load_checkpoint_from_config(self, cfg, **kwargs):
"""
Load checkpoint as specified in the config file.
If load_finetuned is True, load the finetuned model; otherwise, load the pretrained model.
When loading the pretrained model, each task-specific architecture may define their
own load_from_pretrained() method.
"""
load_finetuned = cfg.get("load_finetuned", True)
if load_finetuned:
finetune_path = cfg.get("finetuned", None)
assert (
finetune_path is not None
), "Found load_finetuned is True, but finetune_path is None."
self.load_checkpoint(url_or_filename=finetune_path)
else:
# load pre-trained weights
pretrain_path = cfg.get("pretrained", None)
assert "Found load_finetuned is False, but pretrain_path is None."
self.load_from_pretrained(url_or_filename=pretrain_path, **kwargs)
def before_evaluation(self, **kwargs):
pass
def show_n_params(self, return_str=True):
tot = 0
for p in self.parameters():
w = 1
for x in p.shape:
w *= x
tot += w
if return_str:
if tot >= 1e6:
return "{:.1f}M".format(tot / 1e6)
else:
return "{:.1f}K".format(tot / 1e3)
else:
return tot
def maybe_autocast(self, dtype=torch.float16):
# if on cpu, don't use autocast
# if on gpu, use autocast with dtype if provided, otherwise use torch.float16
enable_autocast = self.device != torch.device("cpu")
if enable_autocast:
return torch.cuda.amp.autocast(dtype=dtype)
else:
return contextlib.nullcontext()
@classmethod
def init_vision_encoder(
cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision, freeze
):
logging.info('Loading VIT')
assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4"
if not freeze:
precision = "fp32" # fp16 is not for training
| visual_encoder = create_eva_vit_g( | 4 | 2023-10-15 19:54:22+00:00 | 4k |
deepghs/sdeval | sdeval/corrupt/aicorrupt.py | [
{
"identifier": "load_images",
"path": "sdeval/utils/images.py",
"snippet": "def _yield_images(images: ImagesTyping) -> Iterator[Image.Image]:\ndef load_images(images: ImagesTyping) -> List[Image.Image]:"
},
{
"identifier": "tqdm",
"path": "sdeval/utils/tqdm_.py",
"snippet": "def tqdm(*a... | import json
import numpy as np
from functools import lru_cache
from typing import Tuple, Optional, Mapping
from PIL import Image
from huggingface_hub import hf_hub_download
from imgutils.data import rgb_encode, ImageTyping, load_image
from imgutils.utils import open_onnx_model
from ..utils import ImagesTyping, load_images, tqdm | 1,616 | This function downloads and opens the meta information of the AI image corrupted detection model specified by the given model name using Hugging Face Hub.
:param model_name: The name of the AI image corrupted detection model.
:type model_name: str
:return: The opened meta information of the AI image corrupted detection model.
:rtype: dict
"""
with open(hf_hub_download(
f'deepghs/ai_image_corrupted',
f'{model_name}/meta.json',
), 'r', encoding='utf-8') as f:
return json.load(f)
@lru_cache()
def _open_anime_aicop_labels(model_name: str):
"""
Open the labels of the AI image corrupted detection model.
This function opens the labels of the AI image corrupted detection model specified by the given model name.
:param model_name: The name of the AI image corrupted detection model.
:type model_name: str
:return: The labels of the AI image corrupted detection model.
:rtype: List[str]
"""
return _open_anime_aicop_meta(model_name)['labels']
def _img_encode(image: Image.Image, size: Tuple[int, int] = (384, 384),
normalize: Optional[Tuple[float, float]] = (0.5, 0.5)):
"""
Encode the image for AI image corrupted detection.
This function resizes and encodes the image for AI image corrupted detection.
:param image: The input image.
:type image: Image.Image
:param size: The target size for encoding. Default is (384, 384).
:type size: Tuple[int, int]
:param normalize: The normalization parameters. Default is (0.5, 0.5).
:type normalize: Optional[Tuple[float, float]]
:return: The encoded image data.
:rtype: np.ndarray
"""
image = image.resize(size, Image.BILINEAR)
data = rgb_encode(image, order_='CHW')
if normalize is not None:
mean_, std_ = normalize
mean = np.asarray([mean_]).reshape((-1, 1, 1))
std = np.asarray([std_]).reshape((-1, 1, 1))
data = (data - mean) / std
return data.astype(np.float32)
def get_ai_corrupted(image: ImageTyping, model_name: str = _DEFAULT_MODEL_NAME) -> Mapping[str, float]:
"""
Get AI image corrupted detection scores for an image.
This function calculates AI image corrupted detection scores for a given image using the specified model.
:param image: The input image.
:type image: ImageTyping
:param model_name: The name of the AI image corrupted detection model. Default is 'caformer_s36_v0_focal'.
:type model_name: str
:return: A dictionary containing the corrupted score.
:rtype: Mapping[str, float]
"""
image = load_image(image, force_background='white', mode='RGB')
input_ = _img_encode(image)[None, ...]
output, = _open_anime_aicop_model(model_name).run(['output'], {'input': input_})
return dict(zip(_open_anime_aicop_labels(model_name), output[0].tolist()))
class AICorruptMetrics:
"""
Class for calculating an AI image corruptness score.
The `AICorruptMetrics` class allows you to calculate an AI image corruptness score using the AI image corrupted detection model.
:param model_name: The name of the AI image corrupted detection model. Default is 'caformer_s36_v0_focal'.
:type model_name: str
:param silent: If True, suppresses progress bars and additional output during calculation.
:type silent: bool
:param tqdm_desc: Description for the tqdm progress bar during calculation.
:type tqdm_desc: str
"""
def __init__(self, model_name: str = _DEFAULT_MODEL_NAME,
silent: bool = False, tqdm_desc: str = None):
self._model_name = model_name
self.silent = silent
self.tqdm_desc = tqdm_desc or self.__class__.__name__
def score(self, images: ImagesTyping, silent: bool = None):
"""
Calculate the AI image corruptness score for a set of images.
This method calculates the AI image corruptness score for a set of input images using the AI image corrupted detection model.
:param images: The set of input images for calculating the AI image corruptness score.
:type images: ImagesTyping
:param silent: If True, suppresses progress bars and additional output during calculation.
:type silent: bool
:return: The AI image corruptness score.
:rtype: float
"""
image_list = load_images(images)
if not image_list:
raise FileNotFoundError(f'Images for calculating AI corrupt score not provided - {images}.')
scores = np.array([
get_ai_corrupted(image, model_name=self._model_name)['corrupted']
| """
Overview:
AI image corrupt evaluation metrics.
"""
_DEFAULT_MODEL_NAME = 'caformer_s36_v0_focal'
@lru_cache()
def _open_anime_aicop_model(model_name: str):
"""
Open the AI image corrupted detection model.
This function downloads and opens the AI image corrupted detection model specified by the given model name using Hugging Face Hub.
:param model_name: The name of the AI image corrupted detection model.
:type model_name: str
:return: The opened AI image corrupted detection model.
:rtype: Model
"""
return open_onnx_model(hf_hub_download(
f'deepghs/ai_image_corrupted',
f'{model_name}/model.onnx',
))
@lru_cache()
def _open_anime_aicop_meta(model_name: str):
"""
Open the meta information of the AI image corrupted detection model.
This function downloads and opens the meta information of the AI image corrupted detection model specified by the given model name using Hugging Face Hub.
:param model_name: The name of the AI image corrupted detection model.
:type model_name: str
:return: The opened meta information of the AI image corrupted detection model.
:rtype: dict
"""
with open(hf_hub_download(
f'deepghs/ai_image_corrupted',
f'{model_name}/meta.json',
), 'r', encoding='utf-8') as f:
return json.load(f)
@lru_cache()
def _open_anime_aicop_labels(model_name: str):
"""
Open the labels of the AI image corrupted detection model.
This function opens the labels of the AI image corrupted detection model specified by the given model name.
:param model_name: The name of the AI image corrupted detection model.
:type model_name: str
:return: The labels of the AI image corrupted detection model.
:rtype: List[str]
"""
return _open_anime_aicop_meta(model_name)['labels']
def _img_encode(image: Image.Image, size: Tuple[int, int] = (384, 384),
normalize: Optional[Tuple[float, float]] = (0.5, 0.5)):
"""
Encode the image for AI image corrupted detection.
This function resizes and encodes the image for AI image corrupted detection.
:param image: The input image.
:type image: Image.Image
:param size: The target size for encoding. Default is (384, 384).
:type size: Tuple[int, int]
:param normalize: The normalization parameters. Default is (0.5, 0.5).
:type normalize: Optional[Tuple[float, float]]
:return: The encoded image data.
:rtype: np.ndarray
"""
image = image.resize(size, Image.BILINEAR)
data = rgb_encode(image, order_='CHW')
if normalize is not None:
mean_, std_ = normalize
mean = np.asarray([mean_]).reshape((-1, 1, 1))
std = np.asarray([std_]).reshape((-1, 1, 1))
data = (data - mean) / std
return data.astype(np.float32)
def get_ai_corrupted(image: ImageTyping, model_name: str = _DEFAULT_MODEL_NAME) -> Mapping[str, float]:
"""
Get AI image corrupted detection scores for an image.
This function calculates AI image corrupted detection scores for a given image using the specified model.
:param image: The input image.
:type image: ImageTyping
:param model_name: The name of the AI image corrupted detection model. Default is 'caformer_s36_v0_focal'.
:type model_name: str
:return: A dictionary containing the corrupted score.
:rtype: Mapping[str, float]
"""
image = load_image(image, force_background='white', mode='RGB')
input_ = _img_encode(image)[None, ...]
output, = _open_anime_aicop_model(model_name).run(['output'], {'input': input_})
return dict(zip(_open_anime_aicop_labels(model_name), output[0].tolist()))
class AICorruptMetrics:
"""
Class for calculating an AI image corruptness score.
The `AICorruptMetrics` class allows you to calculate an AI image corruptness score using the AI image corrupted detection model.
:param model_name: The name of the AI image corrupted detection model. Default is 'caformer_s36_v0_focal'.
:type model_name: str
:param silent: If True, suppresses progress bars and additional output during calculation.
:type silent: bool
:param tqdm_desc: Description for the tqdm progress bar during calculation.
:type tqdm_desc: str
"""
def __init__(self, model_name: str = _DEFAULT_MODEL_NAME,
silent: bool = False, tqdm_desc: str = None):
self._model_name = model_name
self.silent = silent
self.tqdm_desc = tqdm_desc or self.__class__.__name__
def score(self, images: ImagesTyping, silent: bool = None):
"""
Calculate the AI image corruptness score for a set of images.
This method calculates the AI image corruptness score for a set of input images using the AI image corrupted detection model.
:param images: The set of input images for calculating the AI image corruptness score.
:type images: ImagesTyping
:param silent: If True, suppresses progress bars and additional output during calculation.
:type silent: bool
:return: The AI image corruptness score.
:rtype: float
"""
image_list = load_images(images)
if not image_list:
raise FileNotFoundError(f'Images for calculating AI corrupt score not provided - {images}.')
scores = np.array([
get_ai_corrupted(image, model_name=self._model_name)['corrupted'] | for image in tqdm(image_list, silent=self.silent if silent is None else silent, desc=self.tqdm_desc) | 1 | 2023-10-18 03:35:52+00:00 | 4k |
nju-websoft/SCR | framework/dataloader.py | [
{
"identifier": "trigger_combine_event",
"path": "framework/utils.py",
"snippet": "def trigger_combine_event(old_data, new_data):\n if len(new_data) == 0:\n return old_data\n init = False\n res = []\n if len(old_data) == 0:\n init = True\n old_data = copy.deepcopy(new_da... | import torch
import os
import copy
import numpy as np
import random
import json
from torch.utils.data import Dataset, DataLoader
from framework.utils import trigger_combine_event, args_combine_event
from transformers import BertTokenizer
from transformers import logging | 3,446 | # ner2id
self.ner2id = json.load(open(self.data_root+'ner2id.json', 'r'))
self.ner2id['None'] = 0
self.id2ner = {}
for key, value in self.ner2id.items():
self.id2ner[value] = key
# iter
self.stream_turn = config.stream_turn
self.batch = 0
# data stream
self.train_stream = json.load(open(self.data_root+'train_streams.json', 'r'))
self.id2stream = json.load(open(self.data_root+'id2stream.json', 'r'))
# set seed
self.seed = config.seed
random.seed(self.seed)
np.random.seed(self.seed)
self.shuffle_index = list(range(self.stream_turn))
random.shuffle(self.shuffle_index)
self.shuffle_index = np.argsort(self.shuffle_index)
#self.shuffle_index = PERM[i]
print(self.shuffle_index)
# seen data
self.seen_test_data = []
self.seen_dev_data = []
self.seen_event = []
self.seen_test_args_data = []
self.seen_dev_args_data = []
self.seen_args = []
self.ltlabel = []
# prepare data:
self.train_dataset, self.dev_dataset, self.test_dataset = self.read_data(self.data_root)
# tokenizer:
self.tokenizer = BertTokenizer.from_pretrained(config.bert_path)
if config.argument:
# role2id
self.role2id = json.load(open(self.data_root+'role2id.json', 'r'))
self.role2id['None'] = 0
self.id2role = {}
for key, value in self.role2id.items():
self.id2role[value] = key
# metadata
self.args_num = config.args_num
self.metadata = json.load(open(self.data_root+'metadata.json', 'r'))
self.unseen_metadata = {}
for key, value in self.metadata.items():
new_value = [self.role2id[val] for val in value]
self.metadata[key] = new_value
unseen_args = [i for i in range(self.args_num)]
unseen_args = list(set(unseen_args) - set(new_value) - set([0]))
self.unseen_metadata[key] = unseen_args
self.args_train_dataset, self.args_dev_dataset, self.args_test_dataset = self.read_args_data(self.data_root)
if config.lttest:
self.ltlabel = json.load(open(self.data_root+'lt_label.json', 'r'))
def __iter__(self):
return self
def __len__(self):
return self.stream_turn
def __next__(self):
cur_train_data, cur_test_data, cur_dev_data, current_event = [], [], [], []
if self.batch == self.stream_turn:
self.batch = 0
raise StopIteration()
index = self.shuffle_index[self.batch]
# now is tirgger data
cur_train_data = self.train_dataset[index]
cur_dev_data = self.dev_dataset[index]
cur_test_data = self.test_dataset[index]
current_event = self.train_stream[index]
self.seen_event += current_event
self.batch += 1
final_data = [[] , [] , []]
for i, data in enumerate([cur_train_data, cur_dev_data, cur_test_data]):
for x in data:
final_data[i] += data[x]
tr_data, de_data, cur_te_data = final_data
tr_data = trigger_combine_event([], tr_data)
de_data = trigger_combine_event([], de_data)
cur_te_data = trigger_combine_event([], cur_te_data)
temp_cur = copy.deepcopy(cur_te_data)
temp_dev = copy.deepcopy(de_data)
self.seen_test_data = trigger_combine_event(self.seen_test_data, temp_cur)
self.seen_dev_data = trigger_combine_event(self.seen_dev_data, temp_dev)
if self.config.argument:
# now is args data
cur_args_train_data = self.args_train_dataset[index]
cur_args_dev_data = self.args_dev_dataset[index]
cur_args_test_data = self.args_test_dataset[index]
#current_args = self.args_stream[index]
#self.seen_args = list(set(self.seen_args + current_args))
#unseen_args = [i for i in range(self.args_num)]
#unseen_args = list(set(unseen_args) - set(self.seen_args)- set([0]))
args_final_data = [[] , [] , []]
for i, data in enumerate([cur_args_train_data, cur_args_dev_data, cur_args_test_data]):
for x in data:
args_final_data[i] += data[x]
tr_args_data, de_args_data, cur_args_te_data = args_final_data
| logging.set_verbosity_warning()
logging.set_verbosity_error()
class ACETriDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
def collate_fn(self, data):
sentence_ids = [torch.tensor(item['sentence_ids']) for item in data]
input_ids = [torch.tensor(item['input_ids']) for item in data]
input_masks = [torch.tensor(item['input_masks']) for item in data]
in_sent = [torch.tensor(item['in_sent']) for item in data]
segment_ids = [torch.tensor(item['segment_ids']) for item in data]
labels = [torch.tensor(item['labels']) for item in data]
ners = [torch.tensor(item['ners']) for item in data]
sentence = [item['sentence'] for item in data]
return (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence)
def get_ACETriData_loader(data, config, shuffle = False, batch_size = None):
dataset = ACETriDataset(data)
if batch_size == None:
batchSize = min(config.batch_size, len(data))
else:
batchSize = min(batch_size, len(data))
ACETriData_loader = DataLoader(
dataset = dataset,
batch_size= batchSize,
shuffle= shuffle,
collate_fn= dataset.collate_fn,
drop_last= False
)
return ACETriData_loader
class ACEPredDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
def collate_fn(self, data):
input_ids = [torch.tensor(item['input_ids']) for item in data]
input_masks = [torch.tensor(item['input_masks']) for item in data]
in_sent = [torch.tensor(item['in_sent']) for item in data]
segment_ids = [torch.tensor(item['segment_ids']) for item in data]
sentence = [item['sentence'] for item in data]
event = [item['event'] for item in data]
return (input_ids, input_masks, in_sent, segment_ids, sentence, event)
def get_ACEPredData_loader(data, config, shuffle = False, batch_size = None):
dataset = ACEPredDataset(data)
if batch_size == None:
batchSize = min(config.batch_size, len(data))
else:
batchSize = min(batch_size, len(data))
ACEPredData_loader = DataLoader(
dataset = dataset,
batch_size= batchSize,
shuffle= shuffle,
collate_fn= dataset.collate_fn,
drop_last= False
)
return ACEPredData_loader
def get_ACEArgData_loader(data, config, shuffle = False, batch_size = None):
dataset = ACEArgDataloader(data)
if batch_size == None:
batchSize = min(config.batch_size, len(data))
else:
batchSize = min(batch_size, len(data))
ACEPredData_loader = DataLoader(
dataset = dataset,
batch_size= batchSize,
shuffle= shuffle,
collate_fn= dataset.collate_fn,
drop_last= False
)
return ACEPredData_loader
class ACEArgDataloader(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
def collate_fn(self, data):
sentence = [item['sentence'] for item in data]
input_ids = [torch.tensor(item['input_ids']) for item in data]
input_masks = [torch.tensor(item['input_masks']) for item in data]
in_sent = [torch.tensor(item['in_sent']) for item in data]
segment_ids = [torch.tensor(item['segment_ids']) for item in data]
args = [torch.tensor(item['args']) for item in data]
args_offset = [item['args_offset'] for item in data]
gold_args = [item['gold_args'] for item in data]
ner = [item['ner'] for item in data]
trigger = [item['trigger'] for item in data]
return (sentence, input_ids, input_masks, in_sent, segment_ids, args, args_offset, gold_args, ner, trigger)
class ACEPredNerDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
def collate_fn(self, data):
input_ids = [torch.tensor(item['input_ids']) for item in data]
input_masks = [torch.tensor(item['input_masks']) for item in data]
in_sent = [torch.tensor(item['in_sent']) for item in data]
segment_ids = [torch.tensor(item['segment_ids']) for item in data]
sentence = [item['sentence'] for item in data]
event = [item['event'] for item in data]
ner = [item['ner'] for item in data]
return (input_ids, input_masks, in_sent, segment_ids, sentence, event, ner)
def get_ACEPredNerData_loader(data, config, shuffle = False, batch_size = None):
dataset = ACEPredNerDataset(data)
if batch_size == None:
batchSize = min(config.batch_size, len(data))
else:
batchSize = min(batch_size, len(data))
ACEPredNerData_loader = DataLoader(
dataset = dataset,
batch_size= batchSize,
shuffle= shuffle,
collate_fn= dataset.collate_fn,
drop_last= False
)
return ACEPredNerData_loader
class ACETriDataloder(Dataset):
def __init__(self, config, i):
self.config = config
self.data_root = config.data_root
#print(config.bert_path, type(config.bert_path))
self.tokenizer = BertTokenizer.from_pretrained(config.bert_path)
self.max_sentence_length = 512
# trigger category vocabulary
self.vocab2index = {}
self.index2vocab = {}
self.vocab2index = json.load(open(self.data_root+'label2id.json', 'r'))
self.vocab2index['None'] = 0
for key, value in self.vocab2index.items():
#value = value - 169
self.index2vocab[value] = key
#self.vocab2index[key] = value
# ner2id
self.ner2id = json.load(open(self.data_root+'ner2id.json', 'r'))
self.ner2id['None'] = 0
self.id2ner = {}
for key, value in self.ner2id.items():
self.id2ner[value] = key
# iter
self.stream_turn = config.stream_turn
self.batch = 0
# data stream
self.train_stream = json.load(open(self.data_root+'train_streams.json', 'r'))
self.id2stream = json.load(open(self.data_root+'id2stream.json', 'r'))
# set seed
self.seed = config.seed
random.seed(self.seed)
np.random.seed(self.seed)
self.shuffle_index = list(range(self.stream_turn))
random.shuffle(self.shuffle_index)
self.shuffle_index = np.argsort(self.shuffle_index)
#self.shuffle_index = PERM[i]
print(self.shuffle_index)
# seen data
self.seen_test_data = []
self.seen_dev_data = []
self.seen_event = []
self.seen_test_args_data = []
self.seen_dev_args_data = []
self.seen_args = []
self.ltlabel = []
# prepare data:
self.train_dataset, self.dev_dataset, self.test_dataset = self.read_data(self.data_root)
# tokenizer:
self.tokenizer = BertTokenizer.from_pretrained(config.bert_path)
if config.argument:
# role2id
self.role2id = json.load(open(self.data_root+'role2id.json', 'r'))
self.role2id['None'] = 0
self.id2role = {}
for key, value in self.role2id.items():
self.id2role[value] = key
# metadata
self.args_num = config.args_num
self.metadata = json.load(open(self.data_root+'metadata.json', 'r'))
self.unseen_metadata = {}
for key, value in self.metadata.items():
new_value = [self.role2id[val] for val in value]
self.metadata[key] = new_value
unseen_args = [i for i in range(self.args_num)]
unseen_args = list(set(unseen_args) - set(new_value) - set([0]))
self.unseen_metadata[key] = unseen_args
self.args_train_dataset, self.args_dev_dataset, self.args_test_dataset = self.read_args_data(self.data_root)
if config.lttest:
self.ltlabel = json.load(open(self.data_root+'lt_label.json', 'r'))
def __iter__(self):
return self
def __len__(self):
return self.stream_turn
def __next__(self):
cur_train_data, cur_test_data, cur_dev_data, current_event = [], [], [], []
if self.batch == self.stream_turn:
self.batch = 0
raise StopIteration()
index = self.shuffle_index[self.batch]
# now is tirgger data
cur_train_data = self.train_dataset[index]
cur_dev_data = self.dev_dataset[index]
cur_test_data = self.test_dataset[index]
current_event = self.train_stream[index]
self.seen_event += current_event
self.batch += 1
final_data = [[] , [] , []]
for i, data in enumerate([cur_train_data, cur_dev_data, cur_test_data]):
for x in data:
final_data[i] += data[x]
tr_data, de_data, cur_te_data = final_data
tr_data = trigger_combine_event([], tr_data)
de_data = trigger_combine_event([], de_data)
cur_te_data = trigger_combine_event([], cur_te_data)
temp_cur = copy.deepcopy(cur_te_data)
temp_dev = copy.deepcopy(de_data)
self.seen_test_data = trigger_combine_event(self.seen_test_data, temp_cur)
self.seen_dev_data = trigger_combine_event(self.seen_dev_data, temp_dev)
if self.config.argument:
# now is args data
cur_args_train_data = self.args_train_dataset[index]
cur_args_dev_data = self.args_dev_dataset[index]
cur_args_test_data = self.args_test_dataset[index]
#current_args = self.args_stream[index]
#self.seen_args = list(set(self.seen_args + current_args))
#unseen_args = [i for i in range(self.args_num)]
#unseen_args = list(set(unseen_args) - set(self.seen_args)- set([0]))
args_final_data = [[] , [] , []]
for i, data in enumerate([cur_args_train_data, cur_args_dev_data, cur_args_test_data]):
for x in data:
args_final_data[i] += data[x]
tr_args_data, de_args_data, cur_args_te_data = args_final_data | tr_args_data = args_combine_event([], tr_args_data) | 1 | 2023-10-17 02:40:04+00:00 | 4k |
IBM/VillanDiffusion | caption_dataset.py | [
{
"identifier": "Log",
"path": "util.py",
"snippet": "class Log:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n \n ... | import io
import json
import os
import pathlib
import random
import shutil
import tempfile
import traceback
import warnings
import jsonlines
import datasets
import numpy as np
import requests
import torch
from random import sample
from typing import Callable, List, Tuple, Union
from functools import lru_cache, partial
from tqdm import tqdm
from datasets import load_dataset, concatenate_datasets, get_dataset_split_names, IterableDataset, load_from_disk
from datasets.dataset_dict import DatasetDict
from matplotlib import pyplot as plt
from torchvision import transforms
from torchvision.transforms import Compose, ToTensor, Lambda, ToPILImage, CenterCrop, Resize
from torchvision.utils import make_grid, save_image
from torch.utils.data import DataLoader, ConcatDataset, Subset, Dataset, IterableDataset
from torchvision.datasets import MNIST, CIFAR10, SVHN, FashionMNIST
from PIL import Image
from joblib import Parallel, delayed
from util import Log, normalize
from diffusers import DDPMScheduler | 2,900 | IMAGE = "image"
IS_CLEAN = "is_clean"
RAW = "raw"
LABEL = "label"
CAPTION = "caption"
RAW_CAPTION = "raw_caption"
CAPTION_AUGMENT_KEY: str = "caption_aug"
# CAPTION_TOKEN = "caption_token"
def __init__(self, name: str, label: int=None, root: str=None,
channel: int=None, image_size: int=None, split: str='[:100%]',
vmin: Union[int, float]=DEFAULT_VMIN, vmax: Union[int, float]=DEFAULT_VMAX,
batch_size: int=512, shuffle: bool=True, num_workers: int=8, force_R_to_0: bool=False, seed: int=0):
self.__root = root
self.__name = name
if label != None and not isinstance(label, list)and not isinstance(label, tuple):
self.__label = [label]
else:
self.__label = label
self.__channel = channel
self.__vmin = vmin
self.__vmax = vmax
self.__batch_size = batch_size
self.__shuffle = shuffle
self.__split = split
self.__dataset = self.__load_dataset(name=name)
self.__set_img_shape(image_size=image_size)
self.__trigger = self.__target = self.__caption_trigger = self.__poison_rate = None
self.__clean_rate = 1
self.__seed = seed
self.__num_workers = num_workers
self.__force_R_to_0 = force_R_to_0
self.__caption_backdoor = CaptionBackdoor()
if root != None:
self.__backdoor = Backdoor(root=root)
# self.__prep_dataset()
def set_poison(self, trigger_type: str, target_type: str, caption_trigger_type: str=None, rand_caption_trig_pos: int=0, target_dx: int=-5, target_dy: int=-3, clean_rate: float=1.0, poison_rate: float=0.2) -> 'DatasetLoader':
if self.__root == None:
raise ValueError("Attribute 'root' is None")
self.__clean_rate = clean_rate
self.__poison_rate = poison_rate
self.__trigger = self.__backdoor.get_trigger(type=trigger_type, channel=self.__channel, image_size=self.__image_size, vmin=self.__vmin, vmax=self.__vmax)
self.__caption_trigger = self.__caption_backdoor.get_trigger(_type=caption_trigger_type)
self.__rand_caption_trig_pos: int = rand_caption_trig_pos
self.__target = self.__backdoor.get_target(type=target_type, trigger=self.__trigger, dx=target_dx, dy=target_dy)
return self
def __load_dataset(self, name: str):
datasets.config.IN_MEMORY_MAX_SIZE = 50 * 2 ** 30
split_method = f'train{self.__split}+test{self.__split}'
if name == DatasetLoader.MNIST:
return load_dataset("mnist", split=split_method)
elif name == DatasetLoader.CIFAR10:
return load_dataset("cifar10", split=split_method)
elif name == DatasetLoader.CELEBA:
return load_dataset("student/celebA", split=f"train{self.__split}")
elif name == DatasetLoader.CELEBA_HQ:
return load_dataset("datasets/celeba_hq_256", split=f"train{self.__split}")
elif name ==DatasetLoader.CELEBA_HQ_DIALOG:
return CelebA_HQ_Dialog(path="datasets/CelebA-Dialog (HQ)").prepare(split=f"train{self.__split}")
elif name == DatasetLoader.LAION_COCO or name == DatasetLoader.LAION_COCO_20K:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg200K.hf")
elif name == DatasetLoader.LAION_COCO_1:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg1.hf")
elif name == DatasetLoader.LAION_COCO_200:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg200.hf")
elif name == DatasetLoader.LAION_COCO_50K:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg50K.hf")
elif name == DatasetLoader.POKEMON_CAPTION:
return load_dataset("lambdalabs/pokemon-blip-captions", split=f"train{self.__split}")
else:
raise NotImplementedError(f"Undefined dataset: {name}")
def __set_img_shape(self, image_size: int) -> None:
# Set channel
if self.__name == self.MNIST:
self.__channel = 1 if self.__channel == None else self.__channel
# self.__vmin = -1
# self.__vmax = 1
self.__cmap = "gray"
elif self.__name == self.CIFAR10 or self.__name == self.CELEBA or self.__name == self.CELEBA_HQ or self.__name == self.LSUN_CHURCH or self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K or self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:
self.__channel = 3 if self.__channel == None else self.__channel
# self.__vmin = -1
# self.__vmax = 1
self.__cmap = None
else:
raise NotImplementedError(f"No dataset named as {self.__name}")
# Set image size
if image_size == None:
if self.__name == self.MNIST:
self.__image_size = 32
elif self.__name == self.CIFAR10:
self.__image_size = 32
elif self.__name == self.CELEBA:
self.__image_size = 64
elif self.__name == self.CELEBA_HQ or self.__name == self.LSUN_CHURCH:
self.__image_size = 256
elif self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K or self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:
self.__image_size = 512
else:
raise NotImplementedError(f"No dataset named as {self.__name}")
else:
self.__image_size = image_size
def __get_transform(self, prev_trans: List=[], next_trans: List=[]):
if self.__channel == 1:
channel_trans = transforms.Grayscale(num_output_channels=1)
elif self.__channel == 3:
channel_trans = transforms.Lambda(lambda x: x.convert("RGB"))
aug_trans = []
if self.__dataset != DatasetLoader.LSUN_CHURCH:
aug_trans = [transforms.RandomHorizontalFlip()]
trans = [channel_trans,
transforms.Resize([self.__image_size, self.__image_size]),
transforms.ToTensor(),
| # %%
"""
Backdoor Poisoned Dataset
"""
# from tmp_parse_dataset import LaionCoco
DEFAULT_VMIN = float(-1.0)
DEFAULT_VMAX = float(1.0)
class DatasetLoader(object):
# Dataset generation mode
MODE_FIXED = "FIXED"
MODE_FLEX = "FLEX"
# Dataset names
MNIST = "MNIST"
CIFAR10 = "CIFAR10"
CELEBA = "CELEBA"
LSUN_CHURCH = "LSUN-CHURCH"
LSUN_BEDROOM = "LSUN-BEDROOM"
CELEBA_HQ = "CELEBA-HQ"
CELEBA_HQ_DIALOG = "CELEBA-HQ-DIALOG"
LAION_COCO = "LAION-COCO"
LAION_COCO_1 = "LAION-COCO-1"
LAION_COCO_20K = "LAION-COCO-20K"
LAION_COCO_200 = "LAION-COCO-200"
LAION_COCO_50K = "LAION-COCO-50K"
POKEMON_CAPTION = "POKEMON-CAPTION"
# Inpaint Type
INPAINT_BOX: str = "INPAINT_BOX"
INPAINT_LINE: str = "INPAINT_LINE"
TRAIN = "train"
TEST = "test"
POISON_IMAGE = "poison_image"
IMAGE = "image"
IS_CLEAN = "is_clean"
RAW = "raw"
LABEL = "label"
CAPTION = "caption"
RAW_CAPTION = "raw_caption"
CAPTION_AUGMENT_KEY: str = "caption_aug"
# CAPTION_TOKEN = "caption_token"
def __init__(self, name: str, label: int=None, root: str=None,
channel: int=None, image_size: int=None, split: str='[:100%]',
vmin: Union[int, float]=DEFAULT_VMIN, vmax: Union[int, float]=DEFAULT_VMAX,
batch_size: int=512, shuffle: bool=True, num_workers: int=8, force_R_to_0: bool=False, seed: int=0):
self.__root = root
self.__name = name
if label != None and not isinstance(label, list)and not isinstance(label, tuple):
self.__label = [label]
else:
self.__label = label
self.__channel = channel
self.__vmin = vmin
self.__vmax = vmax
self.__batch_size = batch_size
self.__shuffle = shuffle
self.__split = split
self.__dataset = self.__load_dataset(name=name)
self.__set_img_shape(image_size=image_size)
self.__trigger = self.__target = self.__caption_trigger = self.__poison_rate = None
self.__clean_rate = 1
self.__seed = seed
self.__num_workers = num_workers
self.__force_R_to_0 = force_R_to_0
self.__caption_backdoor = CaptionBackdoor()
if root != None:
self.__backdoor = Backdoor(root=root)
# self.__prep_dataset()
def set_poison(self, trigger_type: str, target_type: str, caption_trigger_type: str=None, rand_caption_trig_pos: int=0, target_dx: int=-5, target_dy: int=-3, clean_rate: float=1.0, poison_rate: float=0.2) -> 'DatasetLoader':
if self.__root == None:
raise ValueError("Attribute 'root' is None")
self.__clean_rate = clean_rate
self.__poison_rate = poison_rate
self.__trigger = self.__backdoor.get_trigger(type=trigger_type, channel=self.__channel, image_size=self.__image_size, vmin=self.__vmin, vmax=self.__vmax)
self.__caption_trigger = self.__caption_backdoor.get_trigger(_type=caption_trigger_type)
self.__rand_caption_trig_pos: int = rand_caption_trig_pos
self.__target = self.__backdoor.get_target(type=target_type, trigger=self.__trigger, dx=target_dx, dy=target_dy)
return self
def __load_dataset(self, name: str):
datasets.config.IN_MEMORY_MAX_SIZE = 50 * 2 ** 30
split_method = f'train{self.__split}+test{self.__split}'
if name == DatasetLoader.MNIST:
return load_dataset("mnist", split=split_method)
elif name == DatasetLoader.CIFAR10:
return load_dataset("cifar10", split=split_method)
elif name == DatasetLoader.CELEBA:
return load_dataset("student/celebA", split=f"train{self.__split}")
elif name == DatasetLoader.CELEBA_HQ:
return load_dataset("datasets/celeba_hq_256", split=f"train{self.__split}")
elif name ==DatasetLoader.CELEBA_HQ_DIALOG:
return CelebA_HQ_Dialog(path="datasets/CelebA-Dialog (HQ)").prepare(split=f"train{self.__split}")
elif name == DatasetLoader.LAION_COCO or name == DatasetLoader.LAION_COCO_20K:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg200K.hf")
elif name == DatasetLoader.LAION_COCO_1:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg1.hf")
elif name == DatasetLoader.LAION_COCO_200:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg200.hf")
elif name == DatasetLoader.LAION_COCO_50K:
return LaionCoco.load("/work/u2941379/workspace/laion_coco_hg50K.hf")
elif name == DatasetLoader.POKEMON_CAPTION:
return load_dataset("lambdalabs/pokemon-blip-captions", split=f"train{self.__split}")
else:
raise NotImplementedError(f"Undefined dataset: {name}")
def __set_img_shape(self, image_size: int) -> None:
# Set channel
if self.__name == self.MNIST:
self.__channel = 1 if self.__channel == None else self.__channel
# self.__vmin = -1
# self.__vmax = 1
self.__cmap = "gray"
elif self.__name == self.CIFAR10 or self.__name == self.CELEBA or self.__name == self.CELEBA_HQ or self.__name == self.LSUN_CHURCH or self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K or self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:
self.__channel = 3 if self.__channel == None else self.__channel
# self.__vmin = -1
# self.__vmax = 1
self.__cmap = None
else:
raise NotImplementedError(f"No dataset named as {self.__name}")
# Set image size
if image_size == None:
if self.__name == self.MNIST:
self.__image_size = 32
elif self.__name == self.CIFAR10:
self.__image_size = 32
elif self.__name == self.CELEBA:
self.__image_size = 64
elif self.__name == self.CELEBA_HQ or self.__name == self.LSUN_CHURCH:
self.__image_size = 256
elif self.__name == self.LAION_COCO or self.__name == self.LAION_COCO_1 or self.__name == self.LAION_COCO_200 or self.__name == self.LAION_COCO_20K or self.__name == self.LAION_COCO_50K or self.__name == self.POKEMON_CAPTION or self.__name == self.CELEBA_HQ_DIALOG:
self.__image_size = 512
else:
raise NotImplementedError(f"No dataset named as {self.__name}")
else:
self.__image_size = image_size
def __get_transform(self, prev_trans: List=[], next_trans: List=[]):
if self.__channel == 1:
channel_trans = transforms.Grayscale(num_output_channels=1)
elif self.__channel == 3:
channel_trans = transforms.Lambda(lambda x: x.convert("RGB"))
aug_trans = []
if self.__dataset != DatasetLoader.LSUN_CHURCH:
aug_trans = [transforms.RandomHorizontalFlip()]
trans = [channel_trans,
transforms.Resize([self.__image_size, self.__image_size]),
transforms.ToTensor(), | transforms.Lambda(lambda x: normalize(vmin_in=0, vmax_in=1, vmin_out=self.__vmin, vmax_out=self.__vmax, x=x)), | 1 | 2023-10-17 19:57:37+00:00 | 4k |
WHUlwb/Assisted_learning | train_t.py | [
{
"identifier": "Dice_loss",
"path": "loss.py",
"snippet": "def Dice_loss(inputs, target, beta=1, smooth = 1e-5):\r\n # inputs B, C, H, W, and target B, H, W, C. \r\n # There are C dimensions in total, each dimension representing a class.\r\n n, c, h, w = inputs.size()\r\n nt, ht, wt, ct = t... | import torch
import numpy as np
import os
import torch.nn as nn
import metric
import time
from torch.utils.data import DataLoader
from loss import Dice_loss,CE_Loss
from torch.autograd import Variable
from dataset import MyDataset
from config import config
from hrnet.hrnet import HRnet
from torch.cuda.amp import GradScaler as Gradscaler
from torch.cuda.amp import autocast
from tqdm import tqdm | 2,152 | scaler = Gradscaler()
traindd = MyDataset(config.trainroot,is_training=True)
traindata = DataLoader(traindd,batch_size=config.batch_size, shuffle=True)
valdata = DataLoader(MyDataset(config.valroot,is_training=False), num_workers=0, batch_size=config.batch_size, shuffle=False)
net = HRnet(in_channel=3,num_classes=config.classnum,backbone='hrnetv2_w32').cuda()
optimizer = torch.optim.SGD(net.parameters(), lr=config.lr, momentum=0.9, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.95)
iters = len(traindata)
train_size = len(traindata)
val_size = len(valdata)
print('train data size: %04d'%train_size)
print('val data size: %04d'%val_size)
global_Fb = 0
start = time.time()
cls_weights = np.ones([config.classnum], np.float32)
weights = torch.from_numpy(cls_weights)
weights = weights.cuda()
if __name__ == '__main__':
for epoch in range(config.epoch_start,config.n_epochs):
seg_loss_t = 0
kd_loss_t = 0
val_Loss = 0
score = 0
conf_mat_val = 0
conf_mat_tra = 0
loop = tqdm(enumerate(traindata), total = len(traindata))
for i,data in loop:
rgbn,sar,m,seg = data
rgbn = Variable(rgbn).cuda()
sar = Variable(sar).cuda()
m = Variable(m).cuda()
seg = Variable(seg).cuda()
optimizer.zero_grad()
if config.amp:
with autocast():
rgbresult = net(rgbn)
ce = CE_Loss(rgbresult,seg)
| scaler = Gradscaler()
traindd = MyDataset(config.trainroot,is_training=True)
traindata = DataLoader(traindd,batch_size=config.batch_size, shuffle=True)
valdata = DataLoader(MyDataset(config.valroot,is_training=False), num_workers=0, batch_size=config.batch_size, shuffle=False)
net = HRnet(in_channel=3,num_classes=config.classnum,backbone='hrnetv2_w32').cuda()
optimizer = torch.optim.SGD(net.parameters(), lr=config.lr, momentum=0.9, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.95)
iters = len(traindata)
train_size = len(traindata)
val_size = len(valdata)
print('train data size: %04d'%train_size)
print('val data size: %04d'%val_size)
global_Fb = 0
start = time.time()
cls_weights = np.ones([config.classnum], np.float32)
weights = torch.from_numpy(cls_weights)
weights = weights.cuda()
if __name__ == '__main__':
for epoch in range(config.epoch_start,config.n_epochs):
seg_loss_t = 0
kd_loss_t = 0
val_Loss = 0
score = 0
conf_mat_val = 0
conf_mat_tra = 0
loop = tqdm(enumerate(traindata), total = len(traindata))
for i,data in loop:
rgbn,sar,m,seg = data
rgbn = Variable(rgbn).cuda()
sar = Variable(sar).cuda()
m = Variable(m).cuda()
seg = Variable(seg).cuda()
optimizer.zero_grad()
if config.amp:
with autocast():
rgbresult = net(rgbn)
ce = CE_Loss(rgbresult,seg) | dice = Dice_loss(rgbresult,seg) | 0 | 2023-10-17 06:19:02+00:00 | 4k |
dagedarr/telegram-budget | handlers/registration_handler.py | [
{
"identifier": "get_by_id",
"path": "core/crud.py",
"snippet": "async def get_by_id(\n model: ModelType,\n obj_id: int,\n session: AsyncSession\n) -> ModelType:\n \"\"\"\n Получение объекта по ID.\n\n Parameters:\n - model (ModelType): Тип модели SQLAlchemy.\n - obj_id (int): Ид... | from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message
from sqlalchemy.ext.asyncio import AsyncSession
from core.crud import get_by_id, get_or_create, update
from forms import RegistrationForm
from keyboards import set_info_keyboard, universal_keyboard
from models import User
from utils.user_actions import callback_message, make_onboarding_end | 1,742 |
router = Router(name='registration_router')
# ------------------------ REGISTRATION ------------------------
@router.callback_query(F.data == 'registration')
async def registration(callback: CallbackQuery, session: AsyncSession):
"""Регистрация пользователя."""
|
router = Router(name='registration_router')
# ------------------------ REGISTRATION ------------------------
@router.callback_query(F.data == 'registration')
async def registration(callback: CallbackQuery, session: AsyncSession):
"""Регистрация пользователя."""
| await get_or_create( | 1 | 2023-10-23 17:30:24+00:00 | 4k |
nchen909/Pass-Tuning | evaluator/CodeBLEU/calc_code_bleu.py | [
{
"identifier": "bleu",
"path": "evaluator/CodeBLEU/bleu.py",
"snippet": "def sentence_bleu(\r\n references,\r\n hypothesis,\r\n weights=(0.25, 0.25, 0.25, 0.25),\r\n smoothing_function=None,\r\n auto_reweigh=False,\r\n):\r\ndef corpus_bleu(\r\n list_of_references,\r\n hypotheses,\r... | import argparse
import os
from evaluator.CodeBLEU import bleu, weighted_ngram_match, syntax_match, dataflow_match
from utils import get_lang_by_task
| 1,902 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# -*- coding:utf-8 -*-
# import evaluator.CodeBLEU.weighted_ngram_match
# import evaluator.CodeBLEU.syntax_match
# import evaluator.CodeBLEU.dataflow_match
def get_codebleu(refs, hyp, lang, params='0.25,0.25,0.25,0.25',args=None):
if not isinstance(refs, list):
refs = [refs]
alpha, beta, gamma, theta = [float(x) for x in params.split(',')]
# preprocess inputs
pre_references = [[x.strip() for x in open(file, 'r', encoding='utf-8').readlines()] for file in refs]
hypothesis = [x.strip() for x in open(hyp, 'r', encoding='utf-8').readlines()]
for i in range(len(pre_references)):
assert len(hypothesis) == len(pre_references[i])
references = []
for i in range(len(hypothesis)):
ref_for_instance = []
for j in range(len(pre_references)):
ref_for_instance.append(pre_references[j][i])
references.append(ref_for_instance)
assert len(references) == len(pre_references) * len(hypothesis)
# calculate ngram match (BLEU)
tokenized_hyps = [x.split() for x in hypothesis]
tokenized_refs = [[x.split() for x in reference] for reference in references]
ngram_match_score = bleu.corpus_bleu(tokenized_refs, tokenized_hyps)
# calculate weighted ngram match
if args:
keywords_path=args.data_dir+"/../evaluator/CodeBLEU/keywords/"
keywords = [x.strip() for x in open(keywords_path + lang + '.txt', 'r', encoding='utf-8').readlines()]
else:
keywords = [x.strip() for x in open('/data/pretrain-attention/CodePrompt/evaluator/CodeBLEU/keywords/' + lang + '.txt', 'r', encoding='utf-8').readlines()]
def make_weights(reference_tokens, key_word_list):
return {token: 1 if token in key_word_list else 0.2 for token in reference_tokens}
tokenized_refs_with_weights = [[[reference_tokens, make_weights(reference_tokens, keywords)] \
for reference_tokens in reference] for reference in tokenized_refs]
weighted_ngram_match_score = weighted_ngram_match.corpus_bleu(tokenized_refs_with_weights, tokenized_hyps)
# calculate syntax match
syntax_match_score = syntax_match.corpus_syntax_match(references, hypothesis, lang)
# calculate dataflow match
dataflow_match_score = dataflow_match.corpus_dataflow_match(references, hypothesis, lang)
print('ngram match: {0}, weighted ngram match: {1}, syntax_match: {2}, dataflow_match: {3}'. \
format(ngram_match_score, weighted_ngram_match_score, syntax_match_score, dataflow_match_score))
code_bleu_score = alpha * ngram_match_score \
+ beta * weighted_ngram_match_score \
+ gamma * syntax_match_score \
+ theta * dataflow_match_score
return code_bleu_score
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--refs', type=str, nargs='+', required=True,
help='reference files')
parser.add_argument('--hyp', type=str, required=True,
help='hypothesis file')
parser.add_argument('--lang', type=str, required=True,
choices=['java', 'js', 'c_sharp', 'php', 'go', 'python', 'ruby'],
help='programming language')
parser.add_argument('--params', type=str, default='0.25,0.25,0.25,0.25',
help='alpha, beta and gamma')
args = parser.parse_args()
| # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# -*- coding:utf-8 -*-
# import evaluator.CodeBLEU.weighted_ngram_match
# import evaluator.CodeBLEU.syntax_match
# import evaluator.CodeBLEU.dataflow_match
def get_codebleu(refs, hyp, lang, params='0.25,0.25,0.25,0.25',args=None):
if not isinstance(refs, list):
refs = [refs]
alpha, beta, gamma, theta = [float(x) for x in params.split(',')]
# preprocess inputs
pre_references = [[x.strip() for x in open(file, 'r', encoding='utf-8').readlines()] for file in refs]
hypothesis = [x.strip() for x in open(hyp, 'r', encoding='utf-8').readlines()]
for i in range(len(pre_references)):
assert len(hypothesis) == len(pre_references[i])
references = []
for i in range(len(hypothesis)):
ref_for_instance = []
for j in range(len(pre_references)):
ref_for_instance.append(pre_references[j][i])
references.append(ref_for_instance)
assert len(references) == len(pre_references) * len(hypothesis)
# calculate ngram match (BLEU)
tokenized_hyps = [x.split() for x in hypothesis]
tokenized_refs = [[x.split() for x in reference] for reference in references]
ngram_match_score = bleu.corpus_bleu(tokenized_refs, tokenized_hyps)
# calculate weighted ngram match
if args:
keywords_path=args.data_dir+"/../evaluator/CodeBLEU/keywords/"
keywords = [x.strip() for x in open(keywords_path + lang + '.txt', 'r', encoding='utf-8').readlines()]
else:
keywords = [x.strip() for x in open('/data/pretrain-attention/CodePrompt/evaluator/CodeBLEU/keywords/' + lang + '.txt', 'r', encoding='utf-8').readlines()]
def make_weights(reference_tokens, key_word_list):
return {token: 1 if token in key_word_list else 0.2 for token in reference_tokens}
tokenized_refs_with_weights = [[[reference_tokens, make_weights(reference_tokens, keywords)] \
for reference_tokens in reference] for reference in tokenized_refs]
weighted_ngram_match_score = weighted_ngram_match.corpus_bleu(tokenized_refs_with_weights, tokenized_hyps)
# calculate syntax match
syntax_match_score = syntax_match.corpus_syntax_match(references, hypothesis, lang)
# calculate dataflow match
dataflow_match_score = dataflow_match.corpus_dataflow_match(references, hypothesis, lang)
print('ngram match: {0}, weighted ngram match: {1}, syntax_match: {2}, dataflow_match: {3}'. \
format(ngram_match_score, weighted_ngram_match_score, syntax_match_score, dataflow_match_score))
code_bleu_score = alpha * ngram_match_score \
+ beta * weighted_ngram_match_score \
+ gamma * syntax_match_score \
+ theta * dataflow_match_score
return code_bleu_score
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--refs', type=str, nargs='+', required=True,
help='reference files')
parser.add_argument('--hyp', type=str, required=True,
help='hypothesis file')
parser.add_argument('--lang', type=str, required=True,
choices=['java', 'js', 'c_sharp', 'php', 'go', 'python', 'ruby'],
help='programming language')
parser.add_argument('--params', type=str, default='0.25,0.25,0.25,0.25',
help='alpha, beta and gamma')
args = parser.parse_args()
| args.lang = get_lang_by_task(args.task, args.sub_task)
| 4 | 2023-10-20 09:24:44+00:00 | 4k |
openfoodfacts/open-prices | app/tasks.py | [
{
"identifier": "crud",
"path": "app/crud.py",
"snippet": "def get_users_query(filters: ProductFilter | None = None):\ndef get_users(db: Session, filters: ProductFilter | None = None):\ndef get_user(db: Session, user_id: str):\ndef get_user_by_user_id(db: Session, user_id: str):\ndef get_user_by_token(d... | import datetime
import tqdm
from openfoodfacts import DatasetType, Flavor, ProductDataset
from openfoodfacts.types import JSONType
from openfoodfacts.utils import get_logger
from sqlalchemy import or_, select
from sqlalchemy.orm import Session
from app import crud
from app.models import Product
from app.schemas import LocationCreate, PriceFull, ProductCreate, UserCreate
from app.utils import (
OFF_FIELDS,
fetch_location_openstreetmap_details,
fetch_product_openfoodfacts_details,
generate_openfoodfacts_main_image_url,
normalize_product_fields,
) | 2,889 |
logger = get_logger(__name__)
# Users
# ------------------------------------------------------------------------------
def increment_user_price_count(db: Session, user: UserCreate):
crud.increment_user_price_count(db, user=user)
# Products
# ------------------------------------------------------------------------------
def create_price_product(db: Session, price: PriceFull):
# The price may not have a product code, if it's the price of a
# barcode-less product
if price.product_code:
# get or create the corresponding product
product = ProductCreate(code=price.product_code)
db_product, created = crud.get_or_create_product(
db, product=product, init_price_count=1
)
# link the product to the price
crud.link_price_product(db, price=price, product=db_product)
# fetch data from OpenFoodFacts if created
if created:
product_openfoodfacts_details = fetch_product_openfoodfacts_details(
product=db_product
)
if product_openfoodfacts_details:
crud.update_product(
db, product=db_product, update_dict=product_openfoodfacts_details
)
else:
# Increment the price count of the product
crud.increment_product_price_count(db, product=db_product)
def import_product_db(db: Session, batch_size: int = 1000):
"""Import from DB JSONL dump to insert/update product table.
:param db: the session to use
:param batch_size: the number of products to insert/update in a single
transaction, defaults to 1000
"""
logger.info("Launching import_product_db")
existing_codes = set(db.execute(select(Product.code)).scalars())
logger.info("Number of existing codes: %d", len(existing_codes))
dataset = ProductDataset(
dataset_type=DatasetType.jsonl, force_download=True, download_newer=True
)
added_count = 0
updated_count = 0
buffer_len = 0
# the dataset was created after the start of the day, every product updated
# after should be skipped, as we don't know the exact creation time of the
# dump
start_datetime = datetime.datetime.now(tz=datetime.timezone.utc).replace(
hour=0, minute=0, second=0
)
seen_codes = set()
for product in tqdm.tqdm(dataset):
if "code" not in product:
continue
product_code = product["code"]
# Some products are duplicated in the dataset, we skip them
if product_code in seen_codes:
continue
seen_codes.add(product_code)
images: JSONType = product.get("images", {})
last_modified_t = product.get("last_modified_t")
last_modified = (
datetime.datetime.fromtimestamp(last_modified_t, tz=datetime.timezone.utc)
if last_modified_t
else None
)
if last_modified is None:
continue
# Skip products that have been modified today (more recent updates are
# possible)
if last_modified >= start_datetime:
logger.debug("Skipping %s", product_code)
continue
if product_code not in existing_codes:
item = {"code": product_code, "source": Flavor.off}
|
logger = get_logger(__name__)
# Users
# ------------------------------------------------------------------------------
def increment_user_price_count(db: Session, user: UserCreate):
crud.increment_user_price_count(db, user=user)
# Products
# ------------------------------------------------------------------------------
def create_price_product(db: Session, price: PriceFull):
# The price may not have a product code, if it's the price of a
# barcode-less product
if price.product_code:
# get or create the corresponding product
product = ProductCreate(code=price.product_code)
db_product, created = crud.get_or_create_product(
db, product=product, init_price_count=1
)
# link the product to the price
crud.link_price_product(db, price=price, product=db_product)
# fetch data from OpenFoodFacts if created
if created:
product_openfoodfacts_details = fetch_product_openfoodfacts_details(
product=db_product
)
if product_openfoodfacts_details:
crud.update_product(
db, product=db_product, update_dict=product_openfoodfacts_details
)
else:
# Increment the price count of the product
crud.increment_product_price_count(db, product=db_product)
def import_product_db(db: Session, batch_size: int = 1000):
"""Import from DB JSONL dump to insert/update product table.
:param db: the session to use
:param batch_size: the number of products to insert/update in a single
transaction, defaults to 1000
"""
logger.info("Launching import_product_db")
existing_codes = set(db.execute(select(Product.code)).scalars())
logger.info("Number of existing codes: %d", len(existing_codes))
dataset = ProductDataset(
dataset_type=DatasetType.jsonl, force_download=True, download_newer=True
)
added_count = 0
updated_count = 0
buffer_len = 0
# the dataset was created after the start of the day, every product updated
# after should be skipped, as we don't know the exact creation time of the
# dump
start_datetime = datetime.datetime.now(tz=datetime.timezone.utc).replace(
hour=0, minute=0, second=0
)
seen_codes = set()
for product in tqdm.tqdm(dataset):
if "code" not in product:
continue
product_code = product["code"]
# Some products are duplicated in the dataset, we skip them
if product_code in seen_codes:
continue
seen_codes.add(product_code)
images: JSONType = product.get("images", {})
last_modified_t = product.get("last_modified_t")
last_modified = (
datetime.datetime.fromtimestamp(last_modified_t, tz=datetime.timezone.utc)
if last_modified_t
else None
)
if last_modified is None:
continue
# Skip products that have been modified today (more recent updates are
# possible)
if last_modified >= start_datetime:
logger.debug("Skipping %s", product_code)
continue
if product_code not in existing_codes:
item = {"code": product_code, "source": Flavor.off} | for key in OFF_FIELDS: | 6 | 2023-10-21 14:02:15+00:00 | 4k |
krasnoukhov/homeassistant-smart-maic | custom_components/smart_maic/config_flow.py | [
{
"identifier": "DEVICE_NAME",
"path": "custom_components/smart_maic/const.py",
"snippet": "DEVICE_NAME = \"device_name\""
},
{
"identifier": "DEVICE_ID",
"path": "custom_components/smart_maic/const.py",
"snippet": "DEVICE_ID = \"devid\""
},
{
"identifier": "DEVICE_TYPE",
"pa... | import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from typing import Any
from homeassistant import config_entries
from homeassistant.components import mqtt
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import AbortFlow
from .const import (
DEVICE_NAME,
DEVICE_ID,
DEVICE_TYPE,
DOMAIN,
IP_ADDRESS,
PIN,
)
from .smart_maic import SmartMaic
from .coordinator import SmartMaicCoordinator | 1,627 | """Config flow for Smart MAIC integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
USER_SCHEMA = vol.Schema(
{
vol.Required(IP_ADDRESS): cv.string,
vol.Required(PIN): cv.string,
vol.Required(DEVICE_NAME, default="Energy"): cv.string,
}
)
async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]:
"""Validate the user input allows us to connect.
Data has the keys from USER_SCHEMA with values provided by the user.
"""
if not await mqtt.async_wait_for_mqtt_client(hass):
raise AbortFlow("mqtt_unavailable")
smart_maic = SmartMaic(data)
coordinator = SmartMaicCoordinator(smart_maic, hass)
config = await coordinator.async_get_config()
if not config["serv"]:
raise AbortFlow("mqtt_unconfigured")
config = await coordinator.async_set_mqtt_config()
additional = {
DEVICE_ID: config["about"][DEVICE_ID]["value"],
DEVICE_TYPE: config["about"][DEVICE_TYPE]["value"],
}
return {"title": data[DEVICE_NAME], "additional": additional}
| """Config flow for Smart MAIC integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
USER_SCHEMA = vol.Schema(
{
vol.Required(IP_ADDRESS): cv.string,
vol.Required(PIN): cv.string,
vol.Required(DEVICE_NAME, default="Energy"): cv.string,
}
)
async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]:
"""Validate the user input allows us to connect.
Data has the keys from USER_SCHEMA with values provided by the user.
"""
if not await mqtt.async_wait_for_mqtt_client(hass):
raise AbortFlow("mqtt_unavailable")
smart_maic = SmartMaic(data)
coordinator = SmartMaicCoordinator(smart_maic, hass)
config = await coordinator.async_get_config()
if not config["serv"]:
raise AbortFlow("mqtt_unconfigured")
config = await coordinator.async_set_mqtt_config()
additional = {
DEVICE_ID: config["about"][DEVICE_ID]["value"],
DEVICE_TYPE: config["about"][DEVICE_TYPE]["value"],
}
return {"title": data[DEVICE_NAME], "additional": additional}
| class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): | 3 | 2023-10-16 17:24:45+00:00 | 4k |
JoaoPedro9674/django-ledger | django_ledger/models/customer.py | [
{
"identifier": "ContactInfoMixIn",
"path": "django_ledger/models/mixins.py",
"snippet": "class ContactInfoMixIn(models.Model):\n \"\"\"\n Implements a common set of fields used to document contact information.\n\n Attributes\n ----------\n address_1: str\n A string used to documen... | from uuid import uuid4
from django.core.exceptions import ObjectDoesNotExist
from django.db import models, transaction, IntegrityError
from django.db.models import Q, F, QuerySet
from django.utils.translation import gettext_lazy as _
from django_ledger.models.mixins import ContactInfoMixIn, CreateUpdateMixIn, TaxCollectionMixIn
from django_ledger.models.utils import lazy_loader
from django_ledger.settings import DJANGO_LEDGER_DOCUMENT_NUMBER_PADDING, DJANGO_LEDGER_CUSTOMER_NUMBER_PREFIX | 2,326 |
class CustomerModelQueryset(QuerySet):
"""
A custom defined QuerySet for the CustomerModel. This implements multiple methods or queries needed to get a
filtered QuerySet based on the CustomerModel status. For example, we might want to have list of Customers that
are active or hidden. All these separate functions will assist in making such queries and building customized
reports.
"""
def active(self) -> QuerySet:
"""
Active customers can be assigned to new Invoices and show on dropdown menus and views.
Returns
-------
CustomerModelQueryset
A QuerySet of active Customers.
"""
return self.filter(active=True)
def inactive(self) -> QuerySet:
"""
Active customers can be assigned to new Invoices and show on dropdown menus and views.
Marking CustomerModels as inactive can help reduce Database load to populate select inputs and also inactivate
CustomerModels that are not relevant to the Entity anymore. Also, it makes de UI cleaner by not populating
unnecessary choices.
Returns
-------
CustomerModelQueryset
A QuerySet of inactive Customers.
"""
return self.filter(active=False)
def hidden(self) -> QuerySet:
"""
Hidden customers do not show on dropdown menus, but may be used via APIs or any other method that does not
involve the UI.
Returns
-------
CustomerModelQueryset
A QuerySet of hidden Customers.
"""
return self.filter(hidden=True)
def visible(self) -> QuerySet:
"""
Visible customers show on dropdown menus and views. Visible customers are active and not hidden.
Returns
-------
CustomerModelQueryset
A QuerySet of visible Customers.
"""
return self.filter(
Q(hidden=False) & Q(active=True)
)
class CustomerModelManager(models.Manager):
"""
A custom defined CustomerModelManager that will act as an interface to handling the DB queries to the
CustomerModel.
"""
def for_user(self, user_model):
"""
Fetches a QuerySet of BillModels that the UserModel as access to.
May include BillModels from multiple Entities.
The user has access to bills if:
1. Is listed as Manager of Entity.
2. Is the Admin of the Entity.
Parameters
__________
user_model
Logged in and authenticated django UserModel instance.
Examples
________
>>> request_user = request.user
>>> customer_model_qs = CustomerModel.objects.for_user(user_model=request_user)
"""
qs = self.get_queryset()
return qs.filter(
Q(entity__admin=user_model) |
Q(entity__managers__in=[user_model])
)
def for_entity(self, entity_slug, user_model) -> CustomerModelQueryset:
"""
Fetches a QuerySet of CustomerModel associated with a specific EntityModel & UserModel.
May pass an instance of EntityModel or a String representing the EntityModel slug.
Parameters
__________
entity_slug: str or EntityModel
The entity slug or EntityModel used for filtering the QuerySet.
user_model
Logged in and authenticated django UserModel instance.
Examples
________
>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> customer_model_qs = CustomerModel.objects.for_entity(user_model=request_user, entity_slug=slug)
Returns
-------
CustomerModelQueryset
A filtered CustomerModel QuerySet.
"""
qs = self.get_queryset()
| """
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>.
Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
Contributions to this module:
* Miguel Sanda <msanda@arrobalytics.com>
* Pranav P Tulshyan <ptulshyan77@gmail.com>
A Customer refers to the person or entity that buys product and services. When issuing Invoices, a Customer must be
created before it can be assigned to the InvoiceModel. Only customers who are active can be assigned to new Invoices.
"""
class CustomerModelQueryset(QuerySet):
"""
A custom defined QuerySet for the CustomerModel. This implements multiple methods or queries needed to get a
filtered QuerySet based on the CustomerModel status. For example, we might want to have list of Customers that
are active or hidden. All these separate functions will assist in making such queries and building customized
reports.
"""
def active(self) -> QuerySet:
"""
Active customers can be assigned to new Invoices and show on dropdown menus and views.
Returns
-------
CustomerModelQueryset
A QuerySet of active Customers.
"""
return self.filter(active=True)
def inactive(self) -> QuerySet:
"""
Active customers can be assigned to new Invoices and show on dropdown menus and views.
Marking CustomerModels as inactive can help reduce Database load to populate select inputs and also inactivate
CustomerModels that are not relevant to the Entity anymore. Also, it makes de UI cleaner by not populating
unnecessary choices.
Returns
-------
CustomerModelQueryset
A QuerySet of inactive Customers.
"""
return self.filter(active=False)
def hidden(self) -> QuerySet:
"""
Hidden customers do not show on dropdown menus, but may be used via APIs or any other method that does not
involve the UI.
Returns
-------
CustomerModelQueryset
A QuerySet of hidden Customers.
"""
return self.filter(hidden=True)
def visible(self) -> QuerySet:
"""
Visible customers show on dropdown menus and views. Visible customers are active and not hidden.
Returns
-------
CustomerModelQueryset
A QuerySet of visible Customers.
"""
return self.filter(
Q(hidden=False) & Q(active=True)
)
class CustomerModelManager(models.Manager):
"""
A custom defined CustomerModelManager that will act as an interface to handling the DB queries to the
CustomerModel.
"""
def for_user(self, user_model):
"""
Fetches a QuerySet of BillModels that the UserModel as access to.
May include BillModels from multiple Entities.
The user has access to bills if:
1. Is listed as Manager of Entity.
2. Is the Admin of the Entity.
Parameters
__________
user_model
Logged in and authenticated django UserModel instance.
Examples
________
>>> request_user = request.user
>>> customer_model_qs = CustomerModel.objects.for_user(user_model=request_user)
"""
qs = self.get_queryset()
return qs.filter(
Q(entity__admin=user_model) |
Q(entity__managers__in=[user_model])
)
def for_entity(self, entity_slug, user_model) -> CustomerModelQueryset:
"""
Fetches a QuerySet of CustomerModel associated with a specific EntityModel & UserModel.
May pass an instance of EntityModel or a String representing the EntityModel slug.
Parameters
__________
entity_slug: str or EntityModel
The entity slug or EntityModel used for filtering the QuerySet.
user_model
Logged in and authenticated django UserModel instance.
Examples
________
>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> customer_model_qs = CustomerModel.objects.for_entity(user_model=request_user, entity_slug=slug)
Returns
-------
CustomerModelQueryset
A filtered CustomerModel QuerySet.
"""
qs = self.get_queryset()
| if isinstance(entity_slug, lazy_loader.get_entity_model()): | 3 | 2023-10-20 01:07:20+00:00 | 4k |
HLTCHKUST/InstructAlign | run_t2t_finetuning.py | [
{
"identifier": "load_flores_datasets",
"path": "data_utils.py",
"snippet": "def load_flores_datasets(pivot_langs=['eng_Latn'], augmentation='multilingual', num_train_ratio=1.0):\n def inject_lang(row, lang1, lang2):\n row['lang1'] = lang_map[lang1]\n row['lang2'] = lang_map[lang2]\n ... | import logging
import os
import sys
import random
import numpy as np
import pandas as pd
import torch
import transformers
import datasets
from dataclasses import dataclass, field
from typing import Optional
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoModelForCausalLM,
AutoTokenizer,
DataCollatorWithPadding,
DataCollatorForLanguageModeling,
DataCollatorForSeq2Seq,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from peft import prepare_model_for_int8_training
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils.versions import require_version
from data_utils import load_flores_datasets, load_rehearsal_dataset
from augmentation_utils import do_augment
from prompt_utils import prompt_monolingual, prompt_translation, prompt_xss, prompt_bilingual | 3,399 | "than this will be truncated, sequences shorter will be padded."
)
},
)
max_target_length: Optional[int] = field(
default=128,
metadata={
"help": (
"The maximum total sequence length for target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
},
)
pad_to_max_length: bool = field(
default=False,
metadata={
"help": (
"Whether to pad all samples to model maximum sentence length. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
"efficient on GPU but very bad for TPU."
)
},
)
num_beams: Optional[int] = field(
default=1,
metadata={
"help": (
"Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
"which is used during ``evaluate`` and ``predict``."
)
},
)
ignore_pad_token_for_loss: bool = field(
default=True,
metadata={
"help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
},
)
augmentation_type: str = field(
default='monolingual',
metadata={
"help": "Mode for data augmentation (monolingual / translation / bilingual / random)."
},
)
continual_type: str = field(
default=None,
metadata={
"help": "Mode for continual learning method (rehearsal / None)."
},
)
continual_size: int = field(
default=100,
metadata={
"help": "Mode for data (monolingual / translation / bilingual / random)."
},
)
num_train_ratio: float = field(
default=1.0,
metadata={
"help": "Number of samples to be taken from FLORES"
},
)
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
# Detecting last checkpoint.
last_checkpoint = None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome."
)
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
# Set seed before initializing model.
set_seed(training_args.seed)
# Load the datasets
| #!/usr/bin/env python
# coding=utf-8
# Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Fine-tuning the library models for sequence to sequence.
"""
# You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
logger = logging.getLogger(__name__)
@dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
config_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
)
tokenizer_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
)
cache_dir: Optional[str] = field(
default=None,
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
)
use_fast_tokenizer: bool = field(
default=True,
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
)
model_revision: str = field(
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
use_auth_token: bool = field(
default=False,
metadata={
"help": (
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
"with private models)."
)
},
)
@dataclass
class DataTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
)
overwrite_cache: bool = field(
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
)
preprocessing_num_workers: Optional[int] = field(
default=None,
metadata={"help": "The number of processes to use for the preprocessing."},
)
max_source_length: Optional[int] = field(
default=128,
metadata={
"help": (
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
},
)
max_target_length: Optional[int] = field(
default=128,
metadata={
"help": (
"The maximum total sequence length for target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
},
)
pad_to_max_length: bool = field(
default=False,
metadata={
"help": (
"Whether to pad all samples to model maximum sentence length. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
"efficient on GPU but very bad for TPU."
)
},
)
num_beams: Optional[int] = field(
default=1,
metadata={
"help": (
"Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
"which is used during ``evaluate`` and ``predict``."
)
},
)
ignore_pad_token_for_loss: bool = field(
default=True,
metadata={
"help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
},
)
augmentation_type: str = field(
default='monolingual',
metadata={
"help": "Mode for data augmentation (monolingual / translation / bilingual / random)."
},
)
continual_type: str = field(
default=None,
metadata={
"help": "Mode for continual learning method (rehearsal / None)."
},
)
continual_size: int = field(
default=100,
metadata={
"help": "Mode for data (monolingual / translation / bilingual / random)."
},
)
num_train_ratio: float = field(
default=1.0,
metadata={
"help": "Number of samples to be taken from FLORES"
},
)
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
# Detecting last checkpoint.
last_checkpoint = None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome."
)
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
# Set seed before initializing model.
set_seed(training_args.seed)
# Load the datasets | raw_datasets = load_flores_datasets(pivot_langs=['eng_Latn'], augmentation=data_args.augmentation_type, num_train_ratio=data_args.num_train_ratio) | 0 | 2023-10-24 07:46:05+00:00 | 4k |
acolas1/KGSimple | eval_KGSimp/eval_baselines.py | [
{
"identifier": "args",
"path": "cli.py",
"snippet": ""
},
{
"identifier": "SaliencyBERTScore",
"path": "scoring/saliency_scorer.py",
"snippet": "class SaliencyBERTScore:\n def __init__(self, lmscorer = \"bertscore\", lang=\"en\"):\n self.bertscore = evaluate.load(lmscorer)\n ... | import os
import sys
import logging
import random
import numpy as np
import torch
import pandas as pd
import stanza
import sacrebleu.tokenizers.tokenizer_13a as tok
from ast import literal_eval
from eval_utils import *
from eval_batched import *
from cli import args
from scoring.saliency_scorer import SaliencyBERTScore
from scoring.fluency_scorer import FluencyScorer
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import pipeline
| 1,745 | #### read in result files, format, run eval functions
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# setting path
sys.path.append('../../')
sys.path.append('/blue/daisyw/acolas1/KGSimplification/')
def eval():
| #### read in result files, format, run eval functions
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# setting path
sys.path.append('../../')
sys.path.append('/blue/daisyw/acolas1/KGSimplification/')
def eval():
| eval_mod = args.eval_mod ## model + eval type
| 0 | 2023-10-24 13:24:23+00:00 | 4k |
yuanxy92/DANTE | train_electric_optical_kernel.py | [
{
"identifier": "train_complex",
"path": "optical_layer.py",
"snippet": "def train_complex(label_nopad, folder_prefix, epoch, whole_dim, phase_dim, wave_lambda, focal_length, pixel_size, compute_loss_region, factor):\n image = np.zeros((1, whole_dim, whole_dim))\n image[0, whole_dim//2, whole_dim/... | import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import os
import os.path
import time
import torch
import math
import platform
import torchsummary
import logging
import math
from optical_layer import train_complex
from utils import padding, tile_kernels
from importlib.machinery import SourceFileLoader | 2,523 | elif platform.system().lower() == 'linux':
server_dir = '/data/xiaoyun/Elec-Opt-D2NN/'
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
device_cpu = torch.device('cpu')
device_gpu = torch.device('cuda:0')
model_idx = '3bs'
whole_dim = 2000
phase_dim = 1200
wave_lambda = 532e-9
focal_length = 14.5e-2
pixel_size = 8e-6
factor = 100
train_epoch = 12000
dataset_input_shape = (3, 32, 32) # for cifar-10 and imagenet32 dataset
fc_in = 324
fc_out = 10
################################################################################
########## fashionmnist and cifar-10 ONN #################
################################################################################
# load network
if model_idx == '3bs':
# Three layers best model
folder_to_fit = server_dir + 'results_nc/cifar_3layers_best_0713_091820'
test_epoch = 190
foo = SourceFileLoader(
"a", folder_to_fit+"/electric_network.py").load_module()
CNN = foo.CNN_complex_3layers_best_small
################################################################################
########## Load ONN, start to fit ############
################################################################################
with torch.no_grad():
net = CNN(fc_in, fc_out)
net.load_state_dict(torch.load(
folder_to_fit + '/models/%03d.pth' % test_epoch))
net.eval()
net_gpu = net.to(device_gpu)
# net = net.to(device_cpu)
netsummary = torchsummary.summary(net_gpu, dataset_input_shape)
now = time.strftime('%m%d_%H%M%S', time.localtime(time.time()))
logging_file = folder_to_fit+"/Elec_to_optical_fitting__" + now + ".log"
if os.path.isfile(logging_file):
os.remove(logging_file)
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[
logging.FileHandler(logging_file),
logging.StreamHandler()
])
layer_idx = 0
for layer_key, layer_value in netsummary.items():
if layer_key.startswith('ComplexConv2d'):
# get parameters of layers
num_group = layer_value['groups']
num_padding = layer_value['padding']
output_shape_total = layer_value['output_shape']
input_shape_total = layer_value['input_shape']
complex_kernel_total = layer_value['complex_kernel'].cpu().detach()
w = layer_value['w'].cpu().detach()
for group_idx in range(num_group):
# re-calculate shape
input_shape = (input_shape_total[0], int(
input_shape_total[1] / num_group), input_shape_total[2], input_shape_total[3])
output_shape = (output_shape_total[0], int(
output_shape_total[1] / num_group), output_shape_total[2], output_shape_total[3])
kernel_out_step = int(
complex_kernel_total.shape[0] / num_group)
complex_kernel = complex_kernel_total[group_idx * kernel_out_step:(
group_idx + 1) * kernel_out_step, :, :, :]
# get required size and padding kernel size
kernel_shape = complex_kernel.shape
imgsize = input_shape[2] + 2*num_padding
psf = padding(complex_kernel, imgsize)
psf_shape = psf.shape
print(input_shape, kernel_shape, psf_shape)
# get input and output channels
input_ch_num = input_shape[1]
output_ch_num = output_shape[1]
input_ch_len = int(math.ceil(math.sqrt(input_ch_num)))
output_ch_len = int(math.ceil(math.sqrt(output_ch_num)))
# padding kernel channels to square
if input_ch_len ** 2 - psf_shape[1] > 0:
psf_padding = torch.zeros(
psf_shape[0], input_ch_len ** 2 - psf_shape[1], psf_shape[2], psf_shape[3])
psf = torch.cat((psf, psf_padding), dim=1)
psf_shape = psf.shape
if output_ch_len ** 2 - psf_shape[0] > 0:
psf_padding = torch.zeros(
output_ch_len ** 2 - psf_shape[0], psf_shape[1], psf_shape[2], psf_shape[3])
psf = torch.cat((psf, psf_padding), dim=0)
psf_shape = psf.shape
# tile kernels
psf = torch.transpose(psf, 0, 1)
psf = tile_kernels(psf, input_ch_len, input_ch_len)
psf_to_fit = tile_kernels(
psf, output_ch_len, output_ch_len).unsqueeze(0).detach()
psf_fitting_size = psf_to_fit.shape[1] + psf.shape[1]
# rounded_size = int(math.ceil(psf_fitting_size / 50) * 50)
rounded_size = psf_fitting_size
# print layer fit
print(
f'Fitting layer {layer_key}, group {group_idx}, psf {tuple(psf_to_fit.shape)}, fitting size {psf_fitting_size}, rounded size {rounded_size}')
# start to fit
compute_loss_region = psf_fitting_size # rounded_size
out_layer_name = layer_key + '_group_%d_' % group_idx
folder_prefix = folder_to_fit + '/' + out_layer_name
print('Fitting layer %s group %d ...' % (layer_key, group_idx))
with torch.enable_grad():
| # -*- coding: utf-8 -*-
########################################################################
if platform.system().lower() == 'windows':
server_dir = './'
# os.environ["CUDA_VISIBLE_DEVICES"] = '0'
elif platform.system().lower() == 'linux':
server_dir = '/data/xiaoyun/Elec-Opt-D2NN/'
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
device_cpu = torch.device('cpu')
device_gpu = torch.device('cuda:0')
model_idx = '3bs'
whole_dim = 2000
phase_dim = 1200
wave_lambda = 532e-9
focal_length = 14.5e-2
pixel_size = 8e-6
factor = 100
train_epoch = 12000
dataset_input_shape = (3, 32, 32) # for cifar-10 and imagenet32 dataset
fc_in = 324
fc_out = 10
################################################################################
########## fashionmnist and cifar-10 ONN #################
################################################################################
# load network
if model_idx == '3bs':
# Three layers best model
folder_to_fit = server_dir + 'results_nc/cifar_3layers_best_0713_091820'
test_epoch = 190
foo = SourceFileLoader(
"a", folder_to_fit+"/electric_network.py").load_module()
CNN = foo.CNN_complex_3layers_best_small
################################################################################
########## Load ONN, start to fit ############
################################################################################
with torch.no_grad():
net = CNN(fc_in, fc_out)
net.load_state_dict(torch.load(
folder_to_fit + '/models/%03d.pth' % test_epoch))
net.eval()
net_gpu = net.to(device_gpu)
# net = net.to(device_cpu)
netsummary = torchsummary.summary(net_gpu, dataset_input_shape)
now = time.strftime('%m%d_%H%M%S', time.localtime(time.time()))
logging_file = folder_to_fit+"/Elec_to_optical_fitting__" + now + ".log"
if os.path.isfile(logging_file):
os.remove(logging_file)
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[
logging.FileHandler(logging_file),
logging.StreamHandler()
])
layer_idx = 0
for layer_key, layer_value in netsummary.items():
if layer_key.startswith('ComplexConv2d'):
# get parameters of layers
num_group = layer_value['groups']
num_padding = layer_value['padding']
output_shape_total = layer_value['output_shape']
input_shape_total = layer_value['input_shape']
complex_kernel_total = layer_value['complex_kernel'].cpu().detach()
w = layer_value['w'].cpu().detach()
for group_idx in range(num_group):
# re-calculate shape
input_shape = (input_shape_total[0], int(
input_shape_total[1] / num_group), input_shape_total[2], input_shape_total[3])
output_shape = (output_shape_total[0], int(
output_shape_total[1] / num_group), output_shape_total[2], output_shape_total[3])
kernel_out_step = int(
complex_kernel_total.shape[0] / num_group)
complex_kernel = complex_kernel_total[group_idx * kernel_out_step:(
group_idx + 1) * kernel_out_step, :, :, :]
# get required size and padding kernel size
kernel_shape = complex_kernel.shape
imgsize = input_shape[2] + 2*num_padding
psf = padding(complex_kernel, imgsize)
psf_shape = psf.shape
print(input_shape, kernel_shape, psf_shape)
# get input and output channels
input_ch_num = input_shape[1]
output_ch_num = output_shape[1]
input_ch_len = int(math.ceil(math.sqrt(input_ch_num)))
output_ch_len = int(math.ceil(math.sqrt(output_ch_num)))
# padding kernel channels to square
if input_ch_len ** 2 - psf_shape[1] > 0:
psf_padding = torch.zeros(
psf_shape[0], input_ch_len ** 2 - psf_shape[1], psf_shape[2], psf_shape[3])
psf = torch.cat((psf, psf_padding), dim=1)
psf_shape = psf.shape
if output_ch_len ** 2 - psf_shape[0] > 0:
psf_padding = torch.zeros(
output_ch_len ** 2 - psf_shape[0], psf_shape[1], psf_shape[2], psf_shape[3])
psf = torch.cat((psf, psf_padding), dim=0)
psf_shape = psf.shape
# tile kernels
psf = torch.transpose(psf, 0, 1)
psf = tile_kernels(psf, input_ch_len, input_ch_len)
psf_to_fit = tile_kernels(
psf, output_ch_len, output_ch_len).unsqueeze(0).detach()
psf_fitting_size = psf_to_fit.shape[1] + psf.shape[1]
# rounded_size = int(math.ceil(psf_fitting_size / 50) * 50)
rounded_size = psf_fitting_size
# print layer fit
print(
f'Fitting layer {layer_key}, group {group_idx}, psf {tuple(psf_to_fit.shape)}, fitting size {psf_fitting_size}, rounded size {rounded_size}')
# start to fit
compute_loss_region = psf_fitting_size # rounded_size
out_layer_name = layer_key + '_group_%d_' % group_idx
folder_prefix = folder_to_fit + '/' + out_layer_name
print('Fitting layer %s group %d ...' % (layer_key, group_idx))
with torch.enable_grad(): | folder_fitting, loss = train_complex(psf_to_fit, folder_prefix, train_epoch, whole_dim, phase_dim, wave_lambda, focal_length, pixel_size, compute_loss_region, factor) | 0 | 2023-10-19 10:42:47+00:00 | 4k |
CAMeL-Lab/camel_parser | src/data_preparation.py | [
{
"identifier": "ConllParams",
"path": "src/classes.py",
"snippet": "class ConllParams:\n file_path: str\n parse_model_path: str\n \n def __iter__(self):\n return iter(astuple(self))"
},
{
"identifier": "TextParams",
"path": "src/classes.py",
"snippet": "class TextPara... | import re
import pandas as pd
from typing import List, Union
from camel_tools.disambig.common import DisambiguatedWord
from src.classes import ConllParams, TextParams, PreprocessedTextParams, TokenizedParams, TokenizedTaggedParams
from src.dependency_parser.biaff_parser import parse_conll, parse_text_tuples
from src.initialize_disambiguator.disambiguator_interface import get_disambiguator
from src.parse_disambiguation.disambiguation_analysis import to_sentence_analysis_list
from src.parse_disambiguation.feature_extraction import to_conll_fields_list
from src.utils.text_cleaner import clean_lines, split_lines_words
from src.logger import log | 2,083 |
FileTypeParams = Union[ConllParams, TextParams, PreprocessedTextParams, TokenizedParams, TokenizedTaggedParams]
def get_feats_from_text_tuples(text_tuples: List[List[tuple]]) -> List[List[str]]:
"""Extract the FEATS columns from the unparsed data.
FEATS will exist only for text and pre-processed text inputs.
Args:
text_tuples (List[List[tuple]]): unparsed data
Returns:
List[List[str]]: the FEATS column (or _ if it does not exist)
"""
try:
return [[col_items[5] for col_items in tup_list] for tup_list in text_tuples]
except Exception as e:
print(e)
print('Not enough elements in tuple.')
def add_feats(text_tuples: List[List[tuple]], text_feats: List[List[str]]) -> List[List[tuple]]:
"""Add FEATS data to the text tuples.
The parent list (text_tuples) is a list of sentences.
Each sentence is a list of tuples.
Each tuple represents a token.
Args:
text_tuples (List[List[tuple]]): list of list of tuples
text_feats (List[List[str]]): list of list of FEATS
Returns:
List[List[tuple]]: text_tuples but with the FEATS column filled
"""
text_tuples_with_feats = []
for sentence_tuples, sentence_feats in zip(text_tuples, text_feats):
# get first 5 and last 4 items from parsed tuple using lists, and add features.
# Convert the list of fields to a tuple
merged_tuples = [
tuple(list(token_tuple[:5]) + [token_feats] + list(token_tuple[6:]))
for token_tuple, token_feats in zip(sentence_tuples, sentence_feats)
]
text_tuples_with_feats.append(merged_tuples)
return text_tuples_with_feats
def string_to_tuple_list(string_of_tuples: str) -> List[tuple[str, str]]:
"""Take a string of space-separated tuples and convert it to a tuple list.
Example input: '(جامعة, NOM) (نيويورك, PROP)'
Example output: [(جامعة, NOM), (نيويورك, PROP)]
Args:
string_of_tuples (str): string of tuples
Returns:
List(tuple[str, str]): list of token-pos tuple pairs
"""
sentence_tuples = []
# split on space, and using positive lookbehind and lookahead
# to detect parentheses around the space
for tup in re.split(r'(?<=\)) (?=\()', string_of_tuples.strip()):
# tup = (جامعة, NOM)
tup_items = tup[1:-1] # removes parens
form = (','.join(tup_items.split(',')[:-1])).strip() # account for comma tokens
pos = (tup_items.split(',')[-1]).strip()
sentence_tuples.append((form, pos))
return sentence_tuples
def get_tree_tokens(tok_pos_tuples):
sentences = []
for sentence_tuples in tok_pos_tuples:
sentence = ' '.join([tok_pos_tuple[0] for tok_pos_tuple in sentence_tuples])
sentences.append(sentence)
return sentences
def handle_conll(file_type_params):
file_path, parse_model_path = file_type_params
# pass the path to the text file and the model path and name, and get the tuples
return parse_conll(file_path, parse_model=parse_model_path)
def handle_preprocessed_text(file_type_params):
lines, _, disambiguator_param, clitic_feats_df, tagset, morphology_db_type = file_type_params
|
FileTypeParams = Union[ConllParams, TextParams, PreprocessedTextParams, TokenizedParams, TokenizedTaggedParams]
def get_feats_from_text_tuples(text_tuples: List[List[tuple]]) -> List[List[str]]:
"""Extract the FEATS columns from the unparsed data.
FEATS will exist only for text and pre-processed text inputs.
Args:
text_tuples (List[List[tuple]]): unparsed data
Returns:
List[List[str]]: the FEATS column (or _ if it does not exist)
"""
try:
return [[col_items[5] for col_items in tup_list] for tup_list in text_tuples]
except Exception as e:
print(e)
print('Not enough elements in tuple.')
def add_feats(text_tuples: List[List[tuple]], text_feats: List[List[str]]) -> List[List[tuple]]:
"""Add FEATS data to the text tuples.
The parent list (text_tuples) is a list of sentences.
Each sentence is a list of tuples.
Each tuple represents a token.
Args:
text_tuples (List[List[tuple]]): list of list of tuples
text_feats (List[List[str]]): list of list of FEATS
Returns:
List[List[tuple]]: text_tuples but with the FEATS column filled
"""
text_tuples_with_feats = []
for sentence_tuples, sentence_feats in zip(text_tuples, text_feats):
# get first 5 and last 4 items from parsed tuple using lists, and add features.
# Convert the list of fields to a tuple
merged_tuples = [
tuple(list(token_tuple[:5]) + [token_feats] + list(token_tuple[6:]))
for token_tuple, token_feats in zip(sentence_tuples, sentence_feats)
]
text_tuples_with_feats.append(merged_tuples)
return text_tuples_with_feats
def string_to_tuple_list(string_of_tuples: str) -> List[tuple[str, str]]:
"""Take a string of space-separated tuples and convert it to a tuple list.
Example input: '(جامعة, NOM) (نيويورك, PROP)'
Example output: [(جامعة, NOM), (نيويورك, PROP)]
Args:
string_of_tuples (str): string of tuples
Returns:
List(tuple[str, str]): list of token-pos tuple pairs
"""
sentence_tuples = []
# split on space, and using positive lookbehind and lookahead
# to detect parentheses around the space
for tup in re.split(r'(?<=\)) (?=\()', string_of_tuples.strip()):
# tup = (جامعة, NOM)
tup_items = tup[1:-1] # removes parens
form = (','.join(tup_items.split(',')[:-1])).strip() # account for comma tokens
pos = (tup_items.split(',')[-1]).strip()
sentence_tuples.append((form, pos))
return sentence_tuples
def get_tree_tokens(tok_pos_tuples):
sentences = []
for sentence_tuples in tok_pos_tuples:
sentence = ' '.join([tok_pos_tuple[0] for tok_pos_tuple in sentence_tuples])
sentences.append(sentence)
return sentences
def handle_conll(file_type_params):
file_path, parse_model_path = file_type_params
# pass the path to the text file and the model path and name, and get the tuples
return parse_conll(file_path, parse_model=parse_model_path)
def handle_preprocessed_text(file_type_params):
lines, _, disambiguator_param, clitic_feats_df, tagset, morphology_db_type = file_type_params
| token_lines = split_lines_words(lines) | 11 | 2023-10-21 10:39:28+00:00 | 4k |
aiueola/neurips2023-future-dependent-ope | src/ope/value_based.py | [
{
"identifier": "DiscreteStateLSTMVfunction",
"path": "src/ope/v_func.py",
"snippet": "class DiscreteStateLSTMVfunction(nn.Module):\n def __init__(\n self,\n n_states: int = 500,\n n_actions: int = 6,\n memory_length: int = 0,\n future_length: int = 0,\n lstm... | from dataclasses import dataclass
from typing import Tuple, Optional, Union
from torch import optim
from sklearn.utils import check_random_state
from policy.policy import BasePolicy
from .v_func import DiscreteStateLSTMVfunction, ContinuousStateLSTMVfunction
from .base import BaseNeuralValueBasedOffPolicyEstimator
from utils import to_tensor
import torch
import numpy as np
import matplotlib.pyplot as plt | 3,512 | """Value-Based Estimator."""
@dataclass
class NeuralFutureDependentValueBasedOPE(BaseNeuralValueBasedOffPolicyEstimator):
behavior_policy: BasePolicy
evaluation_policy: BasePolicy
| """Value-Based Estimator."""
@dataclass
class NeuralFutureDependentValueBasedOPE(BaseNeuralValueBasedOffPolicyEstimator):
behavior_policy: BasePolicy
evaluation_policy: BasePolicy | v_function: Union[DiscreteStateLSTMVfunction, ContinuousStateLSTMVfunction] | 0 | 2023-10-24 06:09:37+00:00 | 4k |
JerBouma/FinancePortfolio | financeportfolio/portfolio_controller.py | [
{
"identifier": "excel_model",
"path": "financeportfolio/excel_model.py",
"snippet": "def create_portfolio_performance_excel_report(\n writer: pd.ExcelWriter, dataset: pd.DataFrame, sheet_name: str, currency: str = \"$\"\n):\ndef create_transactions_performance_excel_report(\n writer: pd.ExcelWrit... | import pandas as pd
from financetoolkit import Toolkit
from financeportfolio import excel_model, helpers, portfolio_model
| 3,123 |
Returns:
DataFrame: A DataFrame containing transaction performance metrics.
Raises:
ValueError: If an invalid or unsupported period_string is provided.
"""
if self._daily_historical_data.empty:
try:
self.collect_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect historical data: {error}"
) from error
if self._daily_benchmark_data.empty:
try:
self.collect_benchmark_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect benchmark historical data: {error}"
) from error
if not period:
raise ValueError(
"Please provide a period. This can be 'yearly', 'quarterly', 'monthly', 'weekly', or 'daily'"
)
period_string = period.lower()
if period_string == "yearly":
historical_dataset = self._yearly_historical_data["Adj Close"]
benchmark_dataset = self._yearly_benchmark_data["Adj Close"]
period_symbol = "Y"
elif period_string == "quarterly":
historical_dataset = self._quarterly_historical_data["Adj Close"]
benchmark_dataset = self._quarterly_benchmark_data["Adj Close"]
period_symbol = "Q"
elif period_string == "monthly":
historical_dataset = self._monthly_historical_data["Adj Close"]
benchmark_dataset = self._monthly_benchmark_data["Adj Close"]
period_symbol = "M"
elif period_string == "weekly":
historical_dataset = self._weekly_historical_data["Adj Close"]
benchmark_dataset = self._weekly_benchmark_data["Adj Close"]
period_symbol = "W"
elif period_string == "daily":
historical_dataset = self._daily_historical_data["Adj Close"]
benchmark_dataset = self._daily_benchmark_data["Adj Close"]
period_symbol = "D"
else:
raise ValueError(
"Please provide a valid period. This can be "
"'yearly', 'quarterly', 'monthly', 'weekly', "
"or 'daily'"
)
try:
self._transactions_performance = (
portfolio_model.create_transactions_performance(
portfolio_dataset=self._portfolio_dataset,
ticker_column=self._ticker_column,
date_column=self._date_column,
volume_column=self._volume_column,
price_column=self._price_column,
costs_column=self._costs_column,
period_prices=historical_dataset,
period_string=period_symbol,
original_ticker_combinations=self._original_ticker_combinations,
benchmark_per_ticker=self._benchmark_tickers,
benchmark_specific_prices=self._benchmark_specific_prices,
benchmark_period_prices=benchmark_dataset,
)
)
except ValueError as error:
raise ValueError(
f"Failed to create transaction performance metrics: {error}"
) from error
return self._transactions_performance
def create_excel_report(
self,
excel_file_name: str | None = None,
currency: str | None = None,
):
"""
Create an Excel report file with specified data sheets.
This function creates an Excel file with multiple data sheets, including monthly,
quarterly, and yearly overviews if the corresponding data is available. The data
sheets are populated with dataframes provided by the class attributes
_monthly_overview, _quarterly_overview, and _yearly_overview.
The Excel file is saved with the specified name or the default name from the
configuration. The date and datetime formats in the Excel file are set to
"yyyy-mm-dd" for consistency.
Args:
excel_file_name (str | None): The name of the Excel file to be created. If None,
the default file name specified in the configuration will be used.
currency (str | None): The currency to be used for formatting in the Excel file.
If None, the default currency from the configuration will be used.
"""
excel_file_name = (
excel_file_name if excel_file_name else self._cfg["excel"]["file_name"]
)
currency = currency if currency else self._cfg["excel"]["currency"]
writer = pd.ExcelWriter(
excel_file_name,
engine="xlsxwriter",
date_format="yyyy-mm-dd",
datetime_format="yyyy-mm-dd",
)
try:
# Try to create and save Portfolio Overview
self._portfolio_overview = self.get_portfolio_overview()
| """Portfolio Module"""
# pylint: disable=too-many-instance-attributes,abstract-class-instantiated,
# pylint: disable=too-few-public-methods,protected-access,too-many-lines
class Portfolio:
"""
A class for managing and analyzing your portfolio.
This class provides functionality for loading, preprocessing, categorizing, and analyzing
cash flow data based on a specified configuration file. It offers methods to read and format
the dataset, apply cost or income indicators, categorize transactions, and create periodical
cash flow overviews.
Parameters:
configuration_file (str): The file path to the configuration file in YAML format. The
configuration file should define various settings and columns used in cash flow
analysis.
Attributes:
_configuration_file (str): The file path to the configuration file.
_cash_flow_dataset (pd.DataFrame): The cash flow dataset as a pandas DataFrame.
Note:
- The configuration file should be in YAML format and contain settings for date columns,
description columns, amount columns, and optionally cost/income columns.
- Initialize an instance of this class to begin cash flow analysis.
"""
def __init__(
self,
configuration_file: str | None = None,
portfolio_dataset: pd.DataFrame = pd.DataFrame(),
example: bool = False,
):
"""
Initialize a Cashflow instance with the provided configuration file.
This constructor sets up the Cashflow instance by loading the configuration file, defining
default attributes, and initializing the cash flow dataset as an empty DataFrame.
Parameters:
configuration_file (str): The file path to the configuration file in YAML format.
Raises:
ValueError: If the provided configuration file does not have a '.yaml' extension.
Only '.yaml' configuration files are supported.
"""
if example:
configuration_file = helpers.download_yaml_configuration(example=True)
helpers.download_example_datasets()
print(
f"Creating new Portfolio Configuration file at {configuration_file} and "
"downloading example datasets.\nRunning the Portfolio class with this example "
"dataset which illustrates the functionality of the Portfolio class."
)
elif configuration_file is None:
configuration_file = helpers.download_yaml_configuration(example=False)
print(
f"Creating new Portfolio file at {configuration_file}. Please provide this file "
"path to the Portfolio class to prevent overwriting the existing file."
)
self._configuration_file = str(configuration_file)
self._custom_dataset = portfolio_dataset
self._yearly_overview: pd.DataFrame = pd.DataFrame()
self._quarterly_overview: pd.DataFrame = pd.DataFrame()
self._monthly_overview: pd.DataFrame = pd.DataFrame()
self._yearly_cash_flow_dataset: pd.DataFrame = pd.DataFrame()
self._quarterly_cash_flow_dataset: pd.DataFrame = pd.DataFrame()
self._monthly_cash_flow_dataset: pd.DataFrame = pd.DataFrame()
# Tickers
self._ticker_combinations: dict[str, str] = {}
self._original_ticker_combinations: dict[str, str] = {}
# Historical Data
self._daily_historical_data: pd.DataFrame = pd.DataFrame()
self._weekly_historical_data: pd.DataFrame = pd.DataFrame()
self._monthly_historical_data: pd.DataFrame = pd.DataFrame()
self._quarterly_historical_data: pd.DataFrame = pd.DataFrame()
self._yearly_historical_data: pd.DataFrame = pd.DataFrame()
self._historical_statistics: pd.DataFrame = pd.DataFrame()
# Benchmark Historical Data
self._benchmark_tickers: dict[str, str] = {}
self._daily_benchmark_data: pd.DataFrame = pd.DataFrame()
self._weekly_benchmark_data: pd.DataFrame = pd.DataFrame()
self._monthly_benchmark_data: pd.DataFrame = pd.DataFrame()
self._quarterly_benchmark_data: pd.DataFrame = pd.DataFrame()
self._yearly_benchmark_data: pd.DataFrame = pd.DataFrame()
self._benchmark_prices: pd.DataFrame = pd.DataFrame()
self._benchmark_specific_prices: pd.Series = pd.Series()
self._benchmark_prices_per_ticker: pd.DataFrame = pd.DataFrame()
self._latest_benchmark_price: pd.Series = pd.Series()
# Portfolio Overveiw
self._portfolio_overview: pd.DataFrame = pd.DataFrame()
self._portfolio_performance: pd.DataFrame = pd.DataFrame()
self._transactions_performance: pd.DataFrame = pd.DataFrame()
self._portfolio_dataset: pd.DataFrame = pd.DataFrame()
self._positions_overview: pd.DataFrame = pd.DataFrame()
self._transactions_overview: pd.DataFrame = pd.DataFrame()
# Finance Toolkit Initialization
self._tickers: list | None = None
self._toolkit: Toolkit | None = None
self._benchmark_toolkit: Toolkit | None = None
self._currency_toolkit: Toolkit | None = None
self._latest_price: pd.Series = pd.Series()
self._daily_currency_data: pd.DataFrame = pd.DataFrame()
if self._configuration_file.endswith(".yaml"):
self._cfg: dict[str, dict] = helpers.read_yaml_file(
location=self._configuration_file
)
else:
raise ValueError("File type not supported. Please use .yaml")
if (
self._cfg["general"]["file_location"] == "REPLACE_ME"
and self._custom_dataset.empty
):
print(
f"{helpers.Style.BOLD}Please provide a file location in the configuration file (change "
f"'REPLACE_ME' within the general section) or provide a custom dataset.{helpers.Style.RESET}"
"\nSee https://github.com/JerBouma/FinancePortfolio for instructions"
)
else:
# Column Names
self._date_column: str = self._cfg["general"]["date_columns"]
self._name_column: str = self._cfg["general"]["name_columns"]
self._ticker_column: str = self._cfg["general"]["ticker_columns"]
self._price_column: str = self._cfg["general"]["price_columns"]
self._volume_column: str = self._cfg["general"]["volume_columns"]
self._costs_column: str = self._cfg["general"]["costs_columns"]
self.read_portfolio_dataset()
def to_toolkit(
self,
api_key: str | None = None,
quarterly: bool = False,
custom_ratios: dict | None = None,
rounding: int = 4,
remove_invalid_tickers: bool = False,
sleep_timer: bool = False,
progress_bar: bool = True,
) -> Toolkit:
"""
Converts the Portfolio to a Finance Toolkit object.
This method allows you to convert your Portfolio to a Finance Toolkit object,
giving access to 30+ years of fundamental and historical data, 130+ financial
metrics and much more. It intentilligently understands the assets you have
purchased and generated a "Portfolio" column automatically which is based off
your portfolio weights and the assets you have purchased. This allows you to
easily calculate portfolio metrics such as the Sharpe Ratio, Sortino Ratio,
Treynor Ratio, Value at Risk and many more that would fit precisely to your
portfolio.
Args:
api_key (str, optional):
Your API key for access to additional data. If not provided, only historical
data and indicators are available.
start_date (str, optional):
The start date for historical data retrieval. If not provided, it defaults
to the earliest available date.
end_date (str, optional):
The end date for historical data retrieval. If not provided, it defaults to
the current date.
quarterly (bool, optional):
Set to True to retrieve quarterly data. Defaults to False.
risk_free_rate (str, optional):
The risk-free rate used for calculations. Defaults to "10y".
benchmark_ticker (str, optional):
The benchmark ticker symbol. Defaults to "^GSPC".
custom_ratios (dict, optional):
Custom ratios to calculate. Should be a dictionary of ratio names and formulas.
rounding (int, optional):
The number of decimal places to round data. Defaults to 4.
remove_invalid_tickers (bool, optional):
Remove invalid tickers from the toolkit. Defaults to True.
sleep_timer (bool, optional):
Enable a sleep timer to avoid rate limiting. Defaults to False.
progress_bar (bool, optional):
Show a progress bar during data retrieval. Defaults to True.
Returns:
Toolkit:
A Finance Toolkit object.
"""
if api_key is None:
print(
"The parameter api_key is not set. Therefore, only historical data and "
"indicators are available. Consider obtaining a key with the following link: "
"https://intelligence.financialmodelingprep.com/pricing-plans?couponCode=jeroen"
"\nThe free plan has a limit of 5 years fundamental data and has no quarterly data. "
"You can get 15% off by using the above affiliate link to get access to 30+ years "
"of (quarterly) data which also supports the project."
)
if self._daily_historical_data.empty:
self.collect_historical_data()
if self._daily_benchmark_data.empty:
self.collect_benchmark_historical_data()
if self._positions_overview.empty:
self.get_positions_overview()
symbols = list(self._tickers) + ["Portfolio"] # type: ignore
historical_columns = self._daily_historical_data.columns.get_level_values(
0
).unique()
benchmark_ticker = self._cfg["general"]["benchmark_ticker"]
benchmark_data = self._daily_benchmark_data.xs(
benchmark_ticker, axis=1, level=1
)
for column in historical_columns:
self._daily_historical_data[column, "Benchmark"] = benchmark_data[column]
self._daily_historical_data[column, "Portfolio"] = (
self._positions_overview["Current Weight"]
.mul(self._daily_historical_data[column], axis=1)
.sum(axis=1)
)
historical = (
self._daily_historical_data.sort_index(axis=1)
.reindex(historical_columns, axis=1, level=0)
.reindex(list(self._tickers) + ["Portfolio", "Benchmark"], axis=1, level=1) # type: ignore
)
historical = historical.round(rounding)
toolkit = Toolkit(
tickers=symbols,
api_key=api_key,
historical=historical,
start_date=self._start_date,
quarterly=quarterly,
benchmark_ticker=benchmark_ticker,
custom_ratios=custom_ratios,
rounding=rounding,
remove_invalid_tickers=remove_invalid_tickers,
sleep_timer=sleep_timer,
progress_bar=progress_bar,
)
return toolkit
def read_portfolio_dataset(
self,
excel_location: str | list | None = None,
adjust_duplicates: bool | None = None,
date_column: list[str] | None = None,
date_format: str | None = None,
name_columns: list[str] | None = None,
ticker_columns: list[str] | None = None,
price_columns: list[str] | None = None,
volume_columns: list[str] | None = None,
currency_columns: list[str] | None = None,
costs_columns: list[str] | None = None,
column_mapping: dict[str, str] | None = None,
):
"""
Read and consolidate cash flow data from Excel or CSV files into a single DataFrame.
This function reads cash flow data from one or more Excel or CSV files specified by the
'excel_location' parameter. It can accept a single file path as a string or a list of file
paths. If 'excel_location' is not provided, it will use the default file location from the
configuration ('self._cfg["general"]["file_location"]').
The function identifies additional files within directories specified in 'excel_location'
and includes them in the data consolidation. It supports Excel (.xlsx) and CSV (.csv) file
formats.
If the cash flow dataset is initially empty, it reads and consolidates the data, performs
optional adjustments for duplicated rows, and sets column names to lowercase. The resulting
dataset is sorted by index in descending order and has its index converted to daily frequency
('D').
Next to that, this function performs various formatting and preprocessing steps to ensure
data consistency and facilitate analysis. It includes options to customize column names
for dates, descriptions, amounts, and cost/income categories.
Parameters:
excel_location (str | list | None): A file path or a list of file paths to Excel or CSV
files containing cash flow data. If None, the default file location from the
configuration is used.
adjust_duplicates (bool | None): A boolean value indicating whether to adjust duplicated
rows in the dataset. If None, it defaults to the value specified in the configuration
('self._cfg["general"]["adjust_duplicates"]').
date_column (list[str] | None): A list of column names representing date information
in the dataset. If None, it defaults to the date columns specified in the
configuration ('self._cfg["general"]["date_columns"]').
date_format (str | None): A string representing the date format in the dataset. If None,
it defaults to the date format specified in the configuration ('self._cfg["general"]["date_format"]').
description_columns (list[str] | None): A list of column names representing
transaction descriptions in the dataset. If None, it defaults to the description
columns specified in the configuration ('self._cfg["general"]["description_columns"]').
amount_column (list[str] | None): A list of column names representing transaction
amounts in the dataset. If None, it defaults to the amount columns specified in
the configuration ('self._cfg["general"]["amount_columns"]').
cost_or_income_column (list[str] | None): A list of column names representing
cost or income categories in the dataset. If None, it defaults to the cost/income
columns specified in the configuration ('self._cfg["general"]["cost_or_income_columns"]').
decimal_seperator (str | None): A string representing the decimal separator used in
the dataset. If None, it defaults to the decimal separator specified in the
configuration ('self._cfg["general"]["decimal_seperator"]').
Returns:
pd.DataFrame: A DataFrame containing the consolidated cash flow data.
Raises:
FileNotFoundError: If any of the specified files or directories in 'excel_location'
cannot be found.
ValueError: If essential columns (date, description, amount) are not found in the dataset.
- For missing columns, specify them in the configuration or provide them explicitly.
- For cost or income columns, raise an exception if not found and configuration is empty.
Note:
- Duplicates in individual datasets are adjusted based on configuration settings
('self._cfg["general"]["adjust_duplicates"]').
- If duplicates are found in the combination of datasets, they are removed to prevent
double-counting.
- The function handles formatting of date columns, converting them to datetime objects.
- Transaction description columns are converted to categorical data.
- Transaction amount columns are converted to float, with support for different decimal separators.
- Cost or income columns are converted to categorical data, with optional customization.
"""
date_column = (
date_column if date_column else self._cfg["general"]["date_columns"]
)
date_format = (
date_format if date_format else self._cfg["general"]["date_format"]
)
name_columns = (
name_columns if name_columns else self._cfg["general"]["name_columns"]
)
ticker_columns = (
ticker_columns if ticker_columns else self._cfg["general"]["ticker_columns"]
)
price_columns = (
price_columns if price_columns else self._cfg["general"]["price_columns"]
)
volume_columns = (
volume_columns if volume_columns else self._cfg["general"]["volume_columns"]
)
currency_columns = (
currency_columns
if currency_columns
else self._cfg["adjustments"]["currency_columns"]
)
costs_columns = (
costs_columns if costs_columns else self._cfg["general"]["costs_columns"]
)
column_mapping = (
column_mapping if column_mapping else self._cfg["general"]["column_mapping"]
)
if self._portfolio_dataset.empty:
if not self._custom_dataset.empty:
(
self._portfolio_dataset,
self._date_column,
self._name_column,
self._ticker_column,
self._price_column,
self._volume_column,
self._currency_column,
self._costs_column,
) = portfolio_model.format_portfolio_dataset(
dataset=self._portfolio_dataset,
date_columns=date_column,
date_format=date_format,
name_columns=name_columns,
tickers_columns=ticker_columns,
price_columns=price_columns,
volume_columns=volume_columns,
column_mapping=column_mapping,
currency_columns=currency_columns,
costs_columns=costs_columns,
)
else:
excel_location = (
excel_location
if excel_location
else self._cfg["general"]["file_location"]
)
if isinstance(excel_location, str):
excel_location = [excel_location]
adjust_duplicates = (
adjust_duplicates
if adjust_duplicates
else self._cfg["general"]["adjust_duplicates"]
)
(
self._portfolio_dataset,
self._date_column,
self._name_column,
self._ticker_column,
self._price_column,
self._volume_column,
self._currency_column,
self._costs_column,
) = portfolio_model.read_portfolio_dataset( # type: ignore
excel_location=excel_location,
adjust_duplicates=adjust_duplicates,
date_column=date_column,
date_format=date_format,
name_columns=name_columns,
ticker_columns=ticker_columns,
price_columns=price_columns,
volume_columns=volume_columns,
currency_columns=currency_columns,
costs_columns=costs_columns,
column_mapping=column_mapping,
)
self._original_tickers = list(
self._portfolio_dataset[self._ticker_column].unique()
)
if self._cfg["adjustments"]["isin_to_ticker"]:
self._portfolio_dataset = self._portfolio_dataset.replace(
self._cfg["adjustments"]["isin_to_ticker"]
)
self._portfolio_dataset = self._portfolio_dataset.sort_values(
by=self._date_column, ascending=True
)
self._tickers = list(self._portfolio_dataset[self._ticker_column].unique())
self._start_date = (
self._portfolio_dataset[self._date_column].min().strftime("%Y-%m-%d")
)
self._transactions_currencies = list(
self._portfolio_dataset[self._currency_column].unique() # type: ignore
)
self._portfolio_dataset = self._portfolio_dataset.set_index(
[self._date_column, self._ticker_column]
)
return self._portfolio_dataset
def collect_benchmark_historical_data(
self,
benchmark_ticker: str | None = None,
benchmark_per_ticker: dict[str, str] | None = None,
):
"""
Collect historical benchmark data for the portfolio.
This method retrieves historical benchmark data, such as daily, weekly, monthly, quarterly,
and yearly prices, for the specified benchmark ticker or per-ticker mapping. It matches the
benchmark data to the dates of the portfolio's historical data.
Args:
benchmark_ticker (str | None): The benchmark ticker symbol to use if no per-ticker mapping
is provided. If None, the default benchmark ticker from the configuration is used.
benchmark_per_ticker (dict[str, str] | None): A dictionary that maps original portfolio
tickers to their corresponding benchmark tickers. If not provided, it defaults to the
mapping specified in the configuration.
Returns:
DataFrame: A DataFrame containing the historical benchmark data.
"""
if self._daily_historical_data.empty:
self.collect_historical_data()
benchmark_ticker = (
benchmark_ticker
if benchmark_ticker
else self._cfg["general"]["benchmark_ticker"]
)
benchmark_per_ticker = (
benchmark_per_ticker
if benchmark_per_ticker
else self._cfg["general"]["benchmark_per_ticker"]
)
if not self._benchmark_toolkit:
self._benchmark_tickers = {}
for ticker in self._original_tickers:
self._benchmark_tickers[ticker] = benchmark_per_ticker.get(
ticker, benchmark_ticker
)
self._benchmark_toolkit = Toolkit(
tickers=list(set(self._benchmark_tickers.values())),
benchmark_ticker=None,
start_date=self._start_date,
)
# Reindex the benchmark data to the dates of the historical dataset so that they are matched up.
self._daily_benchmark_data = self._benchmark_toolkit.get_historical_data(
period="daily"
).reindex(self._daily_historical_data.index, method="backfill")
self._weekly_benchmark_data = self._benchmark_toolkit.get_historical_data(
period="weekly"
)
self._monthly_benchmark_data = self._benchmark_toolkit.get_historical_data(
period="monthly"
)
self._quarterly_benchmark_data = self._benchmark_toolkit.get_historical_data(
period="quarterly"
)
self._yearly_benchmark_data = self._benchmark_toolkit.get_historical_data(
period="yearly"
)
# It could be that a specific date does not exist for the given benchmark. In that case,
# the previous value is used instead.
self._benchmark_prices = self._daily_benchmark_data["Adj Close"].iloc[
self._daily_benchmark_data["Adj Close"].index.get_indexer(
self._portfolio_dataset.index.get_level_values(0), method="backfill"
)
]
# The index of the benchmark prices is set to the dates of the portfolio dataset
# so that they are matched up again.
self._benchmark_prices = self._benchmark_prices.set_index(
self._portfolio_dataset.index
)
self._benchmark_prices = self._benchmark_prices.sort_index()
benchmark_specific_prices = []
benchmark_latest_price = {}
benchmark_prices_per_ticker = pd.DataFrame(
columns=self._tickers, index=self._daily_benchmark_data.index
)
for (date, ticker), _ in self._portfolio_dataset.iterrows():
original_ticker = self._original_ticker_combinations[ticker]
benchmark_ticker = self._benchmark_tickers[original_ticker]
# Add the specific benchmark price and, if multiple orders of the same ticker are made on the same day
# (e.g. buying and selling), only report the benchmark price once.
benchmark_specific_prices.append(
self._benchmark_prices.loc[
(date, ticker), benchmark_ticker
].drop_duplicates()
)
benchmark_latest_price[ticker] = self._daily_benchmark_data["Adj Close"][
benchmark_ticker
].iloc[-1]
benchmark_prices_per_ticker[ticker] = self._daily_benchmark_data[
"Adj Close"
][benchmark_ticker]
self._benchmark_specific_prices = pd.concat(benchmark_specific_prices)
self._latest_benchmark_price = pd.Series(benchmark_latest_price)
self._benchmark_prices_per_ticker = benchmark_prices_per_ticker
return self._daily_benchmark_data
def collect_historical_data(
self,
historical_columns: list[str] | None = None,
isin_to_ticker: dict[str, str] | None = None,
):
"""
Collect historical price and currency adjustment data.
This method retrieves historical price data for the portfolio's tickers and performs
currency adjustments if necessary. It collects daily, weekly, monthly, quarterly, and
yearly price data and stores it in separate DataFrames.
Args:
historical_columns (list[str] | None): A list of column names representing historical price data.
If None, it defaults to the columns specified in the configuration
('self._cfg["adjustments"]["currency_adjustment_columns"]').
isin_to_ticker (dict[str, str] | None): A dictionary that maps ISIN codes to ticker symbols.
If provided, ISIN codes in the portfolio dataset will be matched to the corresponding
tickers. If None, it defaults to the mapping specified in the configuration.
Returns:
pd.DataFrame: A DataFrame containing the daily historical price data for the portfolio.
Note:
- This method uses the Toolkit class to fetch historical price data from a data source.
- Currency conversions are performed if there is a mismatch between the currency of transactions
and the currency of historical data. Currency conversion rates are fetched using the Currency Toolkit.
- The resulting historical price data is stored in separate DataFrames for different periods.
"""
historical_columns = (
historical_columns
if historical_columns
else self._cfg["adjustments"]["currency_adjustment_columns"]
)
isin_to_ticker = (
isin_to_ticker
if isin_to_ticker
else self._cfg["adjustments"]["isin_to_ticker"]
)
if not self._toolkit:
self._toolkit = Toolkit(
tickers=self._tickers,
benchmark_ticker=None,
start_date=self._start_date,
)
# This is used in case ISIN codes are provided and therefore ISIN codes need to
# be matched to the corresponding tickers
self._ticker_combinations = dict(zip(self._toolkit._tickers, self._tickers)) # type: ignore
self._original_ticker_combinations = dict(
zip(self._tickers, self._original_tickers) # type: ignore
)
self._daily_historical_data = self._toolkit.get_historical_data(period="daily")
self._daily_historical_data = self._daily_historical_data.rename(
columns=self._ticker_combinations, level=1
)
currency_conversions = {}
if self._currency_column: # type: ignore
self._historical_statistics = self._toolkit.get_historical_statistics()
self._historical_statistics = self._historical_statistics.rename(
columns=self._ticker_combinations, level=0
)
for (_, ticker), currency in self._portfolio_dataset[
self._currency_column # type: ignore
].items():
data_currency = self._historical_statistics.loc["Currency", ticker]
if self._historical_statistics.loc["Currency", ticker] != currency:
currency_conversions[
ticker
] = f"{currency}{data_currency}=X".upper()
if currency_conversions:
print(
"Found a mismatch between the currency of the transaction and the currency of the historical data. "
"This is usually due to working with ISIN codes.\nConsider filling the 'isin_to_ticker' parameter to "
"correct this by finding the correct ticker on Yahoo Finance (e.g. VUSA.AS). The currencies are "
"automatically converted but this does lead to some inaccuracies."
)
self._currency_toolkit = Toolkit(
tickers=list(set(currency_conversions.values())),
benchmark_ticker=None,
start_date=self._start_date,
)
self._daily_currency_data = self._currency_toolkit.get_historical_data(
period="daily"
)
for ticker, currency in currency_conversions.items():
for column in historical_columns:
self._daily_historical_data.loc[:, (column, ticker)] = (
self._daily_historical_data.loc[:, (column, ticker)]
/ self._daily_currency_data.loc[:, (column, currency)]
)
self._weekly_historical_data = self._toolkit.get_historical_data(
period="weekly"
)
self._weekly_historical_data = self._weekly_historical_data.rename(
columns=self._ticker_combinations, level=1
)
self._monthly_historical_data = self._toolkit.get_historical_data(
period="monthly"
)
self._monthly_historical_data = self._monthly_historical_data.rename(
columns=self._ticker_combinations, level=1
)
self._quarterly_historical_data = self._toolkit.get_historical_data(
period="quarterly"
)
self._quarterly_historical_data = self._quarterly_historical_data.rename(
columns=self._ticker_combinations, level=1
)
self._yearly_historical_data = self._toolkit.get_historical_data(
period="yearly"
)
self._yearly_historical_data = self._yearly_historical_data.rename(
columns=self._ticker_combinations, level=1
)
self._latest_price = self._daily_historical_data["Adj Close"].iloc[-1]
return self._daily_historical_data
def get_positions_overview(self):
"""
Calculate and provide an overview of the portfolio positions.
This method calculates an overview of the portfolio's positions, including
key statistics and performance metrics. It returns a DataFrame summarizing these
metrics.
If the necessary historical data has not been collected, this method will first
trigger data collection using the `collect_historical_data` and
`collect_benchmark_historical_data` methods.
Returns:
DataFrame: A DataFrame containing an overview of the portfolio's positions.
Raises:
Exception: If data collection for historical or benchmark data fails.
"""
if self._daily_historical_data.empty:
try:
self.collect_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect historical data due to {error}"
) from error
if self._daily_benchmark_data.empty:
try:
self.collect_benchmark_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect benchmark historical data due to {error}"
) from error
if self._transactions_overview.empty:
try:
self.get_transactions_overview()
except ValueError as error:
raise ValueError(
f"Failed to get transactions overview due to {error}"
) from error
if self._positions_overview.empty:
try:
self._positions_overview = portfolio_model.create_positions_overview(
portfolio_tickers=self._tickers,
period_dates=self._daily_historical_data.index.get_level_values(0),
portfolio_dataset=self._transactions_overview,
historical_prices=self._daily_historical_data,
)
except ValueError as error:
raise ValueError(
f"Failed to create positions overview due to {error}"
) from error
return self._positions_overview
def get_portfolio_overview(self):
"""
Calculate and provide an overview of the portfolio's key statistics.
This method calculates various key statistics for the portfolio, including
performance metrics and cost-related information. It returns a DataFrame
summarizing these metrics.
If the necessary historical data has not been collected, this method will first
trigger data collection using the `collect_historical_data` and
`collect_benchmark_historical_data` methods.
Returns:
DataFrame: A DataFrame containing key statistics and an overview of the portfolio.
Raises:
Exception: If data collection for historical or benchmark data fails.
Exception: If the creation of portfolio overview fails.
"""
if self._daily_historical_data.empty:
try:
self.collect_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect historical data: {error}"
) from error
if self._daily_benchmark_data.empty:
try:
self.collect_benchmark_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect benchmark historical data: {error}"
) from error
if self._portfolio_overview.empty:
try:
self._portfolio_overview = portfolio_model.create_portfolio_overview(
portfolio_name=self._portfolio_dataset[self._name_column],
portfolio_volume=self._portfolio_dataset[self._volume_column],
portfolio_price=self._portfolio_dataset[self._price_column],
portfolio_costs=self._portfolio_dataset[self._costs_column],
latest_returns=self._latest_price,
benchmark_prices=self._benchmark_specific_prices,
benchmark_latest_prices=self._latest_benchmark_price,
)
except ValueError as error:
raise ValueError(
f"Failed to create portfolio overview: {error}"
) from error
return self._portfolio_overview
def get_portfolio_performance(self, period: str | None = None):
"""
Calculate portfolio performance metrics for a specified period.
This method calculates various portfolio performance metrics, such as returns,
for the specified period. It uses the positions overview dataset for these
calculations.
Args:
period_string (str | None): The time period for which portfolio performance
metrics should be calculated. This can be 'yearly', 'quarterly', 'monthly',
'weekly', or 'daily'. If None, the default is 'daily'.
Returns:
DataFrame: A DataFrame containing portfolio performance metrics.
Raises:
ValueError: If an invalid or unsupported period_string is provided.
"""
if self._daily_historical_data.empty:
try:
self.collect_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect historical data: {error}"
) from error
if self._daily_benchmark_data.empty:
try:
self.collect_benchmark_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect benchmark historical data: {error}"
) from error
if self._positions_overview.empty:
try:
self.get_positions_overview()
except ValueError as error:
raise ValueError(
f"Failed to get positions overview: {error}"
) from error
if not period:
raise ValueError(
"Please provide a period. This can be 'yearly', 'quarterly', 'monthly', 'weekly', or 'daily'"
)
period_string = period.lower()
if period_string == "yearly":
period_symbol = "Y"
elif period_string == "quarterly":
period_symbol = "Q"
elif period_string == "monthly":
period_symbol = "M"
elif period_string == "weekly":
period_symbol = "W"
elif period_string == "daily":
period_symbol = "D"
else:
raise ValueError(
"Please provide a valid period. This can be 'yearly', 'quarterly', 'monthly', 'weekly', or 'daily'"
)
try:
self._portfolio_performance = portfolio_model.create_portfolio_performance(
positions_dataset=self._positions_overview,
date_column=self._date_column,
ticker_column=self._ticker_column,
period_string=period_symbol,
)
except ValueError as error:
raise ValueError(
f"Failed to create portfolio performance: {error}"
) from error
return self._portfolio_performance
def get_transactions_overview(self):
"""
Calculate and collect transaction overview ratios based on the provided data.
This method calculates various transaction overview ratios, such as returns and costs,
based on the transaction dataset. It adds these ratios as new columns to the
portfolio dataset.
Returns:
DataFrame: The portfolio dataset with added transaction overview ratios.
Raises:
ValueError: If there is an issue with collecting historical data or creating the transaction overview.
"""
if self._daily_historical_data.empty:
try:
self.collect_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect historical data: {error}"
) from error
if self._daily_benchmark_data.empty:
try:
self.collect_benchmark_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect benchmark historical data: {error}"
) from error
try:
new_columns = portfolio_model.create_transactions_overview(
portfolio_volume=self._portfolio_dataset[self._volume_column],
portfolio_price=self._portfolio_dataset[self._price_column],
portfolio_costs=self._portfolio_dataset[self._costs_column],
latest_returns=self._latest_price.loc[self._tickers],
)
except ValueError as error:
raise ValueError(
f"Failed to create transaction overview: {error}"
) from error
try:
self._transactions_overview = pd.concat(
[self._portfolio_dataset, new_columns], axis=1
)
except ValueError as error:
raise ValueError(
f"Failed to add transaction overview to portfolio dataset: {error}"
) from error
return self._transactions_overview
def get_transactions_performance(self, period: str | None = None):
"""
Calculate transaction performance metrics for a specified period.
This method calculates various transaction performance metrics, such as returns,
costs, and benchmarks, for the specified period. It uses historical price data
from the corresponding period for these calculations.
Args:
period_string (str | None): The time period for which transaction performance
metrics should be calculated. This can be 'yearly', 'quarterly', 'monthly',
'weekly', or 'daily'. If None, the default is 'daily'.
Returns:
DataFrame: A DataFrame containing transaction performance metrics.
Raises:
ValueError: If an invalid or unsupported period_string is provided.
"""
if self._daily_historical_data.empty:
try:
self.collect_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect historical data: {error}"
) from error
if self._daily_benchmark_data.empty:
try:
self.collect_benchmark_historical_data()
except ValueError as error:
raise ValueError(
f"Failed to collect benchmark historical data: {error}"
) from error
if not period:
raise ValueError(
"Please provide a period. This can be 'yearly', 'quarterly', 'monthly', 'weekly', or 'daily'"
)
period_string = period.lower()
if period_string == "yearly":
historical_dataset = self._yearly_historical_data["Adj Close"]
benchmark_dataset = self._yearly_benchmark_data["Adj Close"]
period_symbol = "Y"
elif period_string == "quarterly":
historical_dataset = self._quarterly_historical_data["Adj Close"]
benchmark_dataset = self._quarterly_benchmark_data["Adj Close"]
period_symbol = "Q"
elif period_string == "monthly":
historical_dataset = self._monthly_historical_data["Adj Close"]
benchmark_dataset = self._monthly_benchmark_data["Adj Close"]
period_symbol = "M"
elif period_string == "weekly":
historical_dataset = self._weekly_historical_data["Adj Close"]
benchmark_dataset = self._weekly_benchmark_data["Adj Close"]
period_symbol = "W"
elif period_string == "daily":
historical_dataset = self._daily_historical_data["Adj Close"]
benchmark_dataset = self._daily_benchmark_data["Adj Close"]
period_symbol = "D"
else:
raise ValueError(
"Please provide a valid period. This can be "
"'yearly', 'quarterly', 'monthly', 'weekly', "
"or 'daily'"
)
try:
self._transactions_performance = (
portfolio_model.create_transactions_performance(
portfolio_dataset=self._portfolio_dataset,
ticker_column=self._ticker_column,
date_column=self._date_column,
volume_column=self._volume_column,
price_column=self._price_column,
costs_column=self._costs_column,
period_prices=historical_dataset,
period_string=period_symbol,
original_ticker_combinations=self._original_ticker_combinations,
benchmark_per_ticker=self._benchmark_tickers,
benchmark_specific_prices=self._benchmark_specific_prices,
benchmark_period_prices=benchmark_dataset,
)
)
except ValueError as error:
raise ValueError(
f"Failed to create transaction performance metrics: {error}"
) from error
return self._transactions_performance
def create_excel_report(
self,
excel_file_name: str | None = None,
currency: str | None = None,
):
"""
Create an Excel report file with specified data sheets.
This function creates an Excel file with multiple data sheets, including monthly,
quarterly, and yearly overviews if the corresponding data is available. The data
sheets are populated with dataframes provided by the class attributes
_monthly_overview, _quarterly_overview, and _yearly_overview.
The Excel file is saved with the specified name or the default name from the
configuration. The date and datetime formats in the Excel file are set to
"yyyy-mm-dd" for consistency.
Args:
excel_file_name (str | None): The name of the Excel file to be created. If None,
the default file name specified in the configuration will be used.
currency (str | None): The currency to be used for formatting in the Excel file.
If None, the default currency from the configuration will be used.
"""
excel_file_name = (
excel_file_name if excel_file_name else self._cfg["excel"]["file_name"]
)
currency = currency if currency else self._cfg["excel"]["currency"]
writer = pd.ExcelWriter(
excel_file_name,
engine="xlsxwriter",
date_format="yyyy-mm-dd",
datetime_format="yyyy-mm-dd",
)
try:
# Try to create and save Portfolio Overview
self._portfolio_overview = self.get_portfolio_overview()
| excel_model.create_portfolio_overview_excel_report(
| 0 | 2023-10-15 09:16:04+00:00 | 4k |
gschramm/2023-MIC-ImageRecon-Shortcourse | 07_osem_varnet_evaluation.py | [
{
"identifier": "EMUpdateModule",
"path": "layers.py",
"snippet": "class EMUpdateModule(torch.nn.Module):\n\n def __init__(\n self,\n projector: parallelproj.LinearOperator,\n ) -> None:\n\n super().__init__()\n self._projector = projector\n\n self._fwd_op_layer ... | import argparse
import json
import utils
import parallelproj
import array_api_compat.torch as torch
import array_api_compat.numpy as np
import pymirc.viewer as pv
from layers import EMUpdateModule
from models import Unet3D, SimpleOSEMVarNet, PostReconNet
from data import load_brain_image_batch, simulate_data_batch
from pathlib import Path | 3,351 | """minimal script that evaluates trained OSEM varnets
"""
from __future__ import annotations
parser = argparse.ArgumentParser(description='OSEM-VARNet evaluation')
parser.add_argument('--run_dir')
parser.add_argument('--sens', type=float, default=1)
args = parser.parse_args()
run_dir = Path(args.run_dir)
sens = args.sens
with open(run_dir / 'input_cfg.json', 'r') as f:
cfg = json.load(f)
num_datasets = cfg['num_datasets']
num_training = cfg['num_training']
num_validation = cfg['num_validation']
num_subsets = cfg['num_subsets']
depth = cfg['depth']
num_epochs = cfg['num_epochs']
num_epochs_post = cfg['num_epochs_post']
batch_size = cfg['batch_size']
num_features = cfg['num_features']
num_rings = cfg['num_rings']
radial_trim = cfg['radial_trim']
random_seed = cfg['random_seed']
voxel_size = tuple(cfg['voxel_size'])
if 'fusion_mode' in cfg:
fusion_mode = cfg['fusion_mode']
else:
fusion_mode = 'simple'
# device variable (cpu or cuda) that determines whether calculations
# are performed on the cpu or cuda gpu
if parallelproj.cuda_present:
dev = 'cuda'
else:
dev = 'cpu'
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
#--- setup the scanner / LOR geometry ---------------------------------------
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# setup a line of response descriptor that describes the LOR start / endpoints of
# a "narrow" clinical PET scanner with 9 rings
lor_descriptor = utils.DemoPETScannerLORDescriptor(torch,
dev,
num_rings=num_rings,
radial_trim=radial_trim)
axial_fov_mm = float(lor_descriptor.scanner.num_rings *
(lor_descriptor.scanner.ring_positions[1] -
lor_descriptor.scanner.ring_positions[0]))
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
#--- load the brainweb images -----------------------------------------------
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# image properties
dataset_ids = tuple(
[i for i in range(num_training, num_training + num_validation)])
val_loss_post = {}
val_loss = {}
for i, dataset_id in enumerate(dataset_ids):
| """minimal script that evaluates trained OSEM varnets
"""
from __future__ import annotations
parser = argparse.ArgumentParser(description='OSEM-VARNet evaluation')
parser.add_argument('--run_dir')
parser.add_argument('--sens', type=float, default=1)
args = parser.parse_args()
run_dir = Path(args.run_dir)
sens = args.sens
with open(run_dir / 'input_cfg.json', 'r') as f:
cfg = json.load(f)
num_datasets = cfg['num_datasets']
num_training = cfg['num_training']
num_validation = cfg['num_validation']
num_subsets = cfg['num_subsets']
depth = cfg['depth']
num_epochs = cfg['num_epochs']
num_epochs_post = cfg['num_epochs_post']
batch_size = cfg['batch_size']
num_features = cfg['num_features']
num_rings = cfg['num_rings']
radial_trim = cfg['radial_trim']
random_seed = cfg['random_seed']
voxel_size = tuple(cfg['voxel_size'])
if 'fusion_mode' in cfg:
fusion_mode = cfg['fusion_mode']
else:
fusion_mode = 'simple'
# device variable (cpu or cuda) that determines whether calculations
# are performed on the cpu or cuda gpu
if parallelproj.cuda_present:
dev = 'cuda'
else:
dev = 'cpu'
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
#--- setup the scanner / LOR geometry ---------------------------------------
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# setup a line of response descriptor that describes the LOR start / endpoints of
# a "narrow" clinical PET scanner with 9 rings
lor_descriptor = utils.DemoPETScannerLORDescriptor(torch,
dev,
num_rings=num_rings,
radial_trim=radial_trim)
axial_fov_mm = float(lor_descriptor.scanner.num_rings *
(lor_descriptor.scanner.ring_positions[1] -
lor_descriptor.scanner.ring_positions[0]))
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
#--- load the brainweb images -----------------------------------------------
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# image properties
dataset_ids = tuple(
[i for i in range(num_training, num_training + num_validation)])
val_loss_post = {}
val_loss = {}
for i, dataset_id in enumerate(dataset_ids): | emission_image_database, attenuation_image_database = load_brain_image_batch( | 4 | 2023-10-16 07:18:26+00:00 | 4k |
ZiaWang/jqtrade | jqtrade/account/api.py | [
{
"identifier": "InvalidParam",
"path": "jqtrade/common/exceptions.py",
"snippet": "class InvalidParam(UserError):\n \"\"\" 用户参数错误 \"\"\"\n pass"
},
{
"identifier": "sys_logger",
"path": "jqtrade/common/log.py",
"snippet": "class SystemLogFormatter(logging.Formatter):\n class Co... | from ..common.exceptions import InvalidParam
from ..common.log import sys_logger
from ..scheduler.context import Context
from .order import OrderSide, OrderStatus, OrderStyle, MarketOrderStyle, LimitOrderStyle
from .position import Position | 2,969 | # -*- coding: utf-8 -*-
logger = sys_logger.getChild("account.api")
def _check_code(code):
if not (code[-4:] in ("XSHE", "XSHG") and code[:-5].isdigit()):
raise InvalidParam(f"标的代码错误: {code}")
def _check_amount(amount):
if not isinstance(amount, int) or amount == 0:
raise InvalidParam(f"委托数量错误,只能是非零整数:{amount}")
def _check_style(style):
if not OrderStyle.is_valid_style(style):
raise InvalidParam(f"style参数错误,只能是MarketOrderStyle, LimitOrderStyle类型的实例: {style}")
def _check_side(side):
if not OrderSide.is_valid_side(side):
raise InvalidParam(f"side参数错误,只能是{list(OrderSide.__members__)}中的一种")
def _check_status(status):
if not OrderStatus.is_valid_status(status):
raise InvalidParam(f"status参数错误,只能是{list(OrderStatus.__members__)}中的一种")
def order(code, amount, style=None, side='long'):
""" 下单
Args:
code: 标的代码字符串,暂只支持上交所和深交所标的下单
上交所示例:600000.XSHG
深交所示例:000001.XSHE
amount: 委托数量,正数代表买入、负数代表卖出
style: 下单类型,支持MarketOrderStyle(市价单)、LimitOrderStyle(限价单)
side: 买卖方向,做多:'long',做空:'short'
Return:
返回内部委托id字符串
"""
_check_code(code)
_check_amount(amount)
if style:
_check_style(style)
else:
style = MarketOrderStyle(0)
if side:
_check_side(side)
else:
side = "long"
side = OrderSide.get_side(side)
| # -*- coding: utf-8 -*-
logger = sys_logger.getChild("account.api")
def _check_code(code):
if not (code[-4:] in ("XSHE", "XSHG") and code[:-5].isdigit()):
raise InvalidParam(f"标的代码错误: {code}")
def _check_amount(amount):
if not isinstance(amount, int) or amount == 0:
raise InvalidParam(f"委托数量错误,只能是非零整数:{amount}")
def _check_style(style):
if not OrderStyle.is_valid_style(style):
raise InvalidParam(f"style参数错误,只能是MarketOrderStyle, LimitOrderStyle类型的实例: {style}")
def _check_side(side):
if not OrderSide.is_valid_side(side):
raise InvalidParam(f"side参数错误,只能是{list(OrderSide.__members__)}中的一种")
def _check_status(status):
if not OrderStatus.is_valid_status(status):
raise InvalidParam(f"status参数错误,只能是{list(OrderStatus.__members__)}中的一种")
def order(code, amount, style=None, side='long'):
""" 下单
Args:
code: 标的代码字符串,暂只支持上交所和深交所标的下单
上交所示例:600000.XSHG
深交所示例:000001.XSHE
amount: 委托数量,正数代表买入、负数代表卖出
style: 下单类型,支持MarketOrderStyle(市价单)、LimitOrderStyle(限价单)
side: 买卖方向,做多:'long',做空:'short'
Return:
返回内部委托id字符串
"""
_check_code(code)
_check_amount(amount)
if style:
_check_style(style)
else:
style = MarketOrderStyle(0)
if side:
_check_side(side)
else:
side = "long"
side = OrderSide.get_side(side)
| ctx = Context.get_instance() | 2 | 2023-10-24 01:34:27+00:00 | 4k |
Glasgow-AI4BioMed/GenKIE | data/pretrain_data/unify_dataset.py | [
{
"identifier": "data_utils",
"path": "data/data_utils.py",
"snippet": "def infer_language_pair(path):\ndef collate_tokens(\n values,\n pad_idx,\n eos_idx=None,\n left_pad=False,\n move_eos_to_beginning=False,\n pad_to_length=None,\n pad_to_multiple=1,\n pad_to_bsz=None,\n):\n ... | from io import BytesIO
from torchvision import transforms
from PIL import Image, ImageFile
from data import data_utils
from data.ofa_dataset import OFADataset
from utils.vision_helper import RandomAugment
import math
import logging
import random
import warnings
import numpy as np
import torch
import base64
import utils.transforms as T | 2,902 | batch = {
"id": id,
"nsentences": len(samples),
"ntokens": ntokens,
"net_input": {
"src_tokens": src_tokens,
"src_lengths": src_lengths,
"patch_images": patch_images,
"patch_masks": patch_masks,
"code_masks": code_masks,
"prev_output_tokens": prev_output_tokens
},
"target": target,
"conf": conf
}
return batch
class UnifyDataset(OFADataset):
def __init__(
self,
split,
dataset,
bpe,
src_dict,
tgt_dict=None,
max_src_length=128,
max_tgt_length=30,
seed=7,
code_dict_size=8192,
num_bins=1000,
patch_image_size=384,
code_image_size=128,
pure_text_dataset=None,
pure_image_dataset=None,
detection_dataset=None,
all_object_list=None,
all_caption_list=None,
type2ans_dict=None,
ans2type_dict=None,
max_image_size=512,
mask_ratio=0.3,
random_ratio=0.0,
keep_ratio=0.0,
mask_length="span-poisson",
poisson_lambda=3.0,
replace_length=1
):
super().__init__(split, dataset, bpe, src_dict, tgt_dict)
self.max_src_length = max_src_length
self.max_tgt_length = max_tgt_length
self.seed = seed
self.code_dict_size = code_dict_size
self.num_bins = num_bins
self.patch_image_size = patch_image_size
self.code_image_size = code_image_size
self.pure_text_dataset = pure_text_dataset
self.pure_image_dataset = pure_image_dataset
self.detection_dataset = detection_dataset
self.epoch = 0
self.all_object_list = all_object_list
self.all_caption_list = all_caption_list
self.type2ans_dict = type2ans_dict
self.ans2type_dict = ans2type_dict
self.mask_ratio = mask_ratio
self.random_ratio = random_ratio
self.keep_ratio = keep_ratio
self.mask_length = mask_length
self.poisson_lambda = poisson_lambda
self.replace_length = replace_length
if self.replace_length not in [-1, 0, 1]:
raise ValueError(f"invalid arg: replace_length={self.replace_length}")
if self.mask_length not in ["subword", "word", "span-poisson"]:
raise ValueError(f"invalid arg: mask-length={self.mask_length}")
if self.mask_length == "subword" and self.replace_length not in [0, 1]:
raise ValueError(f"if using subwords, use replace-length=1 or 0")
self.mask_idx = src_dict.index("<mask>")
self.mask_whole_word = (
get_whole_word_mask(self.bpe, self.src_dict)
if self.mask_length != "subword"
else None
)
self.mask_span_distribution = None
if self.mask_length == "span-poisson":
_lambda = self.poisson_lambda
lambda_to_the_k = 1
e_to_the_minus_lambda = math.exp(-_lambda)
k_factorial = 1
ps = []
for k in range(0, 128):
ps.append(e_to_the_minus_lambda * lambda_to_the_k / k_factorial)
lambda_to_the_k *= _lambda
k_factorial *= k + 1
if ps[-1] < 0.0000001:
break
ps = torch.FloatTensor(ps)
self.mask_span_distribution = torch.distributions.Categorical(ps)
self.pos_tgt_item = self.encode_text(" yes")
self.neg_tgt_item = self.encode_text(" no")
self.mask_left = self.mask_top = int(0.5 * self.code_image_size)
self.mask_right = self.mask_bottom = int(1.5 * self.code_image_size)
self.mask_ids = [
i*self.code_image_size*2+j
for i in range(self.code_image_size*2) for j in range(self.code_image_size*2)
if not (self.mask_left <= i < self.mask_right and self.mask_top <= j < self.mask_bottom)
]
scales = np.arange(patch_image_size, 481).tolist()
# for image-text pair
self.patch_resize_transform = transforms.Compose([
T.RandomResize(scales, max_size=672),
transforms.CenterCrop(patch_image_size),
| # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
ImageFile.LOAD_TRUNCATED_IMAGES = True
ImageFile.MAX_IMAGE_PIXELS = None
Image.MAX_IMAGE_PIXELS = None
logger = logging.getLogger(__name__)
warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
def get_whole_word_mask(bpe, dictionary):
if bpe is not None:
def is_beginning_of_word(i):
if i < dictionary.nspecial:
# special elements are always considered beginnings
return True
tok = dictionary[i]
if tok.startswith("madeupword"):
return True
try:
return bpe.is_beginning_of_word(tok)
except ValueError:
return True
mask_whole_words = torch.ByteTensor(
list(map(is_beginning_of_word, range(len(dictionary))))
)
return mask_whole_words
return None
def collate(samples, pad_idx, eos_idx):
if len(samples) == 0:
return {}
def merge(key):
return data_utils.collate_tokens(
[s[key] for s in samples],
pad_idx,
eos_idx=eos_idx,
)
id = np.array([s["id"] for s in samples])
src_tokens = merge("source")
src_lengths = torch.LongTensor([s["source"].ne(pad_idx).long().sum() for s in samples])
patch_images = torch.stack([sample['patch_image'] for sample in samples], dim=0)
patch_masks = torch.cat([sample['patch_mask'] for sample in samples])
code_masks = None
if samples[0].get("code_mask", None) is not None:
code_masks = torch.cat([sample['code_mask'] for sample in samples])
conf = torch.cat([s['conf'] for s in samples], dim=0)
prev_output_tokens = None
target = None
if samples[0].get("target", None) is not None:
target = merge("target")
tgt_lengths = torch.LongTensor([s["target"].ne(pad_idx).long().sum() for s in samples])
ntokens = tgt_lengths.sum().item()
if samples[0].get("prev_output_tokens", None) is not None:
prev_output_tokens = merge("prev_output_tokens")
else:
ntokens = src_lengths.sum().item()
batch = {
"id": id,
"nsentences": len(samples),
"ntokens": ntokens,
"net_input": {
"src_tokens": src_tokens,
"src_lengths": src_lengths,
"patch_images": patch_images,
"patch_masks": patch_masks,
"code_masks": code_masks,
"prev_output_tokens": prev_output_tokens
},
"target": target,
"conf": conf
}
return batch
class UnifyDataset(OFADataset):
def __init__(
self,
split,
dataset,
bpe,
src_dict,
tgt_dict=None,
max_src_length=128,
max_tgt_length=30,
seed=7,
code_dict_size=8192,
num_bins=1000,
patch_image_size=384,
code_image_size=128,
pure_text_dataset=None,
pure_image_dataset=None,
detection_dataset=None,
all_object_list=None,
all_caption_list=None,
type2ans_dict=None,
ans2type_dict=None,
max_image_size=512,
mask_ratio=0.3,
random_ratio=0.0,
keep_ratio=0.0,
mask_length="span-poisson",
poisson_lambda=3.0,
replace_length=1
):
super().__init__(split, dataset, bpe, src_dict, tgt_dict)
self.max_src_length = max_src_length
self.max_tgt_length = max_tgt_length
self.seed = seed
self.code_dict_size = code_dict_size
self.num_bins = num_bins
self.patch_image_size = patch_image_size
self.code_image_size = code_image_size
self.pure_text_dataset = pure_text_dataset
self.pure_image_dataset = pure_image_dataset
self.detection_dataset = detection_dataset
self.epoch = 0
self.all_object_list = all_object_list
self.all_caption_list = all_caption_list
self.type2ans_dict = type2ans_dict
self.ans2type_dict = ans2type_dict
self.mask_ratio = mask_ratio
self.random_ratio = random_ratio
self.keep_ratio = keep_ratio
self.mask_length = mask_length
self.poisson_lambda = poisson_lambda
self.replace_length = replace_length
if self.replace_length not in [-1, 0, 1]:
raise ValueError(f"invalid arg: replace_length={self.replace_length}")
if self.mask_length not in ["subword", "word", "span-poisson"]:
raise ValueError(f"invalid arg: mask-length={self.mask_length}")
if self.mask_length == "subword" and self.replace_length not in [0, 1]:
raise ValueError(f"if using subwords, use replace-length=1 or 0")
self.mask_idx = src_dict.index("<mask>")
self.mask_whole_word = (
get_whole_word_mask(self.bpe, self.src_dict)
if self.mask_length != "subword"
else None
)
self.mask_span_distribution = None
if self.mask_length == "span-poisson":
_lambda = self.poisson_lambda
lambda_to_the_k = 1
e_to_the_minus_lambda = math.exp(-_lambda)
k_factorial = 1
ps = []
for k in range(0, 128):
ps.append(e_to_the_minus_lambda * lambda_to_the_k / k_factorial)
lambda_to_the_k *= _lambda
k_factorial *= k + 1
if ps[-1] < 0.0000001:
break
ps = torch.FloatTensor(ps)
self.mask_span_distribution = torch.distributions.Categorical(ps)
self.pos_tgt_item = self.encode_text(" yes")
self.neg_tgt_item = self.encode_text(" no")
self.mask_left = self.mask_top = int(0.5 * self.code_image_size)
self.mask_right = self.mask_bottom = int(1.5 * self.code_image_size)
self.mask_ids = [
i*self.code_image_size*2+j
for i in range(self.code_image_size*2) for j in range(self.code_image_size*2)
if not (self.mask_left <= i < self.mask_right and self.mask_top <= j < self.mask_bottom)
]
scales = np.arange(patch_image_size, 481).tolist()
# for image-text pair
self.patch_resize_transform = transforms.Compose([
T.RandomResize(scales, max_size=672),
transforms.CenterCrop(patch_image_size), | RandomAugment(2, 7, isPIL=True, augs=['Identity', 'AutoContrast', 'Equalize', 'Brightness', 'Sharpness', | 2 | 2023-10-20 20:01:42+00:00 | 4k |
ArnaudParant/sel | tests/test_parser_n_formator.py | [
{
"identifier": "query_string_parser",
"path": "sel/query_string_parser.py",
"snippet": "AGGREG_TYPES = [\"aggreg\", \"histogram\", \"count\", \"distinct\", \"min\", \"max\", \"sum\", \"average\", \"stats\"]\nAGGREG_PARAMETER_MAPPING = {\n \"subaggreg\": None,\n \"interval\": None,\n \"size\": ... | import json
import pytest
import traceback
from sel import query_string_parser
from sel.query_string_parser import (
Value, QueryString, Comparator, Not, RangeFilter, Filter, Context,
Aggreg, Sort, Group, NoBracketGroup, Query
)
from sel import query_object_formator | 1,743 |
class TestParserNFormator:
@pytest.mark.parametrize(["query", "expected"], [
["toto", "toto"],
['"toto tata titi"', "toto tata titi"],
["toto tata titi", None], # Exception, does not match type Value
])
def test_value(self, query, expected):
try:
|
class TestParserNFormator:
@pytest.mark.parametrize(["query", "expected"], [
["toto", "toto"],
['"toto tata titi"', "toto tata titi"],
["toto tata titi", None], # Exception, does not match type Value
])
def test_value(self, query, expected):
try: | res = query_string_parser.parse(query, grammar=Value) | 0 | 2023-10-16 09:03:13+00:00 | 4k |
Qualcomm-AI-research/outlier-free-transformers | quantization/autoquant_utils.py | [
{
"identifier": "FP32Acts",
"path": "quantization/base_quantized_classes.py",
"snippet": "class FP32Acts(nn.Module):\n def forward(self, x):\n return x\n\n def reset_ranges(self):\n pass"
},
{
"identifier": "QuantizedActivation",
"path": "quantization/base_quantized_class... | import copy
import warnings
from torch import nn
from torch.nn import functional as F
from torch.nn.modules.pooling import _AdaptiveAvgPoolNd, _AvgPoolNd
from quantization.base_quantized_classes import (
FP32Acts,
QuantizedActivation,
QuantizedModule,
)
from quantization.hijacker import QuantizationHijacker, activations_set
from quantization.quantization_manager import QuantizationManager | 3,541 | def run_forward(self, x, weight, bias, offsets=None):
return F.layer_norm(
input=x.contiguous(),
normalized_shape=self.normalized_shape,
weight=weight.contiguous(),
bias=bias.contiguous(),
eps=self.eps,
)
class QuantEmbedding(QuantizationHijacker, nn.Embedding):
def __init__(self, *args, activation=None, **kwargs):
super().__init__(*args, activation=activation, **kwargs)
# NB: We should not (re-)quantize activations of this module, as it is a
# lookup table (=weights), which is already quantized
self.activation_quantizer = FP32Acts()
def run_forward(self, x, weight, bias, offsets=None):
return F.embedding(
input=x.contiguous(),
weight=weight.contiguous(),
padding_idx=self.padding_idx,
max_norm=self.max_norm,
norm_type=self.norm_type,
scale_grad_by_freq=self.scale_grad_by_freq,
sparse=self.sparse,
)
# Modules Map
module_map = {nn.Linear: QuantLinear, nn.LayerNorm: QuantLayerNorm, nn.Embedding: QuantEmbedding}
non_param_modules = (_AdaptiveAvgPoolNd, _AvgPoolNd)
def next_bn(module, i):
return len(module) > i + 1 and isinstance(module[i + 1], (nn.BatchNorm2d, nn.BatchNorm1d))
def get_act(module, i):
# Case 1: conv + act
if len(module) - i > 1 and isinstance(module[i + 1], tuple(activations_set)):
return module[i + 1], i + 1
# Case 2: conv + bn + act
if (
len(module) - i > 2
and next_bn(module, i)
and isinstance(module[i + 2], tuple(activations_set))
):
return module[i + 2], i + 2
# Case 3: conv + bn + X -> return false
# Case 4: conv + X -> return false
return None, None
def get_linear_args(module):
args = dict(
in_features=module.in_features,
out_features=module.out_features,
bias=module.bias is not None,
)
return args
def get_layernorm_args(module):
args = dict(normalized_shape=module.normalized_shape, eps=module.eps)
return args
def get_embedding_args(module):
args = dict(
num_embeddings=module.num_embeddings,
embedding_dim=module.embedding_dim,
padding_idx=module.padding_idx,
max_norm=module.max_norm,
norm_type=module.norm_type,
scale_grad_by_freq=module.scale_grad_by_freq,
sparse=module.sparse,
)
return args
def get_module_args(mod, act):
if isinstance(mod, nn.Linear):
kwargs = get_linear_args(mod)
elif isinstance(mod, nn.LayerNorm):
kwargs = get_layernorm_args(mod)
elif isinstance(mod, nn.Embedding):
kwargs = get_embedding_args(mod)
else:
raise ValueError
kwargs["activation"] = act
return kwargs
def quant_module(module, i, **quant_params):
act, _ = get_act(module, i)
modtype = module_map[type(module[i])]
kwargs = get_module_args(module[i], act)
new_module = modtype(**kwargs, **quant_params)
new_module.weight.data = module[i].weight.data.clone()
if module[i].bias is not None:
new_module.bias.data = module[i].bias.data.clone()
return new_module, i + int(bool(act)) + 1
def quantize_sequential(model, specials=None, tie_activation_quantizers=False, **quant_params):
specials = specials or dict()
i = 0
quant_modules = []
while i < len(model):
| # Copyright (c) 2023 Qualcomm Technologies, Inc.
# All Rights Reserved.
class QuantLinear(QuantizationHijacker, nn.Linear):
def run_forward(self, x, weight, bias, offsets=None):
return F.linear(x.contiguous(), weight.contiguous(), bias=bias)
class QuantizedActivationWrapper(QuantizedActivation):
"""
Wraps over a layer and quantized the activation.
It also allow for tying the input and output quantizer which is helpful
for layers such Average Pooling
"""
def __init__(
self,
layer,
*args,
tie_activation_quantizers=False,
input_quantizer: QuantizationManager = None,
**kwargs,
):
super().__init__(*args, **kwargs)
self.tie_activation_quantizers = tie_activation_quantizers
if input_quantizer:
assert isinstance(input_quantizer, QuantizationManager)
self.activation_quantizer = input_quantizer
self.layer = layer
def quantize_activations_no_range_update(self, x):
if self._quant_a:
return self.activation_quantizer.quantizer(x)
else:
return x
def forward(self, x):
x = self.layer(x)
if self.tie_activation_quantizers:
# The input activation quantizer is used to quantize the activation
# but without updating the quantization range
return self.quantize_activations_no_range_update(x)
else:
return self.quantize_activations(x)
def extra_repr(self):
return f"tie_activation_quantizers={self.tie_activation_quantizers}"
class QuantLayerNorm(QuantizationHijacker, nn.LayerNorm):
def run_forward(self, x, weight, bias, offsets=None):
return F.layer_norm(
input=x.contiguous(),
normalized_shape=self.normalized_shape,
weight=weight.contiguous(),
bias=bias.contiguous(),
eps=self.eps,
)
class QuantEmbedding(QuantizationHijacker, nn.Embedding):
def __init__(self, *args, activation=None, **kwargs):
super().__init__(*args, activation=activation, **kwargs)
# NB: We should not (re-)quantize activations of this module, as it is a
# lookup table (=weights), which is already quantized
self.activation_quantizer = FP32Acts()
def run_forward(self, x, weight, bias, offsets=None):
return F.embedding(
input=x.contiguous(),
weight=weight.contiguous(),
padding_idx=self.padding_idx,
max_norm=self.max_norm,
norm_type=self.norm_type,
scale_grad_by_freq=self.scale_grad_by_freq,
sparse=self.sparse,
)
# Modules Map
module_map = {nn.Linear: QuantLinear, nn.LayerNorm: QuantLayerNorm, nn.Embedding: QuantEmbedding}
non_param_modules = (_AdaptiveAvgPoolNd, _AvgPoolNd)
def next_bn(module, i):
return len(module) > i + 1 and isinstance(module[i + 1], (nn.BatchNorm2d, nn.BatchNorm1d))
def get_act(module, i):
# Case 1: conv + act
if len(module) - i > 1 and isinstance(module[i + 1], tuple(activations_set)):
return module[i + 1], i + 1
# Case 2: conv + bn + act
if (
len(module) - i > 2
and next_bn(module, i)
and isinstance(module[i + 2], tuple(activations_set))
):
return module[i + 2], i + 2
# Case 3: conv + bn + X -> return false
# Case 4: conv + X -> return false
return None, None
def get_linear_args(module):
args = dict(
in_features=module.in_features,
out_features=module.out_features,
bias=module.bias is not None,
)
return args
def get_layernorm_args(module):
args = dict(normalized_shape=module.normalized_shape, eps=module.eps)
return args
def get_embedding_args(module):
args = dict(
num_embeddings=module.num_embeddings,
embedding_dim=module.embedding_dim,
padding_idx=module.padding_idx,
max_norm=module.max_norm,
norm_type=module.norm_type,
scale_grad_by_freq=module.scale_grad_by_freq,
sparse=module.sparse,
)
return args
def get_module_args(mod, act):
if isinstance(mod, nn.Linear):
kwargs = get_linear_args(mod)
elif isinstance(mod, nn.LayerNorm):
kwargs = get_layernorm_args(mod)
elif isinstance(mod, nn.Embedding):
kwargs = get_embedding_args(mod)
else:
raise ValueError
kwargs["activation"] = act
return kwargs
def quant_module(module, i, **quant_params):
act, _ = get_act(module, i)
modtype = module_map[type(module[i])]
kwargs = get_module_args(module[i], act)
new_module = modtype(**kwargs, **quant_params)
new_module.weight.data = module[i].weight.data.clone()
if module[i].bias is not None:
new_module.bias.data = module[i].bias.data.clone()
return new_module, i + int(bool(act)) + 1
def quantize_sequential(model, specials=None, tie_activation_quantizers=False, **quant_params):
specials = specials or dict()
i = 0
quant_modules = []
while i < len(model): | if isinstance(model[i], QuantizedModule): | 2 | 2023-10-23 15:59:50+00:00 | 4k |
QgZhan/ESVAE | main_snn_ae.py | [
{
"identifier": "aboutCudaDevices",
"path": "utils.py",
"snippet": "class aboutCudaDevices():\r\n def __init__(self):\r\n pass\r\n\r\n def num_devices(self):\r\n \"\"\"Return number of devices connected.\"\"\"\r\n return cuda.Device.count()\r\n\r\n def devices(self):\r\n ... | import os
import os.path
import numpy as np
import logging
import argparse
import pycuda.driver as cuda
import torch
import torchvision
import svae_models.sae as sae
from torch.utils.tensorboard import SummaryWriter
from utils import aboutCudaDevices
from utils import AverageMeter
from utils import aboutCudaDevices
from datasets import load_dataset_snn
| 1,921 |
max_accuracy = 0
min_loss = 1000
def train(network, trainloader, opti, epoch, n_step):
loss_meter = AverageMeter()
network = network.train()
for batch_idx, (real_img, label) in enumerate(trainloader):
opti.zero_grad()
real_img = real_img.to(device)
spike_input = real_img.unsqueeze(-1).repeat(1, 1, 1, 1, n_step) # (N, C, H, W, T)
recons, latent = network(spike_input)
loss = network.loss_function(recons, real_img)
loss.backward()
opti.step()
loss_meter.update(loss.detach().cpu().item())
print(f'Train[{epoch}/{max_epoch}] [{batch_idx}/{len(trainloader)}] Loss: {loss_meter.avg}')
if batch_idx == len(trainloader)-1:
os.makedirs(f'checkpoint/{args.name}/imgs/train/', exist_ok=True)
torchvision.utils.save_image((real_img+1)/2, f'checkpoint/{args.name}/imgs/train/epoch{epoch}_input.png')
torchvision.utils.save_image((recons+1)/2, f'checkpoint/{args.name}/imgs/train/epoch{epoch}_recons.png')
writer.add_images('Train/input_img', (real_img+1)/2, epoch)
writer.add_images('Train/recons_img', (recons+1)/2, epoch)
logging.info(f"Train [{epoch}] Loss: {loss_meter.avg}")
writer.add_scalar('Train/loss', loss_meter.avg, epoch)
return loss_meter.avg
def test(network, trainloader, epoch, n_step):
loss_meter = AverageMeter()
network = network.eval()
with torch.no_grad():
for batch_idx, (real_img, label) in enumerate(trainloader):
real_img = real_img.to(device)
#normalized_img = normalized_img.to(device)
spike_input = real_img.unsqueeze(-1).repeat(1, 1, 1, 1, n_step) # (N, C, H, W, T)
recons, latent = network(spike_input)
loss = network.loss_function(recons, real_img)
loss_meter.update(loss.detach().cpu().item())
print(f'Test[{epoch}/{max_epoch}] [{batch_idx}/{len(trainloader)}] Loss: {loss_meter.avg}')
if batch_idx == len(trainloader)-1:
os.makedirs(f'checkpoint/{args.name}/imgs/test/', exist_ok=True)
torchvision.utils.save_image((real_img+1)/2, f'checkpoint/{args.name}/imgs/test/epoch{epoch}_input.png')
torchvision.utils.save_image((recons+1)/2, f'checkpoint/{args.name}/imgs/test/epoch{epoch}_recons.png')
writer.add_images('Test/input_img', (real_img+1)/2, epoch)
writer.add_images('Test/recons_img', (recons+1)/2, epoch)
logging.info(f"Test [{epoch}] Loss: {loss_meter.avg}")
writer.add_scalar('Test/loss', loss_meter.avg, epoch)
return loss_meter.avg
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('name', type=str)
parser.add_argument('-dataset', type=str, required=True)
parser.add_argument('-batch_size', type=int, default=128)
parser.add_argument('-latent_dim', type=int, default=128)
parser.add_argument('-n_step', type=int, default=16)
parser.add_argument('-checkpoint', action='store', dest='checkpoint', help='The path of checkpoint, if use checkpoint')
parser.add_argument('-device', type=int, default=0)
try:
args = parser.parse_args()
except:
parser.print_help()
exit(0)
if args.device is None:
device = torch.device("cuda:0")
else:
device = torch.device(f"cuda:{args.device}")
logging.info("dataset loading...")
if args.dataset == "MNIST":
data_path = os.path.expanduser("/data/zhan/CV_data/mnist")
in_channels = 1
input_size = 32
|
max_accuracy = 0
min_loss = 1000
def train(network, trainloader, opti, epoch, n_step):
loss_meter = AverageMeter()
network = network.train()
for batch_idx, (real_img, label) in enumerate(trainloader):
opti.zero_grad()
real_img = real_img.to(device)
spike_input = real_img.unsqueeze(-1).repeat(1, 1, 1, 1, n_step) # (N, C, H, W, T)
recons, latent = network(spike_input)
loss = network.loss_function(recons, real_img)
loss.backward()
opti.step()
loss_meter.update(loss.detach().cpu().item())
print(f'Train[{epoch}/{max_epoch}] [{batch_idx}/{len(trainloader)}] Loss: {loss_meter.avg}')
if batch_idx == len(trainloader)-1:
os.makedirs(f'checkpoint/{args.name}/imgs/train/', exist_ok=True)
torchvision.utils.save_image((real_img+1)/2, f'checkpoint/{args.name}/imgs/train/epoch{epoch}_input.png')
torchvision.utils.save_image((recons+1)/2, f'checkpoint/{args.name}/imgs/train/epoch{epoch}_recons.png')
writer.add_images('Train/input_img', (real_img+1)/2, epoch)
writer.add_images('Train/recons_img', (recons+1)/2, epoch)
logging.info(f"Train [{epoch}] Loss: {loss_meter.avg}")
writer.add_scalar('Train/loss', loss_meter.avg, epoch)
return loss_meter.avg
def test(network, trainloader, epoch, n_step):
loss_meter = AverageMeter()
network = network.eval()
with torch.no_grad():
for batch_idx, (real_img, label) in enumerate(trainloader):
real_img = real_img.to(device)
#normalized_img = normalized_img.to(device)
spike_input = real_img.unsqueeze(-1).repeat(1, 1, 1, 1, n_step) # (N, C, H, W, T)
recons, latent = network(spike_input)
loss = network.loss_function(recons, real_img)
loss_meter.update(loss.detach().cpu().item())
print(f'Test[{epoch}/{max_epoch}] [{batch_idx}/{len(trainloader)}] Loss: {loss_meter.avg}')
if batch_idx == len(trainloader)-1:
os.makedirs(f'checkpoint/{args.name}/imgs/test/', exist_ok=True)
torchvision.utils.save_image((real_img+1)/2, f'checkpoint/{args.name}/imgs/test/epoch{epoch}_input.png')
torchvision.utils.save_image((recons+1)/2, f'checkpoint/{args.name}/imgs/test/epoch{epoch}_recons.png')
writer.add_images('Test/input_img', (real_img+1)/2, epoch)
writer.add_images('Test/recons_img', (recons+1)/2, epoch)
logging.info(f"Test [{epoch}] Loss: {loss_meter.avg}")
writer.add_scalar('Test/loss', loss_meter.avg, epoch)
return loss_meter.avg
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('name', type=str)
parser.add_argument('-dataset', type=str, required=True)
parser.add_argument('-batch_size', type=int, default=128)
parser.add_argument('-latent_dim', type=int, default=128)
parser.add_argument('-n_step', type=int, default=16)
parser.add_argument('-checkpoint', action='store', dest='checkpoint', help='The path of checkpoint, if use checkpoint')
parser.add_argument('-device', type=int, default=0)
try:
args = parser.parse_args()
except:
parser.print_help()
exit(0)
if args.device is None:
device = torch.device("cuda:0")
else:
device = torch.device(f"cuda:{args.device}")
logging.info("dataset loading...")
if args.dataset == "MNIST":
data_path = os.path.expanduser("/data/zhan/CV_data/mnist")
in_channels = 1
input_size = 32
| train_loader, test_loader = load_dataset_snn.load_mnist(data_path, args.batch_size, input_size, True)
| 3 | 2023-10-23 07:33:27+00:00 | 4k |
iesl/softmax_CPR_recommend | run_hyper.py | [
{
"identifier": "HyperTuning",
"path": "recbole/trainer/hyper_tuning.py",
"snippet": "class HyperTuning(object):\n r\"\"\"HyperTuning Class is used to manage the parameter tuning process of recommender system models.\n Given objective funciton, parameters range and optimization algorithm, using Hy... | import argparse
from recbole.trainer import HyperTuning
from recbole.quick_start import objective_function | 2,441 | # -*- coding: utf-8 -*-
# @Time : 2020/7/24 15:57
# @Author : Shanlei Mu
# @Email : slmu@ruc.edu.cn
# @File : run_hyper.py
# UPDATE:
# @Time : 2020/8/20 21:17, 2020/8/29
# @Author : Zihan Lin, Yupeng Hou
# @Email : linzihan.super@foxmail.com, houyupeng@ruc.edu.cn
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config_files', type=str, default=None, help='fixed config files')
parser.add_argument('--params_file', type=str, default=None, help='parameters file')
parser.add_argument('--hyper_results', type=str, default=None, help='the result file name of hyperparameter search')
args, _ = parser.parse_known_args()
print(args.hyper_results)
#parameter_dict = {'neg_sampling': None}
# plz set algo='exhaustive' to use exhaustive search, in this case, max_evals is auto set
config_file_list = args.config_files.strip().split(' ') if args.config_files else None
| # -*- coding: utf-8 -*-
# @Time : 2020/7/24 15:57
# @Author : Shanlei Mu
# @Email : slmu@ruc.edu.cn
# @File : run_hyper.py
# UPDATE:
# @Time : 2020/8/20 21:17, 2020/8/29
# @Author : Zihan Lin, Yupeng Hou
# @Email : linzihan.super@foxmail.com, houyupeng@ruc.edu.cn
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config_files', type=str, default=None, help='fixed config files')
parser.add_argument('--params_file', type=str, default=None, help='parameters file')
parser.add_argument('--hyper_results', type=str, default=None, help='the result file name of hyperparameter search')
args, _ = parser.parse_known_args()
print(args.hyper_results)
#parameter_dict = {'neg_sampling': None}
# plz set algo='exhaustive' to use exhaustive search, in this case, max_evals is auto set
config_file_list = args.config_files.strip().split(' ') if args.config_files else None | hp = HyperTuning(objective_function, algo='exhaustive', | 1 | 2023-10-21 16:31:44+00:00 | 4k |
timapage/pyqt6-yolov8 | src/models/tracking/deep_sort/deep_sort.py | [
{
"identifier": "Extractor",
"path": "src/models/tracking/deep_sort/deep/feature_extractor.py",
"snippet": "class Extractor(object):\n def __init__(self, model_path, use_cuda=True):\n self.net = Net(reid=True)\n self.device = \"cuda\" if torch.cuda.is_available() and use_cuda else \"cpu... | import numpy as np
import torch
from .deep.feature_extractor import Extractor
from .sort.nn_matching import NearestNeighborDistanceMetric
from .sort.detection import Detection
from .sort.tracker import Tracker | 2,484 |
__all__ = ['DeepSort']
class DeepSort(object):
def __init__(self, model_path, max_dist=0.2, max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=100, use_cuda=True):
self.extractor = Extractor(model_path, use_cuda=use_cuda)
max_cosine_distance = max_dist
nn_budget = 100
|
__all__ = ['DeepSort']
class DeepSort(object):
def __init__(self, model_path, max_dist=0.2, max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=100, use_cuda=True):
self.extractor = Extractor(model_path, use_cuda=use_cuda)
max_cosine_distance = max_dist
nn_budget = 100 | metric = NearestNeighborDistanceMetric( | 1 | 2023-10-18 09:21:01+00:00 | 4k |
OthersideAI/self-operating-computer | operate/dialog.py | [
{
"identifier": "ModelNotRecognizedException",
"path": "operate/exceptions.py",
"snippet": "class ModelNotRecognizedException(Exception):\n \"\"\"Exception raised for unrecognized models.\n\n Attributes:\n model -- the unrecognized model\n message -- explanation of the error\n \"\... | import sys
import os
import platform
import asyncio
from prompt_toolkit.shortcuts import message_dialog
from prompt_toolkit import prompt
from operate.exceptions import ModelNotRecognizedException
from operate.prompts import USER_QUESTION
from operate.settings import Config
from operate.utils.style import (
ANSI_GREEN,
ANSI_RESET,
ANSI_BLUE,
ANSI_YELLOW,
ANSI_RED,
ANSI_BRIGHT_MAGENTA,
style,
)
from operate.utils.os import (
keyboard_type,
search,
click,
)
from operate.actions import get_next_action, summarize
from operate.utils.misc import parse_response
from whisper_mic import WhisperMic | 2,962 |
# Load configuration
config = Config()
def main(model, terminal_prompt, voice_mode=False):
"""
Main function for the Self-Operating Computer.
Parameters:
- model: The model used for generating responses.
- terminal_prompt: A string representing the prompt provided in the terminal.
- voice_mode: A boolean indicating whether to enable voice mode.
Returns:
None
"""
mic = None
# Initialize `WhisperMic`, if `voice_mode` is True
validation(model, voice_mode)
if voice_mode:
try:
# Initialize WhisperMic if import is successful
mic = WhisperMic()
except ImportError:
print(
"Voice mode requires the 'whisper_mic' module. Please install it using 'pip install -r requirements-audio.txt'"
)
sys.exit(1)
# Skip message dialog if prompt was given directly
if not terminal_prompt:
message_dialog(
title="Self-Operating Computer",
text="Ask a computer to do anything.",
style=style,
).run()
else:
print("Running direct prompt...")
print("SYSTEM", platform.system())
# Clear the console
if platform.system() == "Windows":
os.system("cls")
else:
print("\033c", end="")
if terminal_prompt: # Skip objective prompt if it was given as an argument
objective = terminal_prompt
elif voice_mode:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RESET} Listening for your command... (speak now)"
)
try:
objective = mic.listen()
except Exception as e:
print(f"{ANSI_RED}Error in capturing voice input: {e}{ANSI_RESET}")
return # Exit if voice input fails
else:
print(f"{ANSI_GREEN}[Self-Operating Computer]\n{ANSI_RESET}{USER_QUESTION}")
print(f"{ANSI_YELLOW}[User]{ANSI_RESET}")
objective = prompt(style=style)
assistant_message = {"role": "assistant", "content": USER_QUESTION}
user_message = {
"role": "user",
"content": f"Objective: {objective}",
}
messages = [assistant_message, user_message]
loop_count = 0
while True:
if config.debug:
print("[loop] messages before next action:\n\n\n", messages[1:])
try:
response = asyncio.run(get_next_action(model, messages, objective))
action = parse_response(response)
action_type = action.get("type")
action_detail = action.get("data")
except ModelNotRecognizedException as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] -> {e} {ANSI_RESET}"
)
break
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] -> {e} {ANSI_RESET}"
)
break
if action_type == "DONE":
print(
|
# Load configuration
config = Config()
def main(model, terminal_prompt, voice_mode=False):
"""
Main function for the Self-Operating Computer.
Parameters:
- model: The model used for generating responses.
- terminal_prompt: A string representing the prompt provided in the terminal.
- voice_mode: A boolean indicating whether to enable voice mode.
Returns:
None
"""
mic = None
# Initialize `WhisperMic`, if `voice_mode` is True
validation(model, voice_mode)
if voice_mode:
try:
# Initialize WhisperMic if import is successful
mic = WhisperMic()
except ImportError:
print(
"Voice mode requires the 'whisper_mic' module. Please install it using 'pip install -r requirements-audio.txt'"
)
sys.exit(1)
# Skip message dialog if prompt was given directly
if not terminal_prompt:
message_dialog(
title="Self-Operating Computer",
text="Ask a computer to do anything.",
style=style,
).run()
else:
print("Running direct prompt...")
print("SYSTEM", platform.system())
# Clear the console
if platform.system() == "Windows":
os.system("cls")
else:
print("\033c", end="")
if terminal_prompt: # Skip objective prompt if it was given as an argument
objective = terminal_prompt
elif voice_mode:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RESET} Listening for your command... (speak now)"
)
try:
objective = mic.listen()
except Exception as e:
print(f"{ANSI_RED}Error in capturing voice input: {e}{ANSI_RESET}")
return # Exit if voice input fails
else:
print(f"{ANSI_GREEN}[Self-Operating Computer]\n{ANSI_RESET}{USER_QUESTION}")
print(f"{ANSI_YELLOW}[User]{ANSI_RESET}")
objective = prompt(style=style)
assistant_message = {"role": "assistant", "content": USER_QUESTION}
user_message = {
"role": "user",
"content": f"Objective: {objective}",
}
messages = [assistant_message, user_message]
loop_count = 0
while True:
if config.debug:
print("[loop] messages before next action:\n\n\n", messages[1:])
try:
response = asyncio.run(get_next_action(model, messages, objective))
action = parse_response(response)
action_type = action.get("type")
action_detail = action.get("data")
except ModelNotRecognizedException as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] -> {e} {ANSI_RESET}"
)
break
except Exception as e:
print(
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_RED}[Error] -> {e} {ANSI_RESET}"
)
break
if action_type == "DONE":
print( | f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BLUE} Objective complete {ANSI_RESET}" | 3 | 2023-11-04 03:13:45+00:00 | 4k |
netease-youdao/EmotiVoice | demo_page_databaker.py | [
{
"identifier": "g2p_cn_en",
"path": "frontend.py",
"snippet": "def g2p_cn_en(text, g2p, lexicon):\ndef contains_chinese(text):"
},
{
"identifier": "JETSGenerator",
"path": "models/prompt_tts_modified/jets.py",
"snippet": "class JETSGenerator(nn.Module):\n def __init__(self, config) -... | import streamlit as st
import os, glob
import numpy as np
import torch
import re
import base64
from yacs import config as CONFIG
from frontend import g2p_cn_en, ROOT_DIR, read_lexicon, G2p
from exp.DataBaker.config.config import Config
from models.prompt_tts_modified.jets import JETSGenerator
from models.prompt_tts_modified.simbert import StyleEncoder
from transformers import AutoTokenizer
from pathlib import Path | 1,692 | # Copyright 2023, YOUDAO
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
MAX_WAV_VALUE = 32768.0
config = Config()
def create_download_link():
pdf_path = Path("EmotiVoice_UserAgreement_易魔声用户协议.pdf")
base64_pdf = base64.b64encode(pdf_path.read_bytes()).decode("utf-8") # val looks like b'...'
return f'<a href="data:application/octet-stream;base64,{base64_pdf}" download="EmotiVoice_UserAgreement_易魔声用户协议.pdf.pdf">EmotiVoice_UserAgreement_易魔声用户协议.pdf</a>'
html=create_download_link()
st.set_page_config(
page_title="demo page",
page_icon="📕",
)
st.write("# Text-To-Speech")
st.markdown(f"""
### How to use:
- Simply select a **Speaker ID**, type in the **text** you want to convert and the emotion **Prompt**, like a single word or even a sentence. Then click on the **Synthesize** button below to start voice synthesis.
- You can download the audio by clicking on the vertical three points next to the displayed audio widget.
- For more information on **'Speaker ID'**, please consult the [EmotiVoice voice wiki page](https://github.com/netease-youdao/EmotiVoice/tree/main/data/youdao/text)
- This interactive demo page is provided under the {html} file. The audio is synthesized by AI. 音频由AI合成,仅供参考。
""", unsafe_allow_html=True)
def scan_checkpoint(cp_dir, prefix, c=8):
pattern = os.path.join(cp_dir, prefix + '?'*c)
cp_list = glob.glob(pattern)
if len(cp_list) == 0:
return None
return sorted(cp_list)[-1]
@st.cache_resource
def get_models():
am_checkpoint_path = scan_checkpoint(f'{config.output_directory}/ckpt', 'g_')
style_encoder_checkpoint_path = config.style_encoder_ckpt
with open(config.model_config_path, 'r') as fin:
conf = CONFIG.load_cfg(fin)
conf.n_vocab = config.n_symbols
conf.n_speaker = config.speaker_n_labels
style_encoder = StyleEncoder(config)
model_CKPT = torch.load(style_encoder_checkpoint_path, map_location="cpu")
model_ckpt = {}
for key, value in model_CKPT['model'].items():
new_key = key[7:]
model_ckpt[new_key] = value
style_encoder.load_state_dict(model_ckpt, strict=False)
| # Copyright 2023, YOUDAO
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
MAX_WAV_VALUE = 32768.0
config = Config()
def create_download_link():
pdf_path = Path("EmotiVoice_UserAgreement_易魔声用户协议.pdf")
base64_pdf = base64.b64encode(pdf_path.read_bytes()).decode("utf-8") # val looks like b'...'
return f'<a href="data:application/octet-stream;base64,{base64_pdf}" download="EmotiVoice_UserAgreement_易魔声用户协议.pdf.pdf">EmotiVoice_UserAgreement_易魔声用户协议.pdf</a>'
html=create_download_link()
st.set_page_config(
page_title="demo page",
page_icon="📕",
)
st.write("# Text-To-Speech")
st.markdown(f"""
### How to use:
- Simply select a **Speaker ID**, type in the **text** you want to convert and the emotion **Prompt**, like a single word or even a sentence. Then click on the **Synthesize** button below to start voice synthesis.
- You can download the audio by clicking on the vertical three points next to the displayed audio widget.
- For more information on **'Speaker ID'**, please consult the [EmotiVoice voice wiki page](https://github.com/netease-youdao/EmotiVoice/tree/main/data/youdao/text)
- This interactive demo page is provided under the {html} file. The audio is synthesized by AI. 音频由AI合成,仅供参考。
""", unsafe_allow_html=True)
def scan_checkpoint(cp_dir, prefix, c=8):
pattern = os.path.join(cp_dir, prefix + '?'*c)
cp_list = glob.glob(pattern)
if len(cp_list) == 0:
return None
return sorted(cp_list)[-1]
@st.cache_resource
def get_models():
am_checkpoint_path = scan_checkpoint(f'{config.output_directory}/ckpt', 'g_')
style_encoder_checkpoint_path = config.style_encoder_ckpt
with open(config.model_config_path, 'r') as fin:
conf = CONFIG.load_cfg(fin)
conf.n_vocab = config.n_symbols
conf.n_speaker = config.speaker_n_labels
style_encoder = StyleEncoder(config)
model_CKPT = torch.load(style_encoder_checkpoint_path, map_location="cpu")
model_ckpt = {}
for key, value in model_CKPT['model'].items():
new_key = key[7:]
model_ckpt[new_key] = value
style_encoder.load_state_dict(model_ckpt, strict=False) | generator = JETSGenerator(conf).to(DEVICE) | 1 | 2023-11-08 10:15:27+00:00 | 4k |
daveshap/OpenAI_Agent_Swarm | agents/tool_maker/unit_manager.py | [
{
"identifier": "AssistantManager",
"path": "agents/tool_maker/assistant_manager.py",
"snippet": "class AssistantManager:\n\n def __init__(self, client):\n self.client = client\n self.assistant = None\n self.agent_builder = AgentBuilder(client=self.client)\n Path(__file__)... | from agents.tool_maker.assistant_manager import AssistantManager
from agents.tool_maker.chat_manager import ChatManager
from shared.openai_config import get_openai_client | 2,723 |
class Unit:
"""
A class which creates and exposes chat functionality for a Unit Agent.
A Unit is a first prototype for a Minmium Viable Agent (MVA).
A `Unit` is two `Assistant`s in a symbiotic relationship.
One `Assistant` is the Interface with a thread sharing input with the contents passed via the `chat` method,
the other `Assistant` is a functional one which shares a thread with `submit_tool` requests during runs and is responsible for writing python functions.
:param AssistantManager assistant_manager: Creates and retrieves different `Assistant` types
:param ChatManager chat_manager: provides functionality for managing `Threads`
:param Assistant interface_assistant: talks with `chat` method
:param Assistant functional_assistant: writes python functions when `OpenAI.beta.threads.runs.submit_tools` is called in `chat`
:param Thread interface_thread: `Thread` between `interface_assistant` and `chat`
:param Thread functional_thread: `Thread` between `functional_assistant` and `OpenAI.beta.threads.runs.submit_tools`
:returns: this is retured
"""
def __init__(self, client):
"""
Instantiates a Unit object
:param Client client: OpenAI instance
"""
self.assistant_manager = AssistantManager(client=client)
|
class Unit:
"""
A class which creates and exposes chat functionality for a Unit Agent.
A Unit is a first prototype for a Minmium Viable Agent (MVA).
A `Unit` is two `Assistant`s in a symbiotic relationship.
One `Assistant` is the Interface with a thread sharing input with the contents passed via the `chat` method,
the other `Assistant` is a functional one which shares a thread with `submit_tool` requests during runs and is responsible for writing python functions.
:param AssistantManager assistant_manager: Creates and retrieves different `Assistant` types
:param ChatManager chat_manager: provides functionality for managing `Threads`
:param Assistant interface_assistant: talks with `chat` method
:param Assistant functional_assistant: writes python functions when `OpenAI.beta.threads.runs.submit_tools` is called in `chat`
:param Thread interface_thread: `Thread` between `interface_assistant` and `chat`
:param Thread functional_thread: `Thread` between `functional_assistant` and `OpenAI.beta.threads.runs.submit_tools`
:returns: this is retured
"""
def __init__(self, client):
"""
Instantiates a Unit object
:param Client client: OpenAI instance
"""
self.assistant_manager = AssistantManager(client=client) | self.chat_manager = ChatManager(client=client) | 1 | 2023-11-07 23:12:05+00:00 | 4k |
S-LoRA/S-LoRA | slora/models/llama/layer_infer/post_layer_infer.py | [
{
"identifier": "LlamaPreAndPostLayerWeight",
"path": "slora/models/llama/layer_weights/pre_and_post_layer_weight.py",
"snippet": "class LlamaPreAndPostLayerWeight(PreAndPostLayerWeight):\n def __init__(self, tp_rank, world_size, data_type, network_config, mode):\n super().__init__(tp_rank, wo... | import torch
import torch.functional as F
import torch.distributed as dist
import numpy as np
from slora.models.llama.layer_weights.pre_and_post_layer_weight import LlamaPreAndPostLayerWeight
from einops import rearrange
from slora.models.llama.infer_struct import LlamaInferStateInfo
from slora.models.llama.triton_kernel.rmsnorm import rmsnorm_forward
from slora.common.basemodel import PostLayerInferTpl | 1,649 |
class LlamaPostLayerInfer(PostLayerInferTpl):
"""
"""
def __init__(self, tp_rank, world_size, network_config, mode):
super().__init__(tp_rank, world_size, network_config, mode)
self.eps_ = network_config["rms_norm_eps"]
self.vocab_size_ = network_config["vocab_size"]
self.embed_dim_ = network_config["n_embed"]
return
|
class LlamaPostLayerInfer(PostLayerInferTpl):
"""
"""
def __init__(self, tp_rank, world_size, network_config, mode):
super().__init__(tp_rank, world_size, network_config, mode)
self.eps_ = network_config["rms_norm_eps"]
self.vocab_size_ = network_config["vocab_size"]
self.embed_dim_ = network_config["n_embed"]
return
| def _norm(self, input, infer_state, layer_weight:LlamaPreAndPostLayerWeight) -> torch.Tensor: | 0 | 2023-11-05 04:08:36+00:00 | 4k |
Yuliang-Liu/Monkey | data_generation/grit/grit/modeling/backbone/vit.py | [
{
"identifier": "PatchEmbed",
"path": "data_generation/grit/grit/modeling/backbone/utils.py",
"snippet": "class PatchEmbed(nn.Module):\n \"\"\"\n Image to Patch Embedding.\n \"\"\"\n\n def __init__(\n self, kernel_size=(16, 16), stride=(16, 16), padding=(0, 0), in_chans=3, embed_dim=7... | import logging
import math
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn as nn
import sys
import torch.utils.checkpoint as checkpoint
from functools import partial
from detectron2.layers import CNNBlockBase, Conv2d, get_norm
from detectron2.modeling.backbone.build import BACKBONE_REGISTRY
from detectron2.layers import ShapeSpec
from centernet.modeling.backbone.fpn_p5 import LastLevelP6P7_P5
from timm.models.layers import DropPath, Mlp, trunc_normal_
from detectron2.modeling.backbone.backbone import Backbone
from .utils import (
PatchEmbed,
add_decomposed_rel_pos,
get_abs_pos,
window_partition,
window_unpartition,
) | 3,506 | bottleneck_channels,
norm="LN",
act_layer=nn.GELU,
):
"""
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
bottleneck_channels (int): number of output channels for the 3x3
"bottleneck" conv layers.
norm (str or callable): normalization for all conv layers.
See :func:`layers.get_norm` for supported format.
act_layer (callable): activation for all conv layers.
"""
super().__init__(in_channels, out_channels, 1)
self.conv1 = Conv2d(in_channels, bottleneck_channels, 1, bias=False)
self.norm1 = get_norm(norm, bottleneck_channels)
self.act1 = act_layer()
self.conv2 = Conv2d(
bottleneck_channels,
bottleneck_channels,
3,
padding=1,
bias=False,
)
self.norm2 = get_norm(norm, bottleneck_channels)
self.act2 = act_layer()
self.conv3 = Conv2d(bottleneck_channels, out_channels, 1, bias=False)
self.norm3 = get_norm(norm, out_channels)
for layer in [self.conv1, self.conv2, self.conv3]:
weight_init.c2_msra_fill(layer)
for layer in [self.norm1, self.norm2]:
layer.weight.data.fill_(1.0)
layer.bias.data.zero_()
# zero init last norm layer.
self.norm3.weight.data.zero_()
self.norm3.bias.data.zero_()
def forward(self, x):
out = x
for layer in self.children():
out = layer(out)
out = x + out
return out
class Block(nn.Module):
"""Transformer blocks with support of window attention and residual propagation blocks"""
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=True,
drop_path=0.0,
norm_layer=nn.LayerNorm,
act_layer=nn.GELU,
use_rel_pos=False,
rel_pos_zero_init=True,
window_size=0,
use_residual_block=False,
input_size=None,
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks. If it equals 0, then not
use window attention.
use_residual_block (bool): If True, use a residual block after the MLP block.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
input_size=input_size if window_size == 0 else (window_size, window_size),
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer)
self.window_size = window_size
self.use_residual_block = use_residual_block
if use_residual_block:
# Use a residual block with bottleneck channel as dim // 2
self.residual = ResBottleneckBlock(
in_channels=dim,
out_channels=dim,
bottleneck_channels=dim // 2,
norm="LN",
act_layer=act_layer,
)
def forward(self, x):
shortcut = x
x = self.norm1(x)
# Window partition
if self.window_size > 0:
H, W = x.shape[1], x.shape[2]
| # Modified by Jialian Wu from https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py
sys.path.insert(0, 'models/grit_src/third_party/CenterNet2/projects/CenterNet2/')
logger = logging.getLogger(__name__)
__all__ = ["ViT"]
class Attention(nn.Module):
"""Multi-head Attention block with relative position embeddings."""
def __init__(
self,
dim,
num_heads=8,
qkv_bias=True,
use_rel_pos=False,
rel_pos_zero_init=True,
input_size=None,
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads.
qkv_bias (bool: If True, add a learnable bias to query, key, value.
rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.proj = nn.Linear(dim, dim)
self.use_rel_pos = use_rel_pos
if self.use_rel_pos:
# initialize relative positional embeddings
self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
if not rel_pos_zero_init:
trunc_normal_(self.rel_pos_h, std=0.02)
trunc_normal_(self.rel_pos_w, std=0.02)
def forward(self, x):
B, H, W, _ = x.shape
# qkv with shape (3, B, nHead, H * W, C)
qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
# q, k, v with shape (B * nHead, H * W, C)
q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
attn = (q * self.scale) @ k.transpose(-2, -1)
if self.use_rel_pos:
attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
attn = attn.softmax(dim=-1)
x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
x = self.proj(x)
return x
class ResBottleneckBlock(CNNBlockBase):
"""
The standard bottleneck residual block without the last activation layer.
It contains 3 conv layers with kernels 1x1, 3x3, 1x1.
"""
def __init__(
self,
in_channels,
out_channels,
bottleneck_channels,
norm="LN",
act_layer=nn.GELU,
):
"""
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
bottleneck_channels (int): number of output channels for the 3x3
"bottleneck" conv layers.
norm (str or callable): normalization for all conv layers.
See :func:`layers.get_norm` for supported format.
act_layer (callable): activation for all conv layers.
"""
super().__init__(in_channels, out_channels, 1)
self.conv1 = Conv2d(in_channels, bottleneck_channels, 1, bias=False)
self.norm1 = get_norm(norm, bottleneck_channels)
self.act1 = act_layer()
self.conv2 = Conv2d(
bottleneck_channels,
bottleneck_channels,
3,
padding=1,
bias=False,
)
self.norm2 = get_norm(norm, bottleneck_channels)
self.act2 = act_layer()
self.conv3 = Conv2d(bottleneck_channels, out_channels, 1, bias=False)
self.norm3 = get_norm(norm, out_channels)
for layer in [self.conv1, self.conv2, self.conv3]:
weight_init.c2_msra_fill(layer)
for layer in [self.norm1, self.norm2]:
layer.weight.data.fill_(1.0)
layer.bias.data.zero_()
# zero init last norm layer.
self.norm3.weight.data.zero_()
self.norm3.bias.data.zero_()
def forward(self, x):
out = x
for layer in self.children():
out = layer(out)
out = x + out
return out
class Block(nn.Module):
"""Transformer blocks with support of window attention and residual propagation blocks"""
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=True,
drop_path=0.0,
norm_layer=nn.LayerNorm,
act_layer=nn.GELU,
use_rel_pos=False,
rel_pos_zero_init=True,
window_size=0,
use_residual_block=False,
input_size=None,
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks. If it equals 0, then not
use window attention.
use_residual_block (bool): If True, use a residual block after the MLP block.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
input_size=input_size if window_size == 0 else (window_size, window_size),
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer)
self.window_size = window_size
self.use_residual_block = use_residual_block
if use_residual_block:
# Use a residual block with bottleneck channel as dim // 2
self.residual = ResBottleneckBlock(
in_channels=dim,
out_channels=dim,
bottleneck_channels=dim // 2,
norm="LN",
act_layer=act_layer,
)
def forward(self, x):
shortcut = x
x = self.norm1(x)
# Window partition
if self.window_size > 0:
H, W = x.shape[1], x.shape[2] | x, pad_hw = window_partition(x, self.window_size) | 3 | 2023-11-09 14:31:48+00:00 | 4k |
disler/multi-agent-postgres-data-analytics | postgres_da_ai_agent/agents/agents.py | [
{
"identifier": "PostgresAgentInstruments",
"path": "postgres_da_ai_agent/agents/instruments.py",
"snippet": "class PostgresAgentInstruments(AgentInstruments):\n \"\"\"\n Unified Toolset for the Postgres Data Analytics Multi-Agent System\n\n Advantages:\n - All agents have access to the ... | from typing import Optional, List, Dict, Any
from postgres_da_ai_agent.agents.instruments import PostgresAgentInstruments
from postgres_da_ai_agent.modules import orchestrator
from postgres_da_ai_agent.agents import agent_config
import autogen
import guidance | 3,173 | sr_data_analyst = autogen.AssistantAgent(
name="Sr_Data_Analyst",
llm_config=agent_config.run_sql_config,
system_message=SR_DATA_ANALYST_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
function_map={
"run_sql": instruments.run_sql,
},
)
return [
user_proxy,
data_engineer,
sr_data_analyst,
]
def build_data_viz_team(instruments: PostgresAgentInstruments):
# admin user proxy agent - takes in the prompt and manages the group chat
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
# text report analyst - writes a summary report of the results and saves them to a local text file
text_report_analyst = autogen.AssistantAgent(
name="Text_Report_Analyst",
llm_config=agent_config.write_file_config,
system_message=TEXT_REPORT_ANALYST_PROMPT,
human_input_mode="NEVER",
function_map={
"write_file": instruments.write_file,
},
)
# json report analyst - writes a summary report of the results and saves them to a local json file
json_report_analyst = autogen.AssistantAgent(
name="Json_Report_Analyst",
llm_config=agent_config.write_json_file_config,
system_message=JSON_REPORT_ANALYST_PROMPT,
human_input_mode="NEVER",
function_map={
"write_json_file": instruments.write_json_file,
},
)
yaml_report_analyst = autogen.AssistantAgent(
name="Yml_Report_Analyst",
llm_config=agent_config.write_yaml_file_config,
system_message=YML_REPORT_ANALYST_PROMPT,
human_input_mode="NEVER",
function_map={
"write_yml_file": instruments.write_yml_file,
},
)
return [
user_proxy,
text_report_analyst,
json_report_analyst,
yaml_report_analyst,
]
def build_scrum_master_team(instruments: PostgresAgentInstruments):
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
scrum_agent = DefensiveScrumMasterAgent(
name="Scrum_Master",
llm_config=agent_config.base_config,
system_message=GUIDANCE_SCRUM_MASTER_SQL_NLQ_PROMPT,
human_input_mode="NEVER",
)
return [user_proxy, scrum_agent]
def build_insights_team(instruments: PostgresAgentInstruments):
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
insights_agent = InsightsAgent(
name="Insights",
llm_config=agent_config.base_config,
system_message=DATA_INSIGHTS_GUIDANCE_PROMPT,
human_input_mode="NEVER",
)
insights_data_reporter = autogen.AssistantAgent(
name="Insights_Data_Reporter",
llm_config=agent_config.write_innovation_file_config,
system_message=INSIGHTS_FILE_REPORTER_PROMPT,
human_input_mode="NEVER",
function_map={
"write_innovation_file": instruments.write_innovation_file,
},
)
return [user_proxy, insights_agent, insights_data_reporter]
# ------------------------ ORCHESTRATION ------------------------
def build_team_orchestrator(
team: str,
agent_instruments: PostgresAgentInstruments,
validate_results: callable = None,
|
# ------------------------ PROMPTS ------------------------
USER_PROXY_PROMPT = "A human admin. Interact with the Product Manager to discuss the plan. Plan execution needs to be approved by this admin."
DATA_ENGINEER_PROMPT = "A Data Engineer. Generate the initial SQL based on the requirements provided. Send it to the Sr Data Analyst to be executed. "
SR_DATA_ANALYST_PROMPT = "Sr Data Analyst. You run the SQL query using the run_sql function, send the raw response to the data viz team. You use the run_sql function exclusively."
GUIDANCE_SCRUM_MASTER_SQL_NLQ_PROMPT = """
Is the following block of text a SQL Natural Language Query (NLQ)? Please rank from 1 to 5, where:
1: Definitely not NLQ
2: Likely not NLQ
3: Neutral / Unsure
4: Likely NLQ
5: Definitely NLQ
Return the rank as a number exclusively using the rank variable to be casted as an integer.
Block of Text: {{potential_nlq}}
{{#select "rank" logprobs='logprobs'}} 1{{or}} 2{{or}} 3{{or}} 4{{or}} 5{{/select}}
"""
DATA_INSIGHTS_GUIDANCE_PROMPT = """
You're a data innovator. You analyze SQL databases table structure and generate 3 novel insights for your team to reflect on and query.
Format your insights in JSON format.
```json
[{{#geneach 'insight' num_iterations=3 join=','}}
{
"insight": "{{gen 'insight' temperature=0.7}}",
"actionable_business_value": "{{gen 'actionable_value' temperature=0.7}}",
"sql": "{{gen 'new_query' temperature=0.7}}"
}
{{/geneach}}]
```"""
INSIGHTS_FILE_REPORTER_PROMPT = "You're a data reporter. You write json data you receive directly into a file using the write_innovation_file function."
# unused prompts
COMPLETION_PROMPT = "If everything looks good, respond with APPROVED"
PRODUCT_MANAGER_PROMPT = (
"Product Manager. Validate the response to make sure it's correct"
+ COMPLETION_PROMPT
)
TEXT_REPORT_ANALYST_PROMPT = "Text File Report Analyst. You exclusively use the write_file function on a summarized report."
JSON_REPORT_ANALYST_PROMPT = "Json Report Analyst. You exclusively use the write_json_file function on the report."
YML_REPORT_ANALYST_PROMPT = "Yaml Report Analyst. You exclusively use the write_yml_file function on the report."
# ------------------------ BUILD AGENT TEAMS ------------------------
def build_data_eng_team(instruments: PostgresAgentInstruments):
"""
Build a team of agents that can generate, execute, and report an SQL query
"""
# create a set of agents with specific roles
# admin user proxy agent - takes in the prompt and manages the group chat
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
# data engineer agent - generates the sql query
data_engineer = autogen.AssistantAgent(
name="Engineer",
llm_config=agent_config.base_config,
system_message=DATA_ENGINEER_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
sr_data_analyst = autogen.AssistantAgent(
name="Sr_Data_Analyst",
llm_config=agent_config.run_sql_config,
system_message=SR_DATA_ANALYST_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
function_map={
"run_sql": instruments.run_sql,
},
)
return [
user_proxy,
data_engineer,
sr_data_analyst,
]
def build_data_viz_team(instruments: PostgresAgentInstruments):
# admin user proxy agent - takes in the prompt and manages the group chat
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
# text report analyst - writes a summary report of the results and saves them to a local text file
text_report_analyst = autogen.AssistantAgent(
name="Text_Report_Analyst",
llm_config=agent_config.write_file_config,
system_message=TEXT_REPORT_ANALYST_PROMPT,
human_input_mode="NEVER",
function_map={
"write_file": instruments.write_file,
},
)
# json report analyst - writes a summary report of the results and saves them to a local json file
json_report_analyst = autogen.AssistantAgent(
name="Json_Report_Analyst",
llm_config=agent_config.write_json_file_config,
system_message=JSON_REPORT_ANALYST_PROMPT,
human_input_mode="NEVER",
function_map={
"write_json_file": instruments.write_json_file,
},
)
yaml_report_analyst = autogen.AssistantAgent(
name="Yml_Report_Analyst",
llm_config=agent_config.write_yaml_file_config,
system_message=YML_REPORT_ANALYST_PROMPT,
human_input_mode="NEVER",
function_map={
"write_yml_file": instruments.write_yml_file,
},
)
return [
user_proxy,
text_report_analyst,
json_report_analyst,
yaml_report_analyst,
]
def build_scrum_master_team(instruments: PostgresAgentInstruments):
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
scrum_agent = DefensiveScrumMasterAgent(
name="Scrum_Master",
llm_config=agent_config.base_config,
system_message=GUIDANCE_SCRUM_MASTER_SQL_NLQ_PROMPT,
human_input_mode="NEVER",
)
return [user_proxy, scrum_agent]
def build_insights_team(instruments: PostgresAgentInstruments):
user_proxy = autogen.UserProxyAgent(
name="Admin",
system_message=USER_PROXY_PROMPT,
code_execution_config=False,
human_input_mode="NEVER",
)
insights_agent = InsightsAgent(
name="Insights",
llm_config=agent_config.base_config,
system_message=DATA_INSIGHTS_GUIDANCE_PROMPT,
human_input_mode="NEVER",
)
insights_data_reporter = autogen.AssistantAgent(
name="Insights_Data_Reporter",
llm_config=agent_config.write_innovation_file_config,
system_message=INSIGHTS_FILE_REPORTER_PROMPT,
human_input_mode="NEVER",
function_map={
"write_innovation_file": instruments.write_innovation_file,
},
)
return [user_proxy, insights_agent, insights_data_reporter]
# ------------------------ ORCHESTRATION ------------------------
def build_team_orchestrator(
team: str,
agent_instruments: PostgresAgentInstruments,
validate_results: callable = None, | ) -> orchestrator.Orchestrator: | 1 | 2023-11-04 20:15:46+00:00 | 4k |
OpenBMB/ProAgent | ProAgent/running_recorder.py | [
{
"identifier": "CONFIG",
"path": "ProAgent/config.py",
"snippet": "CONFIG = RPAgentConfig.get_default_config()"
},
{
"identifier": "ENVIRONMENT",
"path": "ProAgent/router/utils.py",
"snippet": "class ENVIRONMENT(Enum):\n '''\n 决定了 record cache 的访问形式\n - Development:不访问缓存,从头开始\n... | import os
import time
import json
from colorama import Fore
from termcolor import colored
from ProAgent.config import CONFIG
from ProAgent.router.utils import ENVIRONMENT
from ProAgent.utils import Action
from ProAgent.loggers.logs import logger | 2,556 | Fore.RED,
record_dir,
)
self.newly_start = False
for dir_name in os.listdir(record_dir):
if dir_name == "LLM_inout_pair":
inout_pair_list = os.listdir(os.path.join(record_dir,dir_name))
inout_pair_list.sort()
for file_name in inout_pair_list:
with open(os.path.join(record_dir,dir_name,file_name), "r", encoding="utf-8") as reader:
llm_pair = json.load(reader)
self.llm_record_cache.append(llm_pair)
elif dir_name == "meta.meta":
with open(os.path.join(record_dir, "meta.meta"), "r", encoding="utf-8") as reader:
tool_call_log = json.load(reader)
def regist_llm_inout(self, base_kwargs, messages, functions, function_call, stop, other_args, output_data, uuid=""):
"""
Registers the LLM input and output data for the specified function call.
Args:
base_kwargs (dict): The base keyword arguments for the function call.
messages (list): The list of messages associated with the function call.
functions (list): The list of functions called during the function call.
function_call (str): The function call being registered.
stop (bool): A flag indicating whether the function call should stop.
other_args (list): The list of other arguments for the function call.
output_data (Any): The output data for the function call.
uuid (str, optional): The UUID associated with the function call. Defaults to "".
Returns:
None
Raises:
None
"""
with open(os.path.join(self.record_root_dir, "LLM_inout_pair", f"{self.llm_interface_id:05d}.json"), "w", encoding="utf-8") as writer:
llm_inout_record = {
"input": {
"base_kwargs": dump_common_things(base_kwargs),
"messages":dump_common_things(messages),
"functions":dump_common_things(functions),
"function_call":dump_common_things(function_call),
"stop":dump_common_things(stop),
"other_args":dump_common_things(other_args),
# 'uuid': dump_common_things(uuid)
},
"output": dump_common_things(output_data),
"llm_interface_id": self.llm_interface_id,
}
json.dump(llm_inout_record,writer,indent=2, ensure_ascii=False)
self.llm_server_cache.append(llm_inout_record)
self.llm_interface_id += 1
self.save_meta()
def query_llm_inout(self, restrict_cache_query, base_kwargs, messages, functions, function_call, stop, other_args, uuid=""):
"""
Query the LLM server for input and output data based on the given parameters.
Parameters:
- restrict_cache_query (bool): Whether to restrict the cache query.
- base_kwargs (dict): A dictionary of base keyword arguments.
- messages (list): A list of messages.
- functions (list): A list of functions.
- function_call (dict): A dictionary representing the function call.
- stop (bool): Whether to stop the query.
- other_args (dict): A dictionary of other arguments.
- uuid (str): A string representing the UUID (optional).
Returns:
- object: The output data from the LLM server, or None if not found.
"""
if CONFIG.environment == ENVIRONMENT.Development or self.newly_start:
self.is_cached = False
return None
elif CONFIG.environment == ENVIRONMENT.Refine:
input_data = {
"base_kwargs": dump_common_things(base_kwargs),
"messages":dump_common_things(messages),
"functions":dump_common_things(functions),
"function_call":dump_common_things(function_call),
"stop":dump_common_things(stop),
"other_args":dump_common_things(other_args),
}
for cache in self.llm_record_cache:
# compare user messages only
input_data_user_messages = [item for item in input_data['messages'] if item['role'] == 'user']
cache_data_user_messages = [item for item in cache["input"]['messages'] if item['role'] == 'user']
if input_data_user_messages == cache_data_user_messages:
if restrict_cache_query and self.llm_interface_id != cache["llm_interface_id"]:
continue
logger.typewriter_log(
f"get a llm_server response from Record {cache['llm_interface_id']}",
Fore.RED,
)
self.is_cached = True
return cache["output"]
self.is_cached = False
return None
elif CONFIG.environment == ENVIRONMENT.Production:
if self.llm_interface_id < len(self.llm_record_cache):
logger.typewriter_log(
"get a llm_server response from Record",
Fore.RED,
)
self.is_cached = True
return self.llm_record_cache[self.llm_interface_id]['output']
else:
self.is_cached = False
return None
else:
self.is_cached = False
return None
|
def dump_common_things(object):
"""
Generates a function comment for the given function body.
Args:
object: The object to be processed.
Returns:
The processed object.
"""
if type(object) in [str,int,float, bool]:
return object
if type(object) == dict:
return {dump_common_things(key): dump_common_things(value) for key,value in object.items()}
if type(object) == list:
return [dump_common_things(cont) for cont in object]
method = getattr(object, 'to_json', None)
if callable(method):
return method()
class RunningRecoder():
def __init__(self, record_base_dir = "./records"):
"""
Initializes the object with the given record base directory.
Parameters:
record_base_dir (str): The base directory for the records. Defaults to "./records".
Returns:
None
"""
self.llm_record_cache = [] # Get cached records
self.llm_interface_id = 0
self.llm_server_cache = [] # Runtime records
self.tool_call_id = 0
self.tool_call_cache = []
self.is_cached = True # Assume to be true at first
self.newly_start = True
now = int(round(time.time()*1000))
strip = time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime(now/1000))
self.record_root_dir = os.path.join(record_base_dir,strip)
os.makedirs(self.record_root_dir,exist_ok=True)
print(colored(f"Recorder Mode: {CONFIG.environment.name}", color='yellow'))
for subdir_name in ["LLM_inout_pair","tool_call_logs"]:
os.makedirs(os.path.join(self.record_root_dir,subdir_name),exist_ok=True)
def save_meta(self):
"""
Saves the meta information of the record.
This function writes the meta information of the record to a file in the
record root directory. The meta information includes the tool call ID and
the LLM inference ID.
Parameters:
None
Returns:
None
"""
with open(os.path.join(self.record_root_dir, "meta.meta"), "w", encoding="utf-8") as writer:
tool_call_log = {
"tool_call_id": self.tool_call_id,
"llm_inference_id": self.llm_interface_id,
}
json.dump(tool_call_log,writer,indent=2, ensure_ascii=False)
def load_from_disk(self, record_dir: str, cfg):
"""
Load data from disk into memory cache.
Args:
record_dir (str): The directory path where the data is stored.
cfg: The configuration object.
Returns:
None
"""
logger.typewriter_log(
"load from a disk record",
Fore.RED,
record_dir,
)
self.newly_start = False
for dir_name in os.listdir(record_dir):
if dir_name == "LLM_inout_pair":
inout_pair_list = os.listdir(os.path.join(record_dir,dir_name))
inout_pair_list.sort()
for file_name in inout_pair_list:
with open(os.path.join(record_dir,dir_name,file_name), "r", encoding="utf-8") as reader:
llm_pair = json.load(reader)
self.llm_record_cache.append(llm_pair)
elif dir_name == "meta.meta":
with open(os.path.join(record_dir, "meta.meta"), "r", encoding="utf-8") as reader:
tool_call_log = json.load(reader)
def regist_llm_inout(self, base_kwargs, messages, functions, function_call, stop, other_args, output_data, uuid=""):
"""
Registers the LLM input and output data for the specified function call.
Args:
base_kwargs (dict): The base keyword arguments for the function call.
messages (list): The list of messages associated with the function call.
functions (list): The list of functions called during the function call.
function_call (str): The function call being registered.
stop (bool): A flag indicating whether the function call should stop.
other_args (list): The list of other arguments for the function call.
output_data (Any): The output data for the function call.
uuid (str, optional): The UUID associated with the function call. Defaults to "".
Returns:
None
Raises:
None
"""
with open(os.path.join(self.record_root_dir, "LLM_inout_pair", f"{self.llm_interface_id:05d}.json"), "w", encoding="utf-8") as writer:
llm_inout_record = {
"input": {
"base_kwargs": dump_common_things(base_kwargs),
"messages":dump_common_things(messages),
"functions":dump_common_things(functions),
"function_call":dump_common_things(function_call),
"stop":dump_common_things(stop),
"other_args":dump_common_things(other_args),
# 'uuid': dump_common_things(uuid)
},
"output": dump_common_things(output_data),
"llm_interface_id": self.llm_interface_id,
}
json.dump(llm_inout_record,writer,indent=2, ensure_ascii=False)
self.llm_server_cache.append(llm_inout_record)
self.llm_interface_id += 1
self.save_meta()
def query_llm_inout(self, restrict_cache_query, base_kwargs, messages, functions, function_call, stop, other_args, uuid=""):
"""
Query the LLM server for input and output data based on the given parameters.
Parameters:
- restrict_cache_query (bool): Whether to restrict the cache query.
- base_kwargs (dict): A dictionary of base keyword arguments.
- messages (list): A list of messages.
- functions (list): A list of functions.
- function_call (dict): A dictionary representing the function call.
- stop (bool): Whether to stop the query.
- other_args (dict): A dictionary of other arguments.
- uuid (str): A string representing the UUID (optional).
Returns:
- object: The output data from the LLM server, or None if not found.
"""
if CONFIG.environment == ENVIRONMENT.Development or self.newly_start:
self.is_cached = False
return None
elif CONFIG.environment == ENVIRONMENT.Refine:
input_data = {
"base_kwargs": dump_common_things(base_kwargs),
"messages":dump_common_things(messages),
"functions":dump_common_things(functions),
"function_call":dump_common_things(function_call),
"stop":dump_common_things(stop),
"other_args":dump_common_things(other_args),
}
for cache in self.llm_record_cache:
# compare user messages only
input_data_user_messages = [item for item in input_data['messages'] if item['role'] == 'user']
cache_data_user_messages = [item for item in cache["input"]['messages'] if item['role'] == 'user']
if input_data_user_messages == cache_data_user_messages:
if restrict_cache_query and self.llm_interface_id != cache["llm_interface_id"]:
continue
logger.typewriter_log(
f"get a llm_server response from Record {cache['llm_interface_id']}",
Fore.RED,
)
self.is_cached = True
return cache["output"]
self.is_cached = False
return None
elif CONFIG.environment == ENVIRONMENT.Production:
if self.llm_interface_id < len(self.llm_record_cache):
logger.typewriter_log(
"get a llm_server response from Record",
Fore.RED,
)
self.is_cached = True
return self.llm_record_cache[self.llm_interface_id]['output']
else:
self.is_cached = False
return None
else:
self.is_cached = False
return None
| def regist_tool_call(self, action: Action, now_code: str): | 2 | 2023-11-03 01:20:14+00:00 | 4k |
LLaVA-VL/LLaVA-Plus-Codebase | llava/eval/run_llava.py | [
{
"identifier": "IMAGE_TOKEN_INDEX",
"path": "llava/constants.py",
"snippet": "IMAGE_TOKEN_INDEX = -200"
},
{
"identifier": "DEFAULT_IMAGE_TOKEN",
"path": "llava/constants.py",
"snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\""
},
{
"identifier": "DEFAULT_IM_START_TOKEN",
"path":... | import argparse
import torch
import requests
import re
from llava.constants import (
IMAGE_TOKEN_INDEX,
DEFAULT_IMAGE_TOKEN,
DEFAULT_IM_START_TOKEN,
DEFAULT_IM_END_TOKEN,
IMAGE_PLACEHOLDER,
)
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils import (
process_images,
tokenizer_image_token,
get_model_name_from_path,
KeywordsStoppingCriteria,
)
from PIL import Image
from PIL import Image
from io import BytesIO | 3,462 |
def image_parser(args):
out = args.image_file.split(args.sep)
return out
def load_image(image_file):
if image_file.startswith("http") or image_file.startswith("https"):
response = requests.get(image_file)
image = Image.open(BytesIO(response.content)).convert("RGB")
else:
image = Image.open(image_file).convert("RGB")
return image
def load_images(image_files):
out = []
for image_file in image_files:
image = load_image(image_file)
out.append(image)
return out
def eval_model(args):
# Model
disable_torch_init()
model_name = get_model_name_from_path(args.model_path)
tokenizer, model, image_processor, context_len = load_pretrained_model(
args.model_path, args.model_base, model_name
)
qs = args.query
|
def image_parser(args):
out = args.image_file.split(args.sep)
return out
def load_image(image_file):
if image_file.startswith("http") or image_file.startswith("https"):
response = requests.get(image_file)
image = Image.open(BytesIO(response.content)).convert("RGB")
else:
image = Image.open(image_file).convert("RGB")
return image
def load_images(image_files):
out = []
for image_file in image_files:
image = load_image(image_file)
out.append(image)
return out
def eval_model(args):
# Model
disable_torch_init()
model_name = get_model_name_from_path(args.model_path)
tokenizer, model, image_processor, context_len = load_pretrained_model(
args.model_path, args.model_base, model_name
)
qs = args.query | image_token_se = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN | 1 | 2023-11-07 13:06:02+00:00 | 4k |
opendilab/LLMRiddles | llmriddles/questions/level4.py | [
{
"identifier": "register_question",
"path": "llmriddles/questions/question.py",
"snippet": "def register_question(text: Union[Mapping[str, str], str],\n checkers: Union[Mapping[str, SingleLangCheckerTyping], MultiLangCheckerTyping],\n name=Union[Mapping[str, st... | import re
from .question import register_question
from .question import Checker
from typing import Callable
from .utility import count_words, word_reverse_text
from .math_tools import check_if_is_number, get_all_numbers
| 1,743 |
CN_TEXT_1 = """
第四章第一题(循环往复),请构造一个问题A,它的回复是不同于A的B,然后以B提问能再次得到A。
请在下面的输入框内填写你构造并点击按钮提交。
"""
EN_TEXT_1 = """
For the first question in chapter 4, please make a question A whose answer is B that is different from A, and then ask B to get A again.
Please enter your query below and click the submit button
"""
def _checker_1(question_text: str, user_text: str, answer_text: str, lang: str, llm_callback: Callable[[str], str]):
answer_text = answer_text.strip()
user_text = user_text.strip()
second_answer_text = llm_callback(answer_text)
if second_answer_text != user_text:
return False, f"B产生的回答和原问题A不一致:\n A: {user_text}\n B: {answer_text}\n Answer from B: {second_answer_text}" if lang == 'cn' else f'The answer from B is not the same as the original question A:\n A: {user_text}\n B: {answer_text}\n Answer from B: {second_answer_text}'
return True, None
register_question(
{
'cn': CN_TEXT_1,
'en': EN_TEXT_1,
},
checkers=Checker(_checker_1, required_input_keys=['question_text', 'user_text', 'answer_text', 'lang', 'llm_callback']),
name={'cn': '4-1 循环往复', 'en': '4-1'},
level=4,
)
CN_TEXT_2 = """
第四章第二题(惜字如金),本题可能没有答案,你可以自由的先去做其他的题。请输入一个字的问题,使模型的回答在16个字以内。
请在下面的输入框内填写你构造并点击按钮提交。
"""
EN_TEXT_2 = """
For the second question in chapter 4, please enter a question of one word so that the model's answer is within 16 words (The Chinese version of this problem may not have a correct answer, but the English version might).
Please enter your query below and click the submit button
"""
def _checker_2(question_text: str, user_text: str, answer_text: str, lang: str):
answer_text = answer_text.strip()
user_text = user_text.strip()
if count_words(user_text) > 1:
return False, "用户的问题长度应该在一个字以内" if lang == 'cn' else 'Question should be within one word.'
if count_words(answer_text) > 16:
return False, "大语言模型的答案应该在16个字以内" if lang == 'cn' else 'Answer should be within 16 words.'
else:
return True, None
register_question(
{
'cn': CN_TEXT_2,
'en': EN_TEXT_2,
},
checkers=_checker_2,
name={'cn': '4-2 惜字如金', 'en': '4-2'},
level=4,
)
CN_TEXT_3 = """
第四章第三题(自然之密),请输入一个大于一的正整数作为问题,使回答里包含和它刚好相差1的数。
请在下面的输入框内填写你构造并点击按钮提交。
"""
EN_TEXT_3 = """
For the third question in chapter 4, please enter a positive integer greater than one as the question so that the answer contains a number that is exactly 1 different from it.
Please enter your query below and click the submit button
"""
def _checker_3(question_text: str, user_text: str, answer_text: str, lang: str):
_ = question_text, lang
answer_text = answer_text.strip()
user_text = user_text.strip()
|
CN_TEXT_1 = """
第四章第一题(循环往复),请构造一个问题A,它的回复是不同于A的B,然后以B提问能再次得到A。
请在下面的输入框内填写你构造并点击按钮提交。
"""
EN_TEXT_1 = """
For the first question in chapter 4, please make a question A whose answer is B that is different from A, and then ask B to get A again.
Please enter your query below and click the submit button
"""
def _checker_1(question_text: str, user_text: str, answer_text: str, lang: str, llm_callback: Callable[[str], str]):
answer_text = answer_text.strip()
user_text = user_text.strip()
second_answer_text = llm_callback(answer_text)
if second_answer_text != user_text:
return False, f"B产生的回答和原问题A不一致:\n A: {user_text}\n B: {answer_text}\n Answer from B: {second_answer_text}" if lang == 'cn' else f'The answer from B is not the same as the original question A:\n A: {user_text}\n B: {answer_text}\n Answer from B: {second_answer_text}'
return True, None
register_question(
{
'cn': CN_TEXT_1,
'en': EN_TEXT_1,
},
checkers=Checker(_checker_1, required_input_keys=['question_text', 'user_text', 'answer_text', 'lang', 'llm_callback']),
name={'cn': '4-1 循环往复', 'en': '4-1'},
level=4,
)
CN_TEXT_2 = """
第四章第二题(惜字如金),本题可能没有答案,你可以自由的先去做其他的题。请输入一个字的问题,使模型的回答在16个字以内。
请在下面的输入框内填写你构造并点击按钮提交。
"""
EN_TEXT_2 = """
For the second question in chapter 4, please enter a question of one word so that the model's answer is within 16 words (The Chinese version of this problem may not have a correct answer, but the English version might).
Please enter your query below and click the submit button
"""
def _checker_2(question_text: str, user_text: str, answer_text: str, lang: str):
answer_text = answer_text.strip()
user_text = user_text.strip()
if count_words(user_text) > 1:
return False, "用户的问题长度应该在一个字以内" if lang == 'cn' else 'Question should be within one word.'
if count_words(answer_text) > 16:
return False, "大语言模型的答案应该在16个字以内" if lang == 'cn' else 'Answer should be within 16 words.'
else:
return True, None
register_question(
{
'cn': CN_TEXT_2,
'en': EN_TEXT_2,
},
checkers=_checker_2,
name={'cn': '4-2 惜字如金', 'en': '4-2'},
level=4,
)
CN_TEXT_3 = """
第四章第三题(自然之密),请输入一个大于一的正整数作为问题,使回答里包含和它刚好相差1的数。
请在下面的输入框内填写你构造并点击按钮提交。
"""
EN_TEXT_3 = """
For the third question in chapter 4, please enter a positive integer greater than one as the question so that the answer contains a number that is exactly 1 different from it.
Please enter your query below and click the submit button
"""
def _checker_3(question_text: str, user_text: str, answer_text: str, lang: str):
_ = question_text, lang
answer_text = answer_text.strip()
user_text = user_text.strip()
| if not check_if_is_number(user_text):
| 4 | 2023-11-07 03:09:55+00:00 | 4k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.